






import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
       from transformers import (
           FlaxBertModel,
           FlaxCLIPVisionModel,
           FlaxVisionTextDualEncoderModel,
           FlaxViTModel,
           VisionTextDualEncoderConfig,
           VisionTextDualEncoderProcessor,
       )
       from transformers.modeling_flax_pytorch_utils import (
           convert_pytorch_state_dict_to_flax,
           load_flax_weights_in_pytorch_model,
       )


if is_torch_available():
       import torch

       from transformers import VisionTextDualEncoderModel

if is_vision_available():
       from PIL import Image


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Optional[int]							)     ->  List[Any]:
   if isinstance(__lowerCAmelCase					,							collections.abc.Iterable							):
      return x
   return (x, x)







@require_flax
class 		_A						:

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	Optional[Any]   ,				lowerCamelCase__						:	Any			):
     """simple docstring"""

     pass

  def    a					(    self						:	Dict			):
     """simple docstring"""

     pass

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     pass

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	np.ndarray   ,				lowerCamelCase__						:	np.ndarray   ,				lowerCamelCase__						:	float			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[Any]					=					np.abs((a - b)			).max()
     self.assertLessEqual(lowerCamelCase__   ,				lowerCamelCase__   ,				f'Difference between torch and flax is {diff} (>= {tol}).'			)

  def    a					(    self						:	Tuple   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	int   ,				lowerCamelCase__						:	Dict=None   ,				**lowerCamelCase__						:	str			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[int]					=					VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__   ,				lowerCamelCase__			)

     __UpperCamelCase	:			Optional[int]					=					FlaxVisionTextDualEncoderModel(lowerCamelCase__			)

     __UpperCamelCase	:			Tuple					=					model(input_ids=lowerCamelCase__   ,				pixel_values=lowerCamelCase__   ,				attention_mask=lowerCamelCase__			)

     self.assertEqual(output["""text_embeds"""].shape   ,				(input_ids.shape[0], config.projection_dim)			)
     self.assertEqual(output["""image_embeds"""].shape   ,				(pixel_values.shape[0], config.projection_dim)			)

  def    a					(    self						:	str   ,				lowerCamelCase__						:	Any   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	Optional[Any]   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	Tuple=None   ,				**lowerCamelCase__						:	Union[str, Any]			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			List[Any]					=					self.get_vision_text_model(lowerCamelCase__   ,				lowerCamelCase__			)
     __UpperCamelCase	:			Optional[int]					=					{"""vision_model""": vision_model, """text_model""": text_model}
     __UpperCamelCase	:			Tuple					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__			)

     __UpperCamelCase	:			List[Any]					=					model(input_ids=lowerCamelCase__   ,				pixel_values=lowerCamelCase__   ,				attention_mask=lowerCamelCase__			)

     self.assertEqual(output["""text_embeds"""].shape   ,				(input_ids.shape[0], model.config.projection_dim)			)
     self.assertEqual(output["""image_embeds"""].shape   ,				(pixel_values.shape[0], model.config.projection_dim)			)

  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	Tuple=None   ,				**lowerCamelCase__						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			List[str]					=					self.get_vision_text_model(lowerCamelCase__   ,				lowerCamelCase__			)
     __UpperCamelCase	:			Optional[int]					=					{"""vision_model""": vision_model, """text_model""": text_model}
     __UpperCamelCase	:			Union[str, Any]					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__			)

     __UpperCamelCase	:			Dict					=					model(input_ids=lowerCamelCase__   ,				pixel_values=lowerCamelCase__   ,				attention_mask=lowerCamelCase__			)
     __UpperCamelCase	:			List[str]					=					output[0]

     with tempfile.TemporaryDirectory() as tmpdirname:
        model.save_pretrained(lowerCamelCase__			)
        __UpperCamelCase	:			List[str]					=					FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__			)

        __UpperCamelCase	:			List[str]					=					model(input_ids=lowerCamelCase__   ,				pixel_values=lowerCamelCase__   ,				attention_mask=lowerCamelCase__			)
        __UpperCamelCase	:			List[Any]					=					after_output[0]
        __UpperCamelCase	:			Dict					=					np.amax(np.abs(out_a - out_a			)			)
        self.assertLessEqual(lowerCamelCase__   ,				1e-3			)

  def    a					(    self						:	str   ,				lowerCamelCase__						:	Dict   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	Any   ,				lowerCamelCase__						:	Tuple=None   ,				**lowerCamelCase__						:	Dict			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			int					=					self.get_vision_text_model(lowerCamelCase__   ,				lowerCamelCase__			)
     __UpperCamelCase	:			Any					=					{"""vision_model""": vision_model, """text_model""": text_model}
     __UpperCamelCase	:			Any					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase__			)

     __UpperCamelCase	:			Optional[int]					=					model(
         input_ids=lowerCamelCase__   ,				pixel_values=lowerCamelCase__   ,				attention_mask=lowerCamelCase__   ,				output_attentions=lowerCamelCase__			)

     __UpperCamelCase	:			Any					=					output.vision_model_output.attentions
     self.assertEqual(len(lowerCamelCase__			)   ,				vision_config.num_hidden_layers			)

     # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
     __UpperCamelCase	:			Tuple					=					to_atuple(vision_model.config.image_size			)
     __UpperCamelCase	:			Dict					=					to_atuple(vision_model.config.patch_size			)
     __UpperCamelCase	:			List[str]					=					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
     __UpperCamelCase	:			Dict					=					num_patches + 1
     self.assertEqual(vision_attentions[0].shape[-3:]   ,				(vision_config.num_attention_heads, seq_len, seq_len)			)

     __UpperCamelCase	:			int					=					output.text_model_output.attentions
     self.assertEqual(len(lowerCamelCase__			)   ,				text_config.num_hidden_layers			)

     self.assertEqual(
         text_attentions[0].shape[-3:]   ,				(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])   ,				)

  def    a					(    self						:	Optional[Any]   ,				lowerCamelCase__						:	int   ,				lowerCamelCase__						:	Optional[Any]   ,				lowerCamelCase__						:	Any			):
     """simple docstring"""

     pt_model.to(lowerCamelCase__			)
     pt_model.eval()

     # prepare inputs
     __UpperCamelCase	:			Optional[int]					=					inputs_dict
     __UpperCamelCase	:			List[Any]					=					{k: torch.tensor(v.tolist()			) for k, v in flax_inputs.items()}

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

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

     # PT -> Flax
     with tempfile.TemporaryDirectory() as tmpdirname:
        pt_model.save_pretrained(lowerCamelCase__			)
        __UpperCamelCase	:			Union[str, Any]					=					FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__   ,				from_pt=lowerCamelCase__			)

     __UpperCamelCase	:			int					=					fx_model_loaded(**lowerCamelCase__			).to_tuple()
     self.assertEqual(len(lowerCamelCase__			)   ,				len(lowerCamelCase__			)   ,				"""Output lengths differ between Flax and PyTorch"""			)
     for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]   ,				pt_outputs[:4]			):
        self.assert_almost_equals(lowerCamelCase__   ,				pt_output.numpy()   ,				4e-2			)

     # Flax -> PT
     with tempfile.TemporaryDirectory() as tmpdirname:
        fx_model.save_pretrained(lowerCamelCase__			)
        __UpperCamelCase	:			Any					=					VisionTextDualEncoderModel.from_pretrained(lowerCamelCase__   ,				from_flax=lowerCamelCase__			)

     pt_model_loaded.to(lowerCamelCase__			)
     pt_model_loaded.eval()

     with torch.no_grad():
        __UpperCamelCase	:			Optional[Any]					=					pt_model_loaded(**lowerCamelCase__			).to_tuple()

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

  def    a					(    self						:	str   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	List[str]   ,				lowerCamelCase__						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	:			str					=					VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__   ,				lowerCamelCase__			)

     __UpperCamelCase	:			Optional[Any]					=					VisionTextDualEncoderModel(lowerCamelCase__			)
     __UpperCamelCase	:			int					=					FlaxVisionTextDualEncoderModel(lowerCamelCase__			)

     __UpperCamelCase	:			Dict					=					convert_pytorch_state_dict_to_flax(pt_model.state_dict()   ,				lowerCamelCase__			)
     __UpperCamelCase	:			int					=					fx_state

     self.check_pt_flax_equivalence(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__			)

  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	List[str]   ,				lowerCamelCase__						:	List[str]   ,				lowerCamelCase__						:	Optional[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			str					=					VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase__   ,				lowerCamelCase__			)

     __UpperCamelCase	:			Tuple					=					VisionTextDualEncoderModel(lowerCamelCase__			)
     __UpperCamelCase	:			List[Any]					=					FlaxVisionTextDualEncoderModel(lowerCamelCase__			)

     __UpperCamelCase	:			str					=					load_flax_weights_in_pytorch_model(lowerCamelCase__   ,				fx_model.params			)

     self.check_pt_flax_equivalence(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__			)

  def    a					(    self						:	Optional[int]			):
     """simple docstring"""

     __UpperCamelCase	:			List[Any]					=					self.prepare_config_and_inputs()
     self.check_model_from_pretrained_configs(**lowerCamelCase__			)

  def    a					(    self						:	int			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase__			)

  def    a					(    self						:	Dict			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[int]					=					self.prepare_config_and_inputs()
     self.check_save_load(**lowerCamelCase__			)

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[Any]					=					self.prepare_config_and_inputs()
     self.check_vision_text_output_attention(**lowerCamelCase__			)

  @is_pt_flax_cross_test
  def    a					(    self						:	str			):
     """simple docstring"""

     __UpperCamelCase	:			Any					=					self.prepare_config_and_inputs()
     __UpperCamelCase	:			Tuple					=					config_inputs_dict.pop("""vision_config"""			)
     __UpperCamelCase	:			Optional[Any]					=					config_inputs_dict.pop("""text_config"""			)

     __UpperCamelCase	:			int					=					config_inputs_dict

     self.check_equivalence_pt_to_flax(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__			)
     self.check_equivalence_flax_to_pt(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__			)

  @slow
  def    a					(    self						:	Union[str, Any]			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			Any					=					self.get_pretrained_model_and_inputs()

     __UpperCamelCase	:			int					=					model_a(**lowerCamelCase__			)
     __UpperCamelCase	:			str					=					outputs[0]

     with tempfile.TemporaryDirectory() as tmp_dirname:
        model_a.save_pretrained(lowerCamelCase__			)
        __UpperCamelCase	:			int					=					FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase__			)

        __UpperCamelCase	:			Tuple					=					model_a(**lowerCamelCase__			)
        __UpperCamelCase	:			Any					=					after_outputs[0]
        __UpperCamelCase	:			Optional[Any]					=					np.amax(np.abs(out_a - out_a			)			)
        self.assertLessEqual(lowerCamelCase__   ,				1e-5			)







@require_flax
class 		_A						( UpperCAmelCase_	,				unittest.TestCase ):

  def    a					(    self						:	Any			):
     """simple docstring"""

     __UpperCamelCase	:			Any					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         """hf-internal-testing/tiny-random-vit"""   ,				"""hf-internal-testing/tiny-bert"""   ,				vision_from_pt=lowerCamelCase__   ,				text_from_pt=lowerCamelCase__   ,				)
     __UpperCamelCase	:			str					=					13
     __UpperCamelCase	:			str					=					floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]			)
     __UpperCamelCase	:			Any					=					ids_tensor([batch_size, 4]   ,				model.config.text_config.vocab_size			)
     __UpperCamelCase	:			Tuple					=					random_attention_mask([batch_size, 4]			)
     __UpperCamelCase	:			str					=					{"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

     return model, inputs

  def    a					(    self						:	Tuple   ,				lowerCamelCase__						:	Optional[Any]   ,				lowerCamelCase__						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					FlaxViTModel(lowerCamelCase__			)
     __UpperCamelCase	:			int					=					FlaxBertModel(lowerCamelCase__			)
     return vision_model, text_model

  def    a					(    self						:	Optional[int]			):
     """simple docstring"""

     __UpperCamelCase	:			int					=					FlaxViTModelTester(self			)
     __UpperCamelCase	:			Tuple					=					FlaxBertModelTester(self			)
     __UpperCamelCase	:			List[str]					=					vit_model_tester.prepare_config_and_inputs()
     __UpperCamelCase	:			int					=					bert_model_tester.prepare_config_and_inputs()

     __UpperCamelCase	,     __UpperCamelCase	:			Union[str, Any]					=					vision_config_and_inputs

     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	:			Union[str, Any]					=					text_config_and_inputs

     # make sure that cross attention layers are added
     return {
         "text_config": text_config,
         "vision_config": vision_config,
         "pixel_values": pixel_values,
         "attention_mask": attention_mask,
         "input_ids": input_ids,
         "token_type_ids": token_type_ids,
     }







@require_torch
class 		_A						( UpperCAmelCase_	,				unittest.TestCase ):

  def    a					(    self						:	Dict			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[Any]					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         """hf-internal-testing/tiny-random-clip"""   ,				"""hf-internal-testing/tiny-bert"""   ,				vision_from_pt=lowerCamelCase__   ,				text_from_pt=lowerCamelCase__   ,				)
     __UpperCamelCase	:			Any					=					13
     __UpperCamelCase	:			str					=					floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]			)
     __UpperCamelCase	:			Union[str, Any]					=					ids_tensor([batch_size, 4]   ,				model.config.text_config.vocab_size			)
     __UpperCamelCase	:			List[str]					=					random_attention_mask([batch_size, 4]			)
     __UpperCamelCase	:			Optional[Any]					=					{"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

     return model, inputs

  def    a					(    self						:	Dict   ,				lowerCamelCase__						:	Dict   ,				lowerCamelCase__						:	Union[str, Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					FlaxCLIPVisionModel(lowerCamelCase__			)
     __UpperCamelCase	:			Union[str, Any]					=					FlaxBertModel(lowerCamelCase__			)
     return vision_model, text_model

  def    a					(    self						:	Any			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					FlaxCLIPVisionModelTester(self			)
     __UpperCamelCase	:			Optional[Any]					=					FlaxBertModelTester(self			)
     __UpperCamelCase	:			Any					=					clip_model_tester.prepare_config_and_inputs()
     __UpperCamelCase	:			Any					=					bert_model_tester.prepare_config_and_inputs()

     __UpperCamelCase	,     __UpperCamelCase	:			Optional[int]					=					vision_config_and_inputs

     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	:			Dict					=					text_config_and_inputs

     # make sure that cross attention layers are added
     return {
         "text_config": text_config,
         "vision_config": vision_config,
         "pixel_values": pixel_values,
         "attention_mask": attention_mask,
         "input_ids": input_ids,
         "token_type_ids": token_type_ids,
     }







@require_flax
@require_vision
class 		_A						( unittest.TestCase ):

  @slow
  def    a					(    self						:	int			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian"""   ,				logit_scale_init_value=1.0			)
     __UpperCamelCase	:			Tuple					=					VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""			)

     __UpperCamelCase	:			Union[str, Any]					=					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
     __UpperCamelCase	:			List[Any]					=					processor(
         text=["""una foto di un gatto""", """una foto di un cane"""]   ,				images=lowerCamelCase__   ,				padding=lowerCamelCase__   ,				return_tensors="""np"""			)

     __UpperCamelCase	:			Optional[int]					=					model(**lowerCamelCase__			)

     # verify the logits
     self.assertEqual(outputs.logits_per_image.shape   ,				(inputs.pixel_values.shape[0], inputs.input_ids.shape[0])			)
     self.assertEqual(
         outputs.logits_per_text.shape   ,				(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])   ,				)

     __UpperCamelCase	:			Tuple					=					np.array([[1.228_4727, 0.310_4122]]			)

     self.assertTrue(np.allclose(outputs.logits_per_image   ,				lowerCamelCase__   ,				atol=1e-3			)			)











import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


UpperCamelCase    							=      logging.get_logger(__name__)


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Tuple							)     ->  List[str]:
   __UpperCamelCase	:			List[str]					=					R"""\w+[.]\d+"""
   __UpperCamelCase	:			Optional[int]					=					re.findall(__lowerCAmelCase					,							__lowerCAmelCase							)
   for pat in pats:
      __UpperCamelCase	:			str					=					key.replace(__lowerCAmelCase					,							"""_""".join(pat.split("""."""							)							)							)
   return key


def 				__lowerCamelCase     (							__lowerCAmelCase							:					int					,							__lowerCAmelCase							:					Optional[int]					,							__lowerCAmelCase							:					Union[str, Any]							)     ->  str:
   __UpperCamelCase	:			Dict					=					pt_tuple_key[:-1] + ("""scale""",)
   if (
       any("""norm""" in str_ for str_ in pt_tuple_key							)
       and (pt_tuple_key[-1] == "bias")
       and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
       and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
   ):
      __UpperCamelCase	:			List[Any]					=					pt_tuple_key[:-1] + ("""scale""",)
      return renamed_pt_tuple_key, pt_tensor
   elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
      __UpperCamelCase	:			Dict					=					pt_tuple_key[:-1] + ("""scale""",)
      return renamed_pt_tuple_key, pt_tensor

   # embedding
   if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
      __UpperCamelCase	:			Any					=					pt_tuple_key[:-1] + ("""embedding""",)
      return renamed_pt_tuple_key, pt_tensor

   # conv layer
   __UpperCamelCase	:			List[Any]					=					pt_tuple_key[:-1] + ("""kernel""",)
   if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
      __UpperCamelCase	:			Dict					=					pt_tensor.transpose(2					,							3					,							1					,							0							)
      return renamed_pt_tuple_key, pt_tensor

   # linear layer
   __UpperCamelCase	:			Union[str, Any]					=					pt_tuple_key[:-1] + ("""kernel""",)
   if pt_tuple_key[-1] == "weight":
      __UpperCamelCase	:			int					=					pt_tensor.T
      return renamed_pt_tuple_key, pt_tensor

   # old PyTorch layer norm weight
   __UpperCamelCase	:			List[Any]					=					pt_tuple_key[:-1] + ("""weight""",)
   if pt_tuple_key[-1] == "gamma":
      return renamed_pt_tuple_key, pt_tensor

   # old PyTorch layer norm bias
   __UpperCamelCase	:			Tuple					=					pt_tuple_key[:-1] + ("""bias""",)
   if pt_tuple_key[-1] == "beta":
      return renamed_pt_tuple_key, pt_tensor

   return pt_tuple_key, pt_tensor



def 				__lowerCamelCase     (							__lowerCAmelCase							:					Dict					,							__lowerCAmelCase							:					List[Any]					,							__lowerCAmelCase							:					Optional[int]=42							)     ->  int:
   # Step 1: Convert pytorch tensor to numpy
   __UpperCamelCase	:			Dict					=					{k: v.numpy() for k, v in pt_state_dict.items()}

   # Step 2: Since the model is stateless, get random Flax params
   __UpperCamelCase	:			str					=					flax_model.init_weights(PRNGKey(__lowerCAmelCase							)							)

   __UpperCamelCase	:			Union[str, Any]					=					flatten_dict(__lowerCAmelCase							)
   __UpperCamelCase	:			List[str]					=					{}

   # Need to change some parameters name to match Flax names
   for pt_key, pt_tensor in pt_state_dict.items():
      __UpperCamelCase	:			str					=					rename_key(__lowerCAmelCase							)
      __UpperCamelCase	:			Any					=					tuple(renamed_pt_key.split("""."""							)							)

      # Correctly rename weight parameters
      __UpperCamelCase	,     __UpperCamelCase	:			Tuple					=					rename_key_and_reshape_tensor(__lowerCAmelCase					,							__lowerCAmelCase					,							__lowerCAmelCase							)

      if flax_key in random_flax_state_dict:
         if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
            raise ValueError(
                f'PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape '
                f'{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.'							)

        # also add unexpected weight so that warning is thrown
      __UpperCamelCase	:			Any					=					jnp.asarray(__lowerCAmelCase							)

   return unflatten_dict(__lowerCAmelCase							)



