
'''simple docstring'''



import gc
import unittest

from transformers import CTRLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import (
						    CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
						    CTRLForSequenceClassification,
						    CTRLLMHeadModel,
						    CTRLModel,
						)




class     UpperCAmelCase_	:






						'''simple docstring'''






						def __init__(   self       ,  _lowercase       ,  _lowercase=14       ,  _lowercase=7       ,  _lowercase=True       ,  _lowercase=True       ,  _lowercase=True       ,  _lowercase=True       ,  _lowercase=True       ,  _lowercase=99       ,  _lowercase=32       ,  _lowercase=5       ,  _lowercase=4       ,  _lowercase=37       ,  _lowercase="gelu"       ,  _lowercase=0.1       ,  _lowercase=0.1       ,  _lowercase=512       ,  _lowercase=16       ,  _lowercase=2       ,  _lowercase=0.02       ,  _lowercase=3       ,  _lowercase=4       ,  _lowercase=None       ,  ):

												"""simple docstring"""



												_lowerCAmelCase    		=					parent
												_lowerCAmelCase    		=					batch_size
												_lowerCAmelCase    		=					seq_length
												_lowerCAmelCase    		=					is_training
												_lowerCAmelCase    		=					use_token_type_ids
												_lowerCAmelCase    		=					use_input_mask
												_lowerCAmelCase    		=					use_labels
												_lowerCAmelCase    		=					use_mc_token_ids
												_lowerCAmelCase    		=					vocab_size
												_lowerCAmelCase    		=					hidden_size
												_lowerCAmelCase    		=					num_hidden_layers
												_lowerCAmelCase    		=					num_attention_heads
												_lowerCAmelCase    		=					intermediate_size
												_lowerCAmelCase    		=					hidden_act
												_lowerCAmelCase    		=					hidden_dropout_prob
												_lowerCAmelCase    		=					attention_probs_dropout_prob
												_lowerCAmelCase    		=					max_position_embeddings
												_lowerCAmelCase    		=					type_vocab_size
												_lowerCAmelCase    		=					type_sequence_label_size
												_lowerCAmelCase    		=					initializer_range
												_lowerCAmelCase    		=					num_labels
												_lowerCAmelCase    		=					num_choices
												_lowerCAmelCase    		=					scope
												_lowerCAmelCase    		=					self.vocab_size - 1




						def    _lowercase      (   self ):

												"""simple docstring"""



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

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

												_lowerCAmelCase    		=					None
												if self.use_token_type_ids:
																		_lowerCAmelCase    		=					ids_tensor([self.batch_size, self.seq_length]       ,  self.type_vocab_size )

												_lowerCAmelCase    		=					None
												if self.use_mc_token_ids:
																		_lowerCAmelCase    		=					ids_tensor([self.batch_size, self.num_choices]       ,  self.seq_length )

												_lowerCAmelCase    		=					None
												_lowerCAmelCase    		=					None
												_lowerCAmelCase    		=					None
												if self.use_labels:
																		_lowerCAmelCase    		=					ids_tensor([self.batch_size]       ,  self.type_sequence_label_size )
																		_lowerCAmelCase    		=					ids_tensor([self.batch_size, self.seq_length]       ,  self.num_labels )
																		_lowerCAmelCase    		=					ids_tensor([self.batch_size]       ,  self.num_choices )

												_lowerCAmelCase    		=					self.get_config()

												_lowerCAmelCase    		=					ids_tensor([self.num_hidden_layers, self.num_attention_heads]       ,  2 )

												return (
												    config,
												    input_ids,
												    input_mask,
												    head_mask,
												    token_type_ids,
												    mc_token_ids,
												    sequence_labels,
												    token_labels,
												    choice_labels,
												)




						def    _lowercase      (   self ):

												"""simple docstring"""



												return CTRLConfig(
												    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       ,  pad_token_id=self.pad_token_id       ,  )




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  *_lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					CTRLModel(config=_lowercase )
												model.to(_lowercase )
												model.eval()

												model(_lowercase       ,  token_type_ids=_lowercase       ,  head_mask=_lowercase )
												model(_lowercase       ,  token_type_ids=_lowercase )
												_lowerCAmelCase    		=					model(_lowercase )
												self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size) )
												self.parent.assertEqual(len(result.past_key_values )       ,  config.n_layer )




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  *_lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					CTRLLMHeadModel(_lowercase )
												model.to(_lowercase )
												model.eval()

												_lowerCAmelCase    		=					model(_lowercase       ,  token_type_ids=_lowercase       ,  labels=_lowercase )
												self.parent.assertEqual(result.loss.shape       ,  () )
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size) )




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.prepare_config_and_inputs()

												(
												    (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       (
												    _lowerCAmelCase
												)		,       
												)    		=					config_and_inputs

												_lowerCAmelCase    		=					{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask}

												return config, inputs_dict




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  *_lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.num_labels
												_lowerCAmelCase    		=					CTRLForSequenceClassification(_lowercase )
												model.to(_lowercase )
												model.eval()
												_lowerCAmelCase    		=					ids_tensor([self.batch_size]       ,  self.type_sequence_label_size )
												_lowerCAmelCase    		=					model(_lowercase       ,  token_type_ids=_lowercase       ,  labels=_lowercase )
												self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels) )






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






						'''simple docstring'''






						_lowercase						: List[str]										=  (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
						_lowercase						: List[str]										=  (CTRLLMHeadModel,) if is_torch_available() else ()
						_lowercase						: Dict										=  (
						    {
						        '''feature-extraction''': CTRLModel,
						        '''text-classification''': CTRLForSequenceClassification,
						        '''text-generation''': CTRLLMHeadModel,
						        '''zero-shot''': CTRLForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)
						_lowercase						: Any										=  True
						_lowercase						: Dict										=  False
						_lowercase						: Dict										=  False




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase       ,  _lowercase ):

												"""simple docstring"""



												if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
																		# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
																		# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
																		# config could not be created.
																		return True

												return False




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					CTRLModelTester(self )
												_lowerCAmelCase    		=					ConfigTester(self       ,  config_class=_lowercase       ,  n_embd=37 )




						def    _lowercase      (   self ):

												"""simple docstring"""



												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()




						def    _lowercase      (   self ):

												"""simple docstring"""



												self.config_tester.run_common_tests()




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_ctrl_model(*_lowercase )




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_lm_head_model(*_lowercase )




						@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
						def    _lowercase      (   self ):

												"""simple docstring"""



												pass




						@slow
						def    _lowercase      (   self ):

												"""simple docstring"""



												for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		_lowerCAmelCase    		=					CTRLModel.from_pretrained(_lowercase )
																		self.assertIsNotNone(_lowercase )




						@unittest.skip("""The model doesn't support left padding""" )  # and it's not used enough to be worth fixing :)
						def    _lowercase      (   self ):

												"""simple docstring"""



												pass






@require_torch
class     UpperCAmelCase_	(						unittest.TestCase					):






						'''simple docstring'''






						def    _lowercase      (   self ):

												"""simple docstring"""



												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()




						@slow
						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					CTRLLMHeadModel.from_pretrained("""ctrl""" )
												model.to(_lowercase )
												_lowerCAmelCase    		=					torch.tensor(
												    [[11_859, 0, 1_611, 8]]       ,  dtype=torch.long       ,  device=_lowercase )  # Legal the president is
												_lowerCAmelCase    		=					[
												    11_859,
												    0,
												    1_611,
												    8,
												    5,
												    150,
												    26_449,
												    2,
												    19,
												    348,
												    469,
												    3,
												    2_595,
												    48,
												    20_740,
												    246_533,
												    246_533,
												    19,
												    30,
												    5,
												]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

												_lowerCAmelCase    		=					model.generate(_lowercase       ,  do_sample=_lowercase )
												self.assertListEqual(output_ids[0].tolist()       ,  _lowercase )








import os
from pickle import UnpicklingError
from typing import Dict, Tuple

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

import transformers

from .utils import logging


UpperCamelCase    							=      logging.get_logger(__name__)


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Any					,							__lowerCAmelCase							:					Any					,							__lowerCAmelCase							:					Any					,							__lowerCAmelCase							:					List[Any]=False							)     ->  Union[str, Any]:
   try:
      import torch  # noqa: F401
   except ImportError:
      logger.error(
          """Loading a PyTorch model in Flax, 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

   if not is_sharded:
      __UpperCamelCase	:			Tuple					=					os.path.abspath(__lowerCAmelCase							)
      logger.info(f'Loading PyTorch weights from {pt_path}'							)

      __UpperCamelCase	:			int					=					torch.load(__lowerCAmelCase					,							map_location="""cpu"""							)
      logger.info(f'PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()							):,} parameters.'							)

      __UpperCamelCase	:			List[Any]					=					convert_pytorch_state_dict_to_flax(__lowerCAmelCase					,							__lowerCAmelCase							)
   else:
      # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files
      __UpperCamelCase	:			List[str]					=					convert_pytorch_sharded_state_dict_to_flax(__lowerCAmelCase					,							__lowerCAmelCase							)
   return flax_state_dict


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Tuple[str]					,							__lowerCAmelCase							:					np.ndarray					,							__lowerCAmelCase							:					Dict[str, jnp.ndarray]					,							__lowerCAmelCase							:					str					,							)     ->  (Tuple[str], np.ndarray):

   def is_key_or_prefix_key_in_dict(__lowerCAmelCase							:					Tuple[str]							) -> bool:
      return len(set(__lowerCAmelCase							) & {key, (model_prefix,) + key}							) > 0

   # layer norm
   __UpperCamelCase	:			Optional[int]					=					pt_tuple_key[:-1] + ("""scale""",)
   if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(__lowerCAmelCase							):
      return renamed_pt_tuple_key, pt_tensor

   # batch norm layer mean
   __UpperCamelCase	:			Optional[Any]					=					pt_tuple_key[:-1] + ("""mean""",)
   if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(__lowerCAmelCase							):
      return renamed_pt_tuple_key, pt_tensor

   # batch norm layer var
   __UpperCamelCase	:			Optional[Any]					=					pt_tuple_key[:-1] + ("""var""",)
   if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(__lowerCAmelCase							):
      return renamed_pt_tuple_key, pt_tensor

   # embedding
   __UpperCamelCase	:			Union[str, Any]					=					pt_tuple_key[:-1] + ("""embedding""",)
   if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(__lowerCAmelCase							):
      return renamed_pt_tuple_key, pt_tensor

   # conv layer
   __UpperCamelCase	:			Tuple					=					pt_tuple_key[:-1] + ("""kernel""",)
   if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(__lowerCAmelCase							):
      __UpperCamelCase	:			Optional[int]					=					pt_tensor.transpose(2					,							3					,							1					,							0							)
      return renamed_pt_tuple_key, pt_tensor

   # linear layer
   __UpperCamelCase	:			int					=					pt_tuple_key[:-1] + ("""kernel""",)
   if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(__lowerCAmelCase							):
      __UpperCamelCase	:			Optional[int]					=					pt_tensor.T
      return renamed_pt_tuple_key, pt_tensor

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

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

   # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030
   __UpperCamelCase	:			Optional[int]					=					None
   if pt_tuple_key[-3::2] == ("parametrizations", "original0"):
      __UpperCamelCase	:			Tuple					=					pt_tuple_key[-2] + """_g"""
   elif pt_tuple_key[-3::2] == ("parametrizations", "original1"):
      __UpperCamelCase	:			Dict					=					pt_tuple_key[-2] + """_v"""
   if name is not None:
      __UpperCamelCase	:			Optional[Any]					=					pt_tuple_key[:-3] + (name,)
      return renamed_pt_tuple_key, pt_tensor

   return pt_tuple_key, pt_tensor


def 				__lowerCamelCase     (							__lowerCAmelCase							:					int					,							__lowerCAmelCase							:					int							)     ->  Union[str, Any]:
   # convert pytorch tensor to numpy
   __UpperCamelCase	:			Optional[Any]					=					{k: v.numpy() for k, v in pt_state_dict.items()}

   __UpperCamelCase	:			List[Any]					=					flax_model.base_model_prefix

   # use params dict if the model contains batch norm layers
   if "params" in flax_model.params:
      __UpperCamelCase	:			Union[str, Any]					=					flax_model.params["""params"""]
   else:
      __UpperCamelCase	:			List[Any]					=					flax_model.params
   __UpperCamelCase	:			List[Any]					=					flatten_dict(__lowerCAmelCase							)

   # add batch_stats keys,values to dict
   if "batch_stats" in flax_model.params:
      __UpperCamelCase	:			List[str]					=					flatten_dict(flax_model.params["""batch_stats"""]							)
      random_flax_state_dict.update(__lowerCAmelCase							)

   __UpperCamelCase	:			List[Any]					=					{}

   __UpperCamelCase	:			int					=					(model_prefix not in flax_model_params) and (
       model_prefix in {k.split("""."""							)[0] for k in pt_state_dict.keys()}
   )
   __UpperCamelCase	:			int					=					(model_prefix in flax_model_params) and (
       model_prefix not in {k.split("""."""							)[0] for k in pt_state_dict.keys()}
   )

   # Need to change some parameters name to match Flax names
   for pt_key, pt_tensor in pt_state_dict.items():
      __UpperCamelCase	:			List[str]					=					tuple(pt_key.split("""."""							)							)

      # remove base model prefix if necessary
      __UpperCamelCase	:			Optional[Any]					=					pt_tuple_key[0] == model_prefix
      if load_model_with_head_into_base_model and has_base_model_prefix:
         __UpperCamelCase	:			List[str]					=					pt_tuple_key[1:]

      # Correctly rename weight parameters
      __UpperCamelCase	,     __UpperCamelCase	:			Optional[int]					=					rename_key_and_reshape_tensor(
          __lowerCAmelCase					,							__lowerCAmelCase					,							__lowerCAmelCase					,							__lowerCAmelCase							)

      # add model prefix if necessary
      __UpperCamelCase	:			Optional[Any]					=					(model_prefix,) + flax_key in random_flax_state_dict
      if load_base_model_into_model_with_head and require_base_model_prefix:
         __UpperCamelCase	:			Dict					=					(model_prefix,) + flax_key

      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}.'							)

        # add batch stats if the model contains batchnorm layers
      if "batch_stats" in flax_model.params:
         if "mean" in flax_key[-1] or "var" in flax_key[-1]:
            __UpperCamelCase	:			int					=					jnp.asarray(__lowerCAmelCase							)
            continue
         # remove num_batches_tracked key
         if "num_batches_tracked" in flax_key[-1]:
            flax_state_dict.pop(__lowerCAmelCase					,							__lowerCAmelCase							)
            continue

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

      else:
         # also add unexpected weight so that warning is thrown
         __UpperCamelCase	:			Optional[int]					=					jnp.asarray(__lowerCAmelCase							)

   return unflatten_dict(__lowerCAmelCase							)


def 				__lowerCamelCase     (							__lowerCAmelCase							:					List[str]					,							__lowerCAmelCase							:					int							)     ->  Dict:
   import torch

   # Load the index
   __UpperCamelCase	:			List[str]					=					{}
   for shard_file in shard_filenames:
      # load using msgpack utils
      __UpperCamelCase	:			List[str]					=					torch.load(__lowerCAmelCase							)
      __UpperCamelCase	:			int					=					{k: v.numpy() for k, v in pt_state_dict.items()}

      __UpperCamelCase	:			List[str]					=					flax_model.base_model_prefix

      # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict
      if "batch_stats" in flax_model.params:
         __UpperCamelCase	:			Optional[Any]					=					flax_model.params["""params"""]

         __UpperCamelCase	:			int					=					flatten_dict(__lowerCAmelCase							)
         random_flax_state_dict.update(flatten_dict(flax_model.params["""batch_stats"""]							)							)
      else:
         __UpperCamelCase	:			Dict					=					flax_model.params
         __UpperCamelCase	:			int					=					flatten_dict(__lowerCAmelCase							)

      __UpperCamelCase	:			Union[str, Any]					=					(model_prefix not in flax_model_params) and (
          model_prefix in {k.split("""."""							)[0] for k in pt_state_dict.keys()}
      )
      __UpperCamelCase	:			Any					=					(model_prefix in flax_model_params) and (
          model_prefix not in {k.split("""."""							)[0] for k in pt_state_dict.keys()}
      )
      # Need to change some parameters name to match Flax names
      for pt_key, pt_tensor in pt_state_dict.items():
         __UpperCamelCase	:			Any					=					tuple(pt_key.split("""."""							)							)

         # remove base model prefix if necessary
         __UpperCamelCase	:			Dict					=					pt_tuple_key[0] == model_prefix
         if load_model_with_head_into_base_model and has_base_model_prefix:
            __UpperCamelCase	:			str					=					pt_tuple_key[1:]

         # Correctly rename weight parameters
         __UpperCamelCase	,     __UpperCamelCase	:			Optional[Any]					=					rename_key_and_reshape_tensor(
             __lowerCAmelCase					,							__lowerCAmelCase					,							__lowerCAmelCase					,							__lowerCAmelCase							)
         # add model prefix if necessary
         __UpperCamelCase	:			Tuple					=					(model_prefix,) + flax_key in random_flax_state_dict
         if load_base_model_into_model_with_head and require_base_model_prefix:
            __UpperCamelCase	:			Optional[Any]					=					(model_prefix,) + flax_key

         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}.'							)

            # add batch stats if the model contains batchnorm layers
         if "batch_stats" in flax_model.params:
            if "mean" in flax_key[-1]:
               __UpperCamelCase	:			List[Any]					=					jnp.asarray(__lowerCAmelCase							)
               continue
            if "var" in flax_key[-1]:
               __UpperCamelCase	:			Optional[Any]					=					jnp.asarray(__lowerCAmelCase							)
               continue
            # remove num_batches_tracked key
            if "num_batches_tracked" in flax_key[-1]:
               flax_state_dict.pop(__lowerCAmelCase					,							__lowerCAmelCase							)
               continue

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

         else:
            # also add unexpected weight so that warning is thrown
            __UpperCamelCase	:			int					=					jnp.asarray(__lowerCAmelCase							)
   return unflatten_dict(__lowerCAmelCase							)


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Any					,							__lowerCAmelCase							:					Union[str, Any]							)     ->  Union[str, Any]:
   __UpperCamelCase	:			List[Any]					=					os.path.abspath(__lowerCAmelCase							)
   logger.info(f'Loading Flax weights from {flax_checkpoint_path}'							)

   # import correct flax class
   __UpperCamelCase	:			str					=					getattr(__lowerCAmelCase					,							"""Flax""" + model.__class__.__name__							)

   # load flax weight dict
   with open(__lowerCAmelCase					,							"""rb"""							) as state_f:
      try:
         __UpperCamelCase	:			Optional[int]					=					from_bytes(__lowerCAmelCase					,							state_f.read()							)
      except UnpicklingError:
         raise EnvironmentError(f'Unable to convert {flax_checkpoint_path} to Flax deserializable object. '							)

   return load_flax_weights_in_pytorch_model(__lowerCAmelCase					,							__lowerCAmelCase							)



def 				__lowerCamelCase     (							__lowerCAmelCase							:					Optional[int]					,							__lowerCAmelCase							:					Optional[int]							)     ->  List[Any]:

   try:
      import torch  # noqa: F401
   except ImportError:
      logger.error(
          """Loading a 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
   __UpperCamelCase	:			Tuple					=					flatten_dict(jax.tree_util.tree_map(lambda __lowerCAmelCase							: x.dtype == jnp.bfloataa					,							__lowerCAmelCase							)							).values()
   if any(__lowerCAmelCase							):
      # convert all weights to fp32 if the 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."""							)
      __UpperCamelCase	:			List[Any]					=					jax.tree_util.tree_map(
          lambda __lowerCAmelCase							: params.astype(np.floataa							) if params.dtype == jnp.bfloataa else params					,							__lowerCAmelCase							)

   __UpperCamelCase	:			Tuple					=					flatten_dict(__lowerCAmelCase							)
   __UpperCamelCase	:			int					=					pt_model.state_dict()

   __UpperCamelCase	:			Tuple					=					(pt_model.base_model_prefix in flax_state) and (
       pt_model.base_model_prefix not in {k.split("""."""							)[0] for k in pt_model_dict.keys()}
   )
   __UpperCamelCase	:			Any					=					(pt_model.base_model_prefix not in flax_state) and (
       pt_model.base_model_prefix in {k.split("""."""							)[0] for k in pt_model_dict.keys()}
   )

   # keep track of unexpected & missing keys
   __UpperCamelCase	:			Dict					=					[]
   __UpperCamelCase	:			List[str]					=					set(pt_model_dict.keys()							)

   for flax_key_tuple, flax_tensor in flax_state_dict.items():
      __UpperCamelCase	:			Union[str, Any]					=					flax_key_tuple[0] == pt_model.base_model_prefix
      __UpperCamelCase	:			Optional[Any]					=					""".""".join((pt_model.base_model_prefix,) + flax_key_tuple							) in pt_model_dict

      # adapt flax_key to prepare for loading from/to base model only
      if load_model_with_head_into_base_model and has_base_model_prefix:
         __UpperCamelCase	:			List[Any]					=					flax_key_tuple[1:]
      elif load_base_model_into_model_with_head and require_base_model_prefix:
         __UpperCamelCase	:			Tuple					=					(pt_model.base_model_prefix,) + flax_key_tuple

      # rename flax weights to PyTorch format
      if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(__lowerCAmelCase							) not in pt_model_dict:
         # conv layer
         __UpperCamelCase	:			Optional[int]					=					flax_key_tuple[:-1] + ("""weight""",)
         __UpperCamelCase	:			Dict					=					jnp.transpose(__lowerCAmelCase					,							(3, 2, 0, 1)							)
      elif flax_key_tuple[-1] == "kernel" and ".".join(__lowerCAmelCase							) not in pt_model_dict:
         # linear layer
         __UpperCamelCase	:			Optional[int]					=					flax_key_tuple[:-1] + ("""weight""",)
         __UpperCamelCase	:			List[Any]					=					flax_tensor.T
      elif flax_key_tuple[-1] in ["scale", "embedding"]:
         __UpperCamelCase	:			Union[str, Any]					=					flax_key_tuple[:-1] + ("""weight""",)

      # adding batch stats from flax batch norm to pt
      elif "mean" in flax_key_tuple[-1]:
         __UpperCamelCase	:			List[str]					=					flax_key_tuple[:-1] + ("""running_mean""",)
      elif "var" in flax_key_tuple[-1]:
         __UpperCamelCase	:			Tuple					=					flax_key_tuple[:-1] + ("""running_var""",)

      if "batch_stats" in flax_state:
         __UpperCamelCase	:			Optional[int]					=					""".""".join(flax_key_tuple[1:]							)  # Remove the params/batch_stats header
      else:
         __UpperCamelCase	:			Optional[int]					=					""".""".join(__lowerCAmelCase							)

      # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation.
      __UpperCamelCase	:			Union[str, Any]					=					{}
      # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030
      for key in pt_model_dict:
         __UpperCamelCase	:			int					=					key.split("""."""							)
         __UpperCamelCase	:			str					=					None
         if key_components[-3::2] == ["parametrizations", "original0"]:
            __UpperCamelCase	:			Union[str, Any]					=					key_components[-2] + """_g"""
         elif key_components[-3::2] == ["parametrizations", "original1"]:
            __UpperCamelCase	:			Tuple					=					key_components[-2] + """_v"""
         if name is not None:
            __UpperCamelCase	:			Optional[Any]					=					key_components[:-3] + [name]
            __UpperCamelCase	:			int					=					""".""".join(__lowerCAmelCase							)
            __UpperCamelCase	:			List[str]					=					key

      if flax_key in special_pt_names:
         __UpperCamelCase	:			Any					=					special_pt_names[flax_key]

      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
            __UpperCamelCase	:			str					=					np.asarray(__lowerCAmelCase							) if not isinstance(__lowerCAmelCase					,							np.ndarray							) else flax_tensor
            __UpperCamelCase	:			Optional[int]					=					torch.from_numpy(__lowerCAmelCase							)
            # remove from missing keys
            missing_keys.remove(__lowerCAmelCase							)
      else:
         # weight is not expected by PyTorch model
         unexpected_keys.append(__lowerCAmelCase							)

   pt_model.load_state_dict(__lowerCAmelCase							)

   # re-transform missing_keys to list
   __UpperCamelCase	:			Union[str, Any]					=					list(__lowerCAmelCase							)

   if len(__lowerCAmelCase							) > 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)."""							)
   else:
      logger.warning(f'All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n'							)
   if len(__lowerCAmelCase							) > 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."""							)
   else:
      logger.warning(
          f'All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n'
          """If your task is similar to the task the model of the checkpoint was trained on, """
          f'you can already use {pt_model.__class__.__name__} for predictions without further training.'							)

   return pt_model



