




import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
  import torch
  from torch import nn

  from transformers import (
      FocalNetBackbone,
      FocalNetForImageClassification,
      FocalNetForMaskedImageModeling,
      FocalNetModel,
  )
  from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor


class     UpperCamelCase_   :

    '''simple docstring'''






    def __init__(      self				:     int ,			UpperCAmelCase__				:     Optional[Any] ,			UpperCAmelCase__				:     Tuple=13 ,			UpperCAmelCase__				:     Dict=32 ,			UpperCAmelCase__				:     str=2 ,			UpperCAmelCase__				:     int=3 ,			UpperCAmelCase__				:     Union[str, Any]=16 ,			UpperCAmelCase__				:     List[str]=[32, 64, 128] ,			UpperCAmelCase__				:     Tuple=[1, 2, 1] ,			UpperCAmelCase__				:     Optional[int]=[2, 2, 4] ,			UpperCAmelCase__				:     Dict=2 ,			UpperCAmelCase__				:     Dict=2.0 ,			UpperCAmelCase__				:     List[Any]=True ,			UpperCAmelCase__				:     List[str]=0.0 ,			UpperCAmelCase__				:     int=0.0 ,			UpperCAmelCase__				:     Any=0.1 ,			UpperCAmelCase__				:     Tuple="gelu" ,			UpperCAmelCase__				:     List[Any]=False ,			UpperCAmelCase__				:     Any=True ,			UpperCAmelCase__				:     int=0.02 ,			UpperCAmelCase__				:     List[Any]=1e-5 ,			UpperCAmelCase__				:     List[Any]=True ,			UpperCAmelCase__				:     List[str]=None ,			UpperCAmelCase__				:     int=True ,			UpperCAmelCase__				:     int=10 ,			UpperCAmelCase__				:     Optional[int]=8 ,			UpperCAmelCase__				:     Tuple=["stage1", "stage2"] ,			UpperCAmelCase__				:     str=[1, 2] ,			)						->str:





           '''simple docstring'''

           A__							=   parent
           A__							=   batch_size
           A__							=   image_size
           A__							=   patch_size
           A__							=   num_channels
           A__							=   embed_dim
           A__							=   hidden_sizes
           A__							=   depths
           A__							=   num_heads
           A__							=   window_size
           A__							=   mlp_ratio
           A__							=   qkv_bias
           A__							=   hidden_dropout_prob
           A__							=   attention_probs_dropout_prob
           A__							=   drop_path_rate
           A__							=   hidden_act
           A__							=   use_absolute_embeddings
           A__							=   patch_norm
           A__							=   layer_norm_eps
           A__							=   initializer_range
           A__							=   is_training
           A__							=   scope
           A__							=   use_labels
           A__							=   type_sequence_label_size
           A__							=   encoder_stride
           A__							=   out_features
           A__							=   out_indices


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





           '''simple docstring'''

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

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

           A__							=   self.get_config()

           return config, pixel_values, labels


    def 	SCREAMING_SNAKE_CASE							(      self				:     Any)						->Any:





           '''simple docstring'''

           return FocalNetConfig(
               image_size=self.image_size ,			patch_size=self.patch_size ,			num_channels=self.num_channels ,			embed_dim=self.embed_dim ,			hidden_sizes=self.hidden_sizes ,			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 ,			out_features=self.out_features ,			out_indices=self.out_indices ,			)


    def 	SCREAMING_SNAKE_CASE							(      self				:     str ,			UpperCAmelCase__				:     Optional[int] ,			UpperCAmelCase__				:     int ,			UpperCAmelCase__				:     int)						->List[Any]:





           '''simple docstring'''

           A__							=   FocalNetModel(config=UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__							=   model(UpperCAmelCase__)

           A__							=   ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
           A__							=   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 	SCREAMING_SNAKE_CASE							(      self				:     Tuple ,			UpperCAmelCase__				:     Any ,			UpperCAmelCase__				:     int ,			UpperCAmelCase__				:     List[str])						->int:





           '''simple docstring'''

           A__							=   FocalNetBackbone(config=UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__							=   model(UpperCAmelCase__)

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps) ,			len(config.out_features))
           self.parent.assertListEqual(list(result.feature_maps[0].shape) ,			[self.batch_size, self.image_size, 8, 8])

           # verify channels
           self.parent.assertEqual(len(model.channels) ,			len(config.out_features))
           self.parent.assertListEqual(model.channels ,			config.hidden_sizes[:-1])

           # verify backbone works with out_features=None
           A__							=   None
           A__							=   FocalNetBackbone(config=UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__							=   model(UpperCAmelCase__)

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps) ,			1)
           self.parent.assertListEqual(list(result.feature_maps[0].shape) ,			[self.batch_size, self.image_size * 2, 4, 4])

           # verify channels
           self.parent.assertEqual(len(model.channels) ,			1)
           self.parent.assertListEqual(model.channels ,			[config.hidden_sizes[-1]])


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[Any] ,			UpperCAmelCase__				:     Tuple ,			UpperCAmelCase__				:     List[Any] ,			UpperCAmelCase__				:     List[Any])						->Optional[Any]:





           '''simple docstring'''

           A__							=   FocalNetForMaskedImageModeling(config=UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__							=   model(UpperCAmelCase__)
           self.parent.assertEqual(
               result.reconstruction.shape ,			(self.batch_size, self.num_channels, self.image_size, self.image_size))

           # test greyscale images
           A__							=   1
           A__							=   FocalNetForMaskedImageModeling(UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()

           A__							=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
           A__							=   model(UpperCAmelCase__)
           self.parent.assertEqual(result.reconstruction.shape ,			(self.batch_size, 1, self.image_size, self.image_size))


    def 	SCREAMING_SNAKE_CASE							(      self				:     str ,			UpperCAmelCase__				:     int ,			UpperCAmelCase__				:     Union[str, Any] ,			UpperCAmelCase__				:     Any)						->Union[str, Any]:





           '''simple docstring'''

           A__							=   self.type_sequence_label_size
           A__							=   FocalNetForImageClassification(UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__							=   model(UpperCAmelCase__ ,			labels=UpperCAmelCase__)
           self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.type_sequence_label_size))

           # test greyscale images
           A__							=   1
           A__							=   FocalNetForImageClassification(UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()

           A__							=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
           A__							=   model(UpperCAmelCase__)
           self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.type_sequence_label_size))





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





           '''simple docstring'''

           A__							=   self.prepare_config_and_inputs()

           A__			,							A__			,							A__							=   config_and_inputs
           A__							=   {'''pixel_values''': pixel_values}
           return config, inputs_dict


