




from __future__ import annotations

import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module

import numpy as np

from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow

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 import TFViTMAEForPreTraining, TFViTMAEModel


if is_vision_available():
  from PIL import Image

  from transformers import ViTImageProcessor
class 	_UpperCamelCase					:
      def __init__(	self      :int       ,					lowerCamelCase      :Tuple       ,					lowerCamelCase      :Optional[int]=13       ,					lowerCamelCase      :Union[str, Any]=30       ,					lowerCamelCase      :List[Any]=2       ,					lowerCamelCase      :Tuple=3       ,					lowerCamelCase      :Tuple=True       ,					lowerCamelCase      :Optional[int]=True       ,					lowerCamelCase      :Optional[Any]=32       ,					lowerCamelCase      :Optional[Any]=2       ,					lowerCamelCase      :List[Any]=4       ,					lowerCamelCase      :Tuple=37       ,					lowerCamelCase      :List[Any]="gelu"       ,					lowerCamelCase      :List[str]=0.1       ,					lowerCamelCase      :List[str]=0.1       ,					lowerCamelCase      :int=10       ,					lowerCamelCase      :Tuple=0.02       ,					lowerCamelCase      :Optional[int]=3       ,					lowerCamelCase      :Dict=0.6       ,					lowerCamelCase      :int=None       ,					)   ->	List[str]:
       UpperCAmelCase__							       =  parent
       UpperCAmelCase__							       =  batch_size
       UpperCAmelCase__							       =  image_size
       UpperCAmelCase__							       =  patch_size
       UpperCAmelCase__							       =  num_channels
       UpperCAmelCase__							       =  is_training
       UpperCAmelCase__							       =  use_labels
       UpperCAmelCase__							       =  hidden_size
       UpperCAmelCase__							       =  num_hidden_layers
       UpperCAmelCase__							       =  num_attention_heads
       UpperCAmelCase__							       =  intermediate_size
       UpperCAmelCase__							       =  hidden_act
       UpperCAmelCase__							       =  hidden_dropout_prob
       UpperCAmelCase__							       =  attention_probs_dropout_prob
       UpperCAmelCase__							       =  type_sequence_label_size
       UpperCAmelCase__							       =  initializer_range
       UpperCAmelCase__							       =  mask_ratio
       UpperCAmelCase__							       =  scope

       # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
       # (we add 1 for the [CLS] token)
       UpperCAmelCase__							       =  (image_size // patch_size) ** 2
       UpperCAmelCase__							       =  int(math.ceil((1 - mask_ratio) * (num_patches + 1)					)					)
      def 		UpperCAmelCase_  (	self      :Tuple					)   ->	Optional[Any]:
       UpperCAmelCase__							       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

       UpperCAmelCase__							       =  self.get_config()

       return config, pixel_values, labels
      def 		UpperCAmelCase_  (	self      :str					)   ->	List[str]:
       return ViTMAEConfig(
           image_size=self.image_size       ,					patch_size=self.patch_size       ,					num_channels=self.num_channels       ,					hidden_size=self.hidden_size       ,					num_hidden_layers=self.num_hidden_layers       ,					num_attention_heads=self.num_attention_heads       ,					intermediate_size=self.intermediate_size       ,					decoder_hidden_size=self.hidden_size       ,					decoder_num_hidden_layers=self.num_hidden_layers       ,					decoder_num_attention_heads=self.num_attention_heads       ,					decoder_intermediate_size=self.intermediate_size       ,					hidden_act=self.hidden_act       ,					hidden_dropout_prob=self.hidden_dropout_prob       ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,					is_decoder=UpperCamelCase_       ,					initializer_range=self.initializer_range       ,					mask_ratio=self.mask_ratio       ,					)
      def 		UpperCAmelCase_  (	self      :Optional[int]       ,					lowerCamelCase      :Union[str, Any]       ,					lowerCamelCase      :Dict       ,					lowerCamelCase      :Optional[Any]					)   ->	List[Any]:
       UpperCAmelCase__							       =  TFViTMAEModel(config=UpperCamelCase_					)
       UpperCAmelCase__							       =  model(UpperCamelCase_       ,					training=UpperCamelCase_					)
       self.parent.assertEqual(result.last_hidden_state.shape       ,					(self.batch_size, self.seq_length, self.hidden_size)					)
      def 		UpperCAmelCase_  (	self      :Optional[int]       ,					lowerCamelCase      :int       ,					lowerCamelCase      :str       ,					lowerCamelCase      :int					)   ->	Any:
       UpperCAmelCase__							       =  TFViTMAEForPreTraining(UpperCamelCase_					)
       UpperCAmelCase__							       =  model(UpperCamelCase_       ,					training=UpperCamelCase_					)
       # expected sequence length = num_patches
       UpperCAmelCase__							       =  (self.image_size // self.patch_size) ** 2
       UpperCAmelCase__							       =  self.patch_size**2 * self.num_channels
       self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, num_patches, expected_num_channels)					)

       # test greyscale images
       UpperCAmelCase__							       =  1
       UpperCAmelCase__							       =  TFViTMAEForPreTraining(UpperCamelCase_					)

       UpperCAmelCase__							       =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
       UpperCAmelCase__							       =  model(UpperCamelCase_       ,					training=UpperCamelCase_					)
       UpperCAmelCase__							       =  self.patch_size**2
       self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, num_patches, expected_num_channels)					)







      def 		UpperCAmelCase_  (	self      :Tuple					)   ->	Union[str, Any]:
       UpperCAmelCase__							       =  self.prepare_config_and_inputs()
       ((UpperCAmelCase__)       ,       (UpperCAmelCase__)       ,       (UpperCAmelCase__))							       =  config_and_inputs
       UpperCAmelCase__							       =  {"pixel_values": pixel_values}
       return config, inputs_dict