@require_torch
class     UpperCamelCase_   (			UpperCAmelCase__		, UpperCAmelCase__		, unittest.TestCase					):

    '''simple docstring'''






    UpperCAmelCase__							  =				(
        (
            FocalNetModel,
            FocalNetForImageClassification,
            FocalNetForMaskedImageModeling,
            FocalNetBackbone,
        )
        if is_torch_available()
        else ()
    )
    UpperCAmelCase__							  =				(
        {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
        if is_torch_available()
        else {}
    )
    UpperCAmelCase__							  =				False

    UpperCAmelCase__							  =				False
    UpperCAmelCase__							  =				False
    UpperCAmelCase__							  =				False
    UpperCAmelCase__							  =				False


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[Any])						->str:





           '''simple docstring'''

           A__							=   FocalNetModelTester(self)
           A__							=   ConfigTester(self ,			config_class=UpperCAmelCase__ ,			embed_dim=37 ,			has_text_modality=UpperCAmelCase__)


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





           '''simple docstring'''

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


    def 	SCREAMING_SNAKE_CASE							(      self				:     Any)						->str:





           '''simple docstring'''

           return


    def 	SCREAMING_SNAKE_CASE							(      self				:     Dict)						->Any:





           '''simple docstring'''

           A__							=   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase__)


    def 	SCREAMING_SNAKE_CASE							(      self				:     Tuple)						->str:





           '''simple docstring'''

           A__							=   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*UpperCAmelCase__)


    def 	SCREAMING_SNAKE_CASE							(      self				:     Dict)						->int:





           '''simple docstring'''

           A__							=   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase__)


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





           '''simple docstring'''

           A__							=   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__)


    @unittest.skip(reason='''FocalNet does not use inputs_embeds''')
    def 	SCREAMING_SNAKE_CASE							(      self				:     Tuple)						->str:





           '''simple docstring'''

           pass


    @unittest.skip(reason='''FocalNet does not use feedforward chunking''')
    def 	SCREAMING_SNAKE_CASE							(      self				:     Union[str, Any])						->Tuple:





           '''simple docstring'''

           pass


    def 	SCREAMING_SNAKE_CASE							(      self				:     int)						->List[Any]:





           '''simple docstring'''

           A__			,							A__							=   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes[:-1]:
                  A__							=   model_class(UpperCAmelCase__)
                  self.assertIsInstance(model.get_input_embeddings() ,			(nn.Module))
                  A__							=   model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(UpperCAmelCase__ ,			nn.Linear))


    def 	SCREAMING_SNAKE_CASE							(      self				:     str)						->Optional[Any]:





           '''simple docstring'''

           A__			,							A__							=   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes[:-1]:
                  A__							=   model_class(UpperCAmelCase__)
                  A__							=   inspect.signature(model.forward)
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  A__							=   [*signature.parameters.keys()]

                  A__							=   ['''pixel_values''']
                  self.assertListEqual(arg_names[:1] ,			UpperCAmelCase__)


    def 	SCREAMING_SNAKE_CASE							(      self				:     Any ,			UpperCAmelCase__				:     int ,			UpperCAmelCase__				:     Dict ,			UpperCAmelCase__				:     Union[str, Any] ,			UpperCAmelCase__				:     str)						->int:





           '''simple docstring'''

           A__							=   model_class(UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()

           with torch.no_grad():
                  A__							=   model(**self._prepare_for_class(UpperCAmelCase__ ,			UpperCAmelCase__))

           A__							=   outputs.hidden_states

           A__							=   getattr(
               self.model_tester ,			'''expected_num_hidden_layers''' ,			len(self.model_tester.depths) + 1)
           self.assertEqual(len(UpperCAmelCase__) ,			UpperCAmelCase__)

           # FocalNet has a different seq_length
           A__							=   (
               config.patch_size
               if isinstance(config.patch_size ,			collections.abc.Iterable)
               else (config.patch_size, config.patch_size)
           )

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

           A__							=   outputs.reshaped_hidden_states
           self.assertEqual(len(UpperCAmelCase__) ,			UpperCAmelCase__)

           A__			,							A__			,							A__			,							A__							=   reshaped_hidden_states[0].shape
           A__							=   (
               reshaped_hidden_states[0].view(UpperCAmelCase__ ,			UpperCAmelCase__ ,			height * width).permute(0 ,			2 ,			1)
           )
           self.assertListEqual(
               list(reshaped_hidden_states.shape[-2:]) ,			[num_patches, self.model_tester.embed_dim] ,			)


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





           '''simple docstring'''

           A__			,							A__							=   self.model_tester.prepare_config_and_inputs_for_common()

           A__							=   (
               self.model_tester.image_size
               if isinstance(self.model_tester.image_size ,			collections.abc.Iterable)
               else (self.model_tester.image_size, self.model_tester.image_size)
           )

           for model_class in self.all_model_classes[:-1]:
                  A__							=   True
                  self.check_hidden_states_output(UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__)

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

                  self.check_hidden_states_output(UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__)


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[Any])						->str:





           '''simple docstring'''

           A__			,							A__							=   self.model_tester.prepare_config_and_inputs_for_common()
           A__							=   3

           A__							=   (
               self.model_tester.image_size
               if isinstance(self.model_tester.image_size ,			collections.abc.Iterable)
               else (self.model_tester.image_size, self.model_tester.image_size)
           )
           A__							=   (
               config.patch_size
               if isinstance(config.patch_size ,			collections.abc.Iterable)
               else (config.patch_size, config.patch_size)
           )

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

           for model_class in self.all_model_classes[:-1]:
                  A__							=   True
                  self.check_hidden_states_output(UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			(padded_height, padded_width))

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


    @slow
    def 	SCREAMING_SNAKE_CASE							(      self				:     Tuple)						->List[Any]:





           '''simple docstring'''

           for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A__							=   FocalNetModel.from_pretrained(UpperCAmelCase__)
                  self.assertIsNotNone(UpperCAmelCase__)





    def 	SCREAMING_SNAKE_CASE							(      self				:     Any)						->Optional[Any]:





           '''simple docstring'''

           A__			,							A__							=   self.model_tester.prepare_config_and_inputs_for_common()

           A__							=   _config_zero_init(UpperCAmelCase__)
           for model_class in self.all_model_classes:
                  A__							=   model_class(config=UpperCAmelCase__)
                  for name, param in model.named_parameters():
                         if "embeddings" not in name and param.requires_grad:
                                self.assertIn(
                                    ((param.data.mean() * 1e9).round() / 1e9).item() ,			[0.0, 1.0] ,			msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" ,			)


@require_vision
@require_torch
class     UpperCamelCase_   (			unittest.TestCase					):

    '''simple docstring'''






    @cached_property
    def 	SCREAMING_SNAKE_CASE							(      self				:     str)						->str:





           '''simple docstring'''

           return AutoImageProcessor.from_pretrained('''microsoft/focalnet-tiny''') if is_vision_available() else None





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





           '''simple docstring'''

           A__							=   FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny''').to(UpperCAmelCase__)
           A__							=   self.default_image_processor

           A__							=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
           A__							=   image_processor(images=UpperCAmelCase__ ,			return_tensors='''pt''').to(UpperCAmelCase__)

           # forward pass
           with torch.no_grad():
                  A__							=   model(**UpperCAmelCase__)

           # verify the logits
           A__							=   torch.Size((1, 1_000))
           self.assertEqual(outputs.logits.shape ,			UpperCAmelCase__)
           A__							=   torch.tensor([0.2166, -0.4368, 0.2191]).to(UpperCAmelCase__)
           self.assertTrue(torch.allclose(outputs.logits[0, :3] ,			UpperCAmelCase__ ,			atol=1e-4))
           self.assertTrue(outputs.logits.argmax(dim=-1).item() ,			281)


@require_torch
class     UpperCamelCase_   (			UpperCAmelCase__		, unittest.TestCase					):

    '''simple docstring'''






    UpperCAmelCase__							  =				(FocalNetBackbone,) if is_torch_available() else ()
    UpperCAmelCase__							  =				FocalNetConfig

    UpperCAmelCase__							  =				False


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





           '''simple docstring'''

           A__							=   FocalNetModelTester(self)








import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, 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.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel

if is_torch_available():
  import torch


class     UpperCamelCase_   :

    '''simple docstring'''






    def __init__(      self				:     str ,			UpperCAmelCase__				:     List[Any] ,			UpperCAmelCase__				:     Any=14 ,			UpperCAmelCase__				:     Any=7 ,			UpperCAmelCase__				:     Dict=True ,			UpperCAmelCase__				:     int=True ,			UpperCAmelCase__				:     Tuple=False ,			UpperCAmelCase__				:     Optional[int]=True ,			UpperCAmelCase__				:     Tuple=99 ,			UpperCAmelCase__				:     Optional[Any]=32 ,			UpperCAmelCase__				:     Tuple=4 ,			UpperCAmelCase__				:     Any=4 ,			UpperCAmelCase__				:     int=4 ,			UpperCAmelCase__				:     Optional[Any]=37 ,			UpperCAmelCase__				:     Union[str, Any]="gelu" ,			UpperCAmelCase__				:     Optional[int]=0.1 ,			UpperCAmelCase__				:     int=0.1 ,			UpperCAmelCase__				:     Optional[Any]=512 ,			UpperCAmelCase__				:     Union[str, Any]=0.02 ,			)						->Any:





           '''simple docstring'''

           A__							=   parent
           A__							=   batch_size
           A__							=   seq_length
           A__							=   is_training
           A__							=   use_input_mask
           A__							=   use_token_type_ids
           A__							=   use_labels
           A__							=   vocab_size
           A__							=   hidden_size
           A__							=   rotary_dim
           A__							=   num_hidden_layers
           A__							=   num_attention_heads
           A__							=   intermediate_size
           A__							=   hidden_act
           A__							=   hidden_dropout_prob
           A__							=   attention_probs_dropout_prob
           A__							=   max_position_embeddings
           A__							=   initializer_range
           A__							=   None
           A__							=   vocab_size - 1
           A__							=   vocab_size - 1
           A__							=   vocab_size - 1


    def 	SCREAMING_SNAKE_CASE							(      self				:     List[str])						->List[str]:





           '''simple docstring'''

           A__							=   ids_tensor([self.batch_size, self.seq_length] ,			self.vocab_size)

           A__							=   None
           if self.use_input_mask:
                  A__							=   random_attention_mask([self.batch_size, self.seq_length])

           A__							=   GPTJConfig(
               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=UpperCAmelCase__ ,			bos_token_id=self.bos_token_id ,			eos_token_id=self.eos_token_id ,			pad_token_id=self.pad_token_id ,			rotary_dim=self.rotary_dim ,			)

           return (config, input_ids, input_mask)


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





           '''simple docstring'''

           A__							=   self.prepare_config_and_inputs()
           A__			,							A__			,							A__							=   config_and_inputs
           A__							=   {'''input_ids''': input_ids, '''attention_mask''': attention_mask}
           return config, inputs_dict


    def 	SCREAMING_SNAKE_CASE							(      self				:     Any ,			UpperCAmelCase__				:     int ,			UpperCAmelCase__				:     Tuple ,			UpperCAmelCase__				:     Union[str, Any] ,			UpperCAmelCase__				:     List[Any])						->Optional[int]:





           '''simple docstring'''

           A__							=   20
           A__							=   model_class_name(UpperCAmelCase__)

           A__							=   model.init_cache(input_ids.shape[0] ,			UpperCAmelCase__)
           A__							=   jnp.ones((input_ids.shape[0], max_decoder_length) ,			dtype='''i4''')

           A__							=   jnp.broadcast_to(
               jnp.arange(input_ids.shape[-1] - 1)[None, :] ,			(input_ids.shape[0], input_ids.shape[-1] - 1))
           A__							=   model(
               input_ids[:, :-1] ,			attention_mask=UpperCAmelCase__ ,			past_key_values=UpperCAmelCase__ ,			position_ids=UpperCAmelCase__ ,			)

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

           A__							=   model(UpperCAmelCase__)

           A__							=   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				:     Tuple ,			UpperCAmelCase__				:     Optional[Any] ,			UpperCAmelCase__				:     Dict ,			UpperCAmelCase__				:     List[Any] ,			UpperCAmelCase__				:     int)						->Any:





           '''simple docstring'''

           A__							=   20
           A__							=   model_class_name(UpperCAmelCase__)

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

           A__							=   model.init_cache(input_ids.shape[0] ,			UpperCAmelCase__)
           A__							=   jnp.broadcast_to(
               jnp.arange(input_ids.shape[-1] - 1)[None, :] ,			(input_ids.shape[0], input_ids.shape[-1] - 1))

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

           A__							=   model(UpperCAmelCase__ ,			attention_mask=UpperCAmelCase__)

           A__							=   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     UpperCamelCase_   (			UpperCAmelCase__		, UpperCAmelCase__		, unittest.TestCase					):

    '''simple docstring'''






    UpperCAmelCase__							  =				(FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
    UpperCAmelCase__							  =				(FlaxGPTJForCausalLM,) if is_flax_available() else ()


    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[Any])						->List[Any]:





           '''simple docstring'''

           A__							=   FlaxGPTJModelTester(self)


    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[Any])						->Any:





           '''simple docstring'''

           for model_class_name in self.all_model_classes:
                  A__			,							A__			,							A__							=   self.model_tester.prepare_config_and_inputs()
                  self.model_tester.check_use_cache_forward(UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__)


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





           '''simple docstring'''

           for model_class_name in self.all_model_classes:
                  A__			,							A__			,							A__							=   self.model_tester.prepare_config_and_inputs()
                  self.model_tester.check_use_cache_forward_with_attn_mask(
                      UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__ ,			UpperCAmelCase__)


    @tooslow
    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[Any])						->Dict:





           '''simple docstring'''

           A__							=   GPTaTokenizer.from_pretrained('''gpt2''' ,			pad_token='''<|endoftext|>''' ,			padding_side='''left''')
           A__							=   tokenizer(['''Hello this is a long string''', '''Hey'''] ,			return_tensors='''np''' ,			padding=UpperCAmelCase__ ,			truncation=UpperCAmelCase__)

           A__							=   FlaxGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B''')
           A__							=   False
           A__							=   model.config.eos_token_id

           A__							=   jax.jit(model.generate)

           A__							=   jit_generate(
               inputs['''input_ids'''] ,			attention_mask=inputs['''attention_mask'''] ,			pad_token_id=tokenizer.pad_token_id).sequences

           A__							=   tokenizer.batch_decode(UpperCAmelCase__ ,			skip_special_tokens=UpperCAmelCase__)

           A__							=   [
               '''Hello this is a long string of text.\n\nI\'m trying to get the text of the''',
               '''Hey, I\'m a little late to the party. I\'m going to''',
           ]

           self.assertListEqual(UpperCAmelCase__ ,			UpperCAmelCase__)


    @is_pt_flax_cross_test
    def 	SCREAMING_SNAKE_CASE							(      self				:     Optional[int])						->int:





           '''simple docstring'''

           A__			,							A__							=   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
                         A__							=   self._prepare_for_class(UpperCAmelCase__ ,			UpperCAmelCase__)
                         A__							=   {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()}

                         # load corresponding PyTorch class
                         A__							=   model_class.__name__[4:]  # Skip the "Flax" at the beginning
                         A__							=   getattr(UpperCAmelCase__ ,			UpperCAmelCase__)

                         A__			,							A__							=   pt_inputs['''input_ids'''].shape
                         A__							=   np.random.randint(0 ,			seq_length - 1 ,			size=(batch_size,))
                         for batch_idx, start_index in enumerate(UpperCAmelCase__):
                                A__							=   0
                                A__							=   1
                                A__							=   0
                                A__							=   1
                         A__							=   pt_model_class(UpperCAmelCase__).eval()
                         A__							=   model_class(UpperCAmelCase__ ,			dtype=jnp.floataa)

                         A__							=   convert_pytorch_state_dict_to_flax(pt_model.state_dict() ,			UpperCAmelCase__)
                         A__							=   fx_state

                         with torch.no_grad():
                                A__							=   pt_model(**UpperCAmelCase__).to_tuple()

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

                         with tempfile.TemporaryDirectory() as tmpdirname:
                                pt_model.save_pretrained(UpperCAmelCase__)
                                A__							=   model_class.from_pretrained(UpperCAmelCase__ ,			from_pt=UpperCAmelCase__)

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


    @is_pt_flax_cross_test
    def 	SCREAMING_SNAKE_CASE							(      self				:     Any)						->Optional[int]:





           '''simple docstring'''

           A__			,							A__							=   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
                         A__							=   self._prepare_for_class(UpperCAmelCase__ ,			UpperCAmelCase__)
                         A__							=   {k: torch.tensor(v.tolist()) for k, v in prepared_inputs_dict.items()}

                         # load corresponding PyTorch class
                         A__							=   model_class.__name__[4:]  # Skip the "Flax" at the beginning
                         A__							=   getattr(UpperCAmelCase__ ,			UpperCAmelCase__)

                         A__							=   pt_model_class(UpperCAmelCase__).eval()
                         A__							=   model_class(UpperCAmelCase__ ,			dtype=jnp.floataa)

                         A__							=   load_flax_weights_in_pytorch_model(UpperCAmelCase__ ,			fx_model.params)
                         A__			,							A__							=   pt_inputs['''input_ids'''].shape
                         A__							=   np.random.randint(0 ,			seq_length - 1 ,			size=(batch_size,))
                         for batch_idx, start_index in enumerate(UpperCAmelCase__):
                                A__							=   0
                                A__							=   1
                                A__							=   0
                                A__							=   1

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

                         with torch.no_grad():
                                A__							=   pt_model(**UpperCAmelCase__).to_tuple()

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

                         with tempfile.TemporaryDirectory() as tmpdirname:
                                fx_model.save_pretrained(UpperCAmelCase__)
                                A__							=   pt_model_class.from_pretrained(UpperCAmelCase__ ,			from_flax=UpperCAmelCase__)

                         with torch.no_grad():
                                A__							=   pt_model_loaded(**UpperCAmelCase__).to_tuple()

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





    @tooslow
    def 	SCREAMING_SNAKE_CASE							(      self				:     Tuple)						->Optional[Any]:





           '''simple docstring'''

           for model_class_name in self.all_model_classes:
                  A__							=   model_class_name.from_pretrained('''EleutherAI/gpt-j-6B''')
                  A__							=   model(np.ones((1, 1)))
                  self.assertIsNotNone(UpperCAmelCase__)