@require_tf
class 	_UpperCamelCase					( UpperCamelCase__		,				UpperCamelCase__		,				unittest.TestCase						):
      UpperCAmelCase_						=						(TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
      UpperCAmelCase_						=						{'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {}

      UpperCAmelCase_						=						False
      UpperCAmelCase_						=						False
      UpperCAmelCase_						=						False
      UpperCAmelCase_						=						False
      def 		UpperCAmelCase_  (	self      :List[str]					)   ->	Union[str, Any]:
       UpperCAmelCase__							       =  TFViTMAEModelTester(self					)
       UpperCAmelCase__							       =  ConfigTester(self       ,					config_class=UpperCamelCase_       ,					has_text_modality=UpperCamelCase_       ,					hidden_size=37					)
      def 		UpperCAmelCase_  (	self      :Union[str, Any]					)   ->	str:
       self.config_tester.run_common_tests()
      @unittest.skip(reason="ViTMAE does not use inputs_embeds"					)
      def 		UpperCAmelCase_  (	self      :int					)   ->	Tuple:
       pass
      def 		UpperCAmelCase_  (	self      :int					)   ->	Tuple:
       UpperCAmelCase__       ,       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCAmelCase__							       =  model_class(UpperCamelCase_					)
        self.assertIsInstance(model.get_input_embeddings()       ,					(tf.keras.layers.Layer)					)
        UpperCAmelCase__							       =  model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(UpperCamelCase_       ,					tf.keras.layers.Layer					)					)
      def 		UpperCAmelCase_  (	self      :Union[str, Any]					)   ->	Tuple:
       UpperCAmelCase__       ,       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCAmelCase__							       =  ["pixel_values"]
        self.assertListEqual(arg_names[:1]       ,					UpperCamelCase_					)
      def 		UpperCAmelCase_  (	self      :List[Any]					)   ->	List[str]:
       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase_					)
      def 		UpperCAmelCase_  (	self      :Tuple					)   ->	Any:
       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_pretraining(*UpperCamelCase_					)
      def 		UpperCAmelCase_  (	self      :Union[str, Any]					)   ->	str:
       np.random.seed(2					)

       UpperCAmelCase__       ,       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs_for_common()

       UpperCAmelCase__							       =  int((config.image_size // config.patch_size) ** 2					)
       UpperCAmelCase__							       =  np.random.uniform(size=(self.model_tester.batch_size, num_patches)					)

       for model_class in self.all_model_classes:
        UpperCAmelCase__							       =  model_class(UpperCamelCase_					)
        UpperCAmelCase__							       =  self._prepare_for_class(UpperCamelCase_       ,					UpperCamelCase_					)

        UpperCAmelCase__							       =  model(UpperCamelCase_       ,					noise=UpperCamelCase_					)

        UpperCAmelCase__							       =  copy.deepcopy(self._prepare_for_class(UpperCamelCase_       ,					UpperCamelCase_					)					)
        UpperCAmelCase__							       =  model(**UpperCamelCase_       ,					noise=UpperCamelCase_					)
        UpperCAmelCase__							       =  outputs_dict[0].numpy()
        UpperCAmelCase__							       =  outputs_keywords[0].numpy()

        self.assertLess(np.sum(np.abs(output_dict - output_keywords					)					)       ,					1e-6					)
      def 		UpperCAmelCase_  (	self      :Dict					)   ->	Tuple:
       np.random.seed(2					)

       UpperCAmelCase__       ,       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs_for_common()

       UpperCAmelCase__							       =  int((config.image_size // config.patch_size) ** 2					)
       UpperCAmelCase__							       =  np.random.uniform(size=(self.model_tester.batch_size, num_patches)					)

       def prepare_numpy_arrays(lowerCamelCase      :Union[str, Any]					):
        UpperCAmelCase__							       =  {}
        for k, v in inputs_dict.items():
         if tf.is_tensor(UpperCamelCase_					):
          UpperCAmelCase__							       =  v.numpy()
         else:
          UpperCAmelCase__							       =  np.array(UpperCamelCase_					)

        return inputs_np_dict

       for model_class in self.all_model_classes:
        UpperCAmelCase__							       =  model_class(UpperCamelCase_					)

        UpperCAmelCase__							       =  self._prepare_for_class(UpperCamelCase_       ,					UpperCamelCase_					)
        UpperCAmelCase__							       =  prepare_numpy_arrays(UpperCamelCase_					)

        UpperCAmelCase__							       =  model(UpperCamelCase_       ,					noise=UpperCamelCase_					)
        UpperCAmelCase__							       =  model(**UpperCamelCase_       ,					noise=UpperCamelCase_					)
        self.assert_outputs_same(UpperCamelCase_       ,					UpperCamelCase_					)
      def 		UpperCAmelCase_  (	self      :str       ,					lowerCamelCase      :Tuple       ,					lowerCamelCase      :List[str]       ,					lowerCamelCase      :List[Any]					)   ->	Union[str, Any]:
       np.random.seed(2					)

       UpperCAmelCase__							       =  int((tf_model.config.image_size // tf_model.config.patch_size) ** 2					)
       UpperCAmelCase__							       =  np.random.uniform(size=(self.model_tester.batch_size, num_patches)					)
       UpperCAmelCase__							       =  tf.constant(UpperCamelCase_					)

       # Add `noise` argument.
       # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
       UpperCAmelCase__							       =  tf_noise

       super().check_pt_tf_models(UpperCamelCase_       ,					UpperCamelCase_       ,					UpperCamelCase_					)
      def 		UpperCAmelCase_  (	self      :str					)   ->	int:
       np.random.seed(2					)

       UpperCAmelCase__       ,       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs_for_common()

       UpperCAmelCase__							       =  {
           module_member
           for model_class in self.all_model_classes
           for module in (import_module(model_class.__module__					),)
           for module_member_name in dir(UpperCamelCase_					)
           if module_member_name.endswith("MainLayer"					)
           # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
           and module_member_name[: -len("MainLayer"					)] == model_class.__name__[: -len("Model"					)]
           for module_member in (getattr(UpperCamelCase_       ,					UpperCamelCase_					),)
           if isinstance(UpperCamelCase_       ,					UpperCamelCase_					)
           and tf.keras.layers.Layer in module_member.__bases__
           and getattr(UpperCamelCase_       ,					"_keras_serializable"       ,					UpperCamelCase_					)
       }

       UpperCAmelCase__							       =  int((config.image_size // config.patch_size) ** 2					)
       UpperCAmelCase__							       =  np.random.uniform(size=(self.model_tester.batch_size, num_patches)					)
       UpperCAmelCase__							       =  tf.convert_to_tensor(UpperCamelCase_					)
       inputs_dict.update({"noise": noise}					)

       for main_layer_class in tf_main_layer_classes:
        UpperCAmelCase__							       =  main_layer_class(UpperCamelCase_					)

        UpperCAmelCase__							       =  {
            name: tf.keras.Input(tensor.shape[1:]       ,					dtype=tensor.dtype					) for name, tensor in inputs_dict.items()
        }

        UpperCAmelCase__							       =  tf.keras.Model(UpperCamelCase_       ,					outputs=main_layer(UpperCamelCase_					)					)
        UpperCAmelCase__							       =  model(UpperCamelCase_					)

        with tempfile.TemporaryDirectory() as tmpdirname:
         UpperCAmelCase__							       =  os.path.join(UpperCamelCase_       ,					"keras_model.h5"					)
         model.save(UpperCamelCase_					)
         UpperCAmelCase__							       =  tf.keras.models.load_model(
             UpperCamelCase_       ,					custom_objects={main_layer_class.__name__: main_layer_class}					)
         assert isinstance(UpperCamelCase_       ,					tf.keras.Model					)
         UpperCAmelCase__							       =  model(UpperCamelCase_					)
         self.assert_outputs_same(UpperCamelCase_       ,					UpperCamelCase_					)
      @slow
      def 		UpperCAmelCase_  (	self      :Optional[int]					)   ->	Tuple:
       np.random.seed(2					)

       UpperCAmelCase__       ,       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs_for_common()

       UpperCAmelCase__							       =  int((config.image_size // config.patch_size) ** 2					)
       UpperCAmelCase__							       =  np.random.uniform(size=(self.model_tester.batch_size, num_patches)					)

       for model_class in self.all_model_classes:
        UpperCAmelCase__							       =  model_class(UpperCamelCase_					)
        UpperCAmelCase__							       =  self._prepare_for_class(UpperCamelCase_       ,					UpperCamelCase_					)
        UpperCAmelCase__							       =  model(UpperCamelCase_       ,					noise=UpperCamelCase_					)

        if model_class.__name__ == "TFViTMAEModel":
         UpperCAmelCase__							       =  outputs.last_hidden_state.numpy()
         UpperCAmelCase__							       =  0
        else:
         UpperCAmelCase__							       =  outputs.logits.numpy()
         UpperCAmelCase__							       =  0

        with tempfile.TemporaryDirectory() as tmpdirname:
         model.save_pretrained(UpperCamelCase_       ,					saved_model=UpperCamelCase_					)
         UpperCAmelCase__							       =  model_class.from_pretrained(UpperCamelCase_					)
         UpperCAmelCase__							       =  model(UpperCamelCase_       ,					noise=UpperCamelCase_					)

         if model_class.__name__ == "TFViTMAEModel":
          UpperCAmelCase__							       =  after_outputs["last_hidden_state"].numpy()
          UpperCAmelCase__							       =  0
         else:
          UpperCAmelCase__							       =  after_outputs["logits"].numpy()
          UpperCAmelCase__							       =  0

         UpperCAmelCase__							       =  np.amax(np.abs(out_a - out_a					)					)
         self.assertLessEqual(UpperCamelCase_       ,					1e-5					)
      def 		UpperCAmelCase_  (	self      :Union[str, Any]					)   ->	int:
       np.random.seed(2					)

       UpperCAmelCase__       ,       UpperCAmelCase__							       =  self.model_tester.prepare_config_and_inputs_for_common()

       UpperCAmelCase__							       =  int((config.image_size // config.patch_size) ** 2					)
       UpperCAmelCase__							       =  np.random.uniform(size=(self.model_tester.batch_size, num_patches)					)

       for model_class in self.all_model_classes:
        UpperCAmelCase__							       =  model_class(UpperCamelCase_					)
        UpperCAmelCase__							       =  self._prepare_for_class(UpperCamelCase_       ,					UpperCamelCase_					)

        UpperCAmelCase__							       =  model(UpperCamelCase_       ,					noise=UpperCamelCase_					)
        UpperCAmelCase__							       =  model.get_config()
        # make sure that returned config is jsonifiable, which is required by keras
        json.dumps(UpperCamelCase_					)
        UpperCAmelCase__							       =  model_class.from_config(model.get_config()					)
        # make sure it also accepts a normal config
        UpperCAmelCase__							       =  model_class.from_config(model.config					)
        UpperCAmelCase__							       =  new_model(UpperCamelCase_					)  # Build model
        new_model.set_weights(model.get_weights()					)
        UpperCAmelCase__							       =  new_model(UpperCamelCase_       ,					noise=UpperCamelCase_					)

        self.assert_outputs_same(UpperCamelCase_       ,					UpperCamelCase_					)
      @unittest.skip(
          reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n    to get deterministic results."					)
      def 		UpperCAmelCase_  (	self      :Tuple					)   ->	str:
       pass
      @unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load"					)
      def 		UpperCAmelCase_  (	self      :Union[str, Any]					)   ->	List[str]:
       pass







      @slow
      def 		UpperCAmelCase_  (	self      :str					)   ->	List[str]:
       UpperCAmelCase__							       =  TFViTMAEModel.from_pretrained("google/vit-base-patch16-224"					)
       self.assertIsNotNone(UpperCamelCase_					)



def   lowerCAmelCase						(						):




 """simple docstring"""







 UpperCAmelCase__							       =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
 return image


@require_tf
@require_vision
class 	_UpperCamelCase					( unittest.TestCase						):
      @cached_property
      def 		UpperCAmelCase_  (	self      :List[str]					)   ->	List[str]:
       return ViTImageProcessor.from_pretrained("facebook/vit-mae-base"					) if is_vision_available() else None







      @slow
      def 		UpperCAmelCase_  (	self      :int					)   ->	Optional[Any]:
       np.random.seed(2					)

       UpperCAmelCase__							       =  TFViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base"					)

       UpperCAmelCase__							       =  self.default_image_processor
       UpperCAmelCase__							       =  prepare_img()
       UpperCAmelCase__							       =  image_processor(images=UpperCamelCase_       ,					return_tensors="tf"					)

       # prepare a noise vector that will be also used for testing the TF model
       # (this way we can ensure that the PT and TF models operate on the same inputs)
       UpperCAmelCase__							       =  ViTMAEConfig()
       UpperCAmelCase__							       =  int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2					)
       UpperCAmelCase__							       =  np.random.uniform(size=(1, num_patches)					)

       # forward pass
       UpperCAmelCase__							       =  model(**UpperCamelCase_       ,					noise=UpperCamelCase_					)

       # verify the logits
       UpperCAmelCase__							       =  tf.convert_to_tensor([1, 196, 768]					)
       self.assertEqual(outputs.logits.shape       ,					UpperCamelCase_					)

       UpperCAmelCase__							       =  tf.convert_to_tensor(
           [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]]					)

       tf.debugging.assert_near(outputs.logits[0, :3, :3]       ,					UpperCamelCase_       ,					atol=1e-4					)









from pickle import UnpicklingError

import jax
import jax.numpy as jnp
import numpy as np
from flax.serialization import from_bytes
from flax.traverse_util import flatten_dict

from ..utils import logging


lowerCAmelCase       =							logging.get_logger(__name__)
def 			_a (      SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		try:
				with open(SCREAMING_SNAKE_CASE						,				'''rb'''     ) as flax_state_f:
						lowercase__            =      from_bytes(SCREAMING_SNAKE_CASE						,				flax_state_f.read()     )
		except UnpicklingError as e:
				try:
						with open(SCREAMING_SNAKE_CASE     ) as f:
								if f.read().startswith('''version'''     ):
										raise OSError(
										    '''You seem to have cloned a repository without having git-lfs installed. Please'''
										    ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the'''
										    ''' folder you cloned.'''     )
								else:
										raise ValueError from e
				except (UnicodeDecodeError, ValueError):
						raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. '     )

		return load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE     )
def 			_a (      SCREAMING_SNAKE_CASE						,				SCREAMING_SNAKE_CASE     ):


		"""simple docstring"""




		try:
				import torch  # noqa: F401
		except ImportError:
				logger.error(
				    '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see'''
				    ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation'''
				    ''' instructions.'''     )
				raise

		# check if we have bf16 weights
		lowercase__            =      flatten_dict(jax.tree_util.tree_map(lambda SCREAMING_SNAKE_CASE     : x.dtype == jnp.bfloataa						,				SCREAMING_SNAKE_CASE     )     ).values()
		if any(SCREAMING_SNAKE_CASE     ):
				# convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16

				# and bf16 is not fully supported in PT yet.
				logger.warning(
				    '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` '''
				    '''before loading those in PyTorch model.'''     )
				lowercase__            =      jax.tree_util.tree_map(
				    lambda SCREAMING_SNAKE_CASE     : params.astype(np.floataa     ) if params.dtype == jnp.bfloataa else params						,				SCREAMING_SNAKE_CASE     )

		lowercase__            =      ''''''

		lowercase__            =      flatten_dict(SCREAMING_SNAKE_CASE						,				sep='''.'''     )
		lowercase__            =      pt_model.state_dict()

		# keep track of unexpected & missing keys
		lowercase__            =      []
		lowercase__            =      set(pt_model_dict.keys()     )

		for flax_key_tuple, flax_tensor in flax_state_dict.items():
				lowercase__            =      flax_key_tuple.split('''.'''     )

				if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4:
						lowercase__            =      flax_key_tuple_array[:-1] + ['''weight''']
						lowercase__            =      jnp.transpose(SCREAMING_SNAKE_CASE						,				(3, 2, 0, 1)     )
				elif flax_key_tuple_array[-1] == "kernel":
						lowercase__            =      flax_key_tuple_array[:-1] + ['''weight''']
						lowercase__            =      flax_tensor.T
				elif flax_key_tuple_array[-1] == "scale":
						lowercase__            =      flax_key_tuple_array[:-1] + ['''weight''']

				if "time_embedding" not in flax_key_tuple_array:
						for i, flax_key_tuple_string in enumerate(SCREAMING_SNAKE_CASE     ):
								lowercase__            =      (
								    flax_key_tuple_string.replace('''_0'''						,				'''.0'''     )
								    .replace('''_1'''						,				'''.1'''     )
								    .replace('''_2'''						,				'''.2'''     )
								    .replace('''_3'''						,				'''.3'''     )
								    .replace('''_4'''						,				'''.4'''     )
								    .replace('''_5'''						,				'''.5'''     )
								    .replace('''_6'''						,				'''.6'''     )
								    .replace('''_7'''						,				'''.7'''     )
								    .replace('''_8'''						,				'''.8'''     )
								    .replace('''_9'''						,				'''.9'''     )
								)

				lowercase__            =      '''.'''.join(SCREAMING_SNAKE_CASE     )

				if flax_key in pt_model_dict:
						if flax_tensor.shape != pt_model_dict[flax_key].shape:
								raise ValueError(
								    f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected '
								    f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.'     )
						else:
								# add weight to pytorch dict
								lowercase__            =      np.asarray(SCREAMING_SNAKE_CASE     ) if not isinstance(SCREAMING_SNAKE_CASE						,				np.ndarray     ) else flax_tensor
								lowercase__            =      torch.from_numpy(SCREAMING_SNAKE_CASE     )
								# remove from missing keys
								missing_keys.remove(SCREAMING_SNAKE_CASE     )
				else:
						# weight is not expected by PyTorch model
						unexpected_keys.append(SCREAMING_SNAKE_CASE     )

		pt_model.load_state_dict(SCREAMING_SNAKE_CASE     )

		# re-transform missing_keys to list
		lowercase__            =      list(SCREAMING_SNAKE_CASE     )

		if len(SCREAMING_SNAKE_CASE     ) > 0:
				logger.warning(
				    '''Some weights of the Flax model were not used when initializing the PyTorch model'''
				    f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing'
				    f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture'
				    ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This'''
				    f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect'
				    ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a'''
				    ''' FlaxBertForSequenceClassification model).'''     )
		if len(SCREAMING_SNAKE_CASE     ) > 0:
				logger.warning(
				    f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly'
				    f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to'
				    ''' use it for predictions and inference.'''     )

		return pt_model


