


"""simple docstring"""







import unittest

from transformers.utils.backbone_utils import (
    BackboneMixin,
    get_aligned_output_features_output_indices,
    verify_out_features_out_indices,
)




class 			UpperCamelCase_     (			unittest.TestCase):

	"""simple docstring"""





	def   UpperCAmelCase_				(			self      :    Union[str, Any]       )	->     List[Any]:
						__SCREAMING_SNAKE_CASE						       =    ["a", "b", "c"]

						# Defaults to last layer if both are None
						__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    get_aligned_output_features_output_indices(UpperCAmelCase__      ,      UpperCAmelCase__      ,      UpperCAmelCase__       )
						self.assertEqual(UpperCAmelCase__      ,      ["c"]       )
						self.assertEqual(UpperCAmelCase__      ,      [2]       )

						# Out indices set to match out features
						__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    get_aligned_output_features_output_indices(["a", "c"]      ,      UpperCAmelCase__      ,      UpperCAmelCase__       )
						self.assertEqual(UpperCAmelCase__      ,      ["a", "c"]       )
						self.assertEqual(UpperCAmelCase__      ,      [0, 2]       )

						# Out features set to match out indices
						__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    get_aligned_output_features_output_indices(UpperCAmelCase__      ,      [0, 2]      ,      UpperCAmelCase__       )
						self.assertEqual(UpperCAmelCase__      ,      ["a", "c"]       )
						self.assertEqual(UpperCAmelCase__      ,      [0, 2]       )

						# Out features selected from negative indices
						__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    get_aligned_output_features_output_indices(UpperCAmelCase__      ,      [-3, -1]      ,      UpperCAmelCase__       )
						self.assertEqual(UpperCAmelCase__      ,      ["a", "c"]       )
						self.assertEqual(UpperCAmelCase__      ,      [-3, -1]       )




	def   UpperCAmelCase_				(			self      :    Union[str, Any]       )	->     List[str]:
						# Stage names must be set
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(["a", "b"]      ,      (0, 1)      ,      UpperCAmelCase__       )

						# Out features must be a list
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(("a", "b")      ,      (0, 1)      ,      ["a", "b"]       )

						# Out features must be a subset of stage names
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(["a", "b"]      ,      (0, 1)      ,      ["a"]       )

						# Out indices must be a list or tuple
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(UpperCAmelCase__      ,      0      ,      ["a", "b"]       )

						# Out indices must be a subset of stage names
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(UpperCAmelCase__      ,      (0, 1)      ,      ["a"]       )

						# Out features and out indices must be the same length
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(["a", "b"]      ,      (0,)      ,      ["a", "b", "c"]       )

						# Out features should match out indices
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(["a", "b"]      ,      (0, 2)      ,      ["a", "b", "c"]       )

						# Out features and out indices should be in order
						with self.assertRaises(UpperCAmelCase__       ):
											verify_out_features_out_indices(["b", "a"]      ,      (0, 1)      ,      ["a", "b"]       )

						# Check passes with valid inputs
						verify_out_features_out_indices(["a", "b", "d"]      ,      (0, 1, -1)      ,      ["a", "b", "c", "d"]       )




	def   UpperCAmelCase_				(			self      :    Union[str, Any]       )	->     List[Any]:
						__SCREAMING_SNAKE_CASE						       =    BackboneMixin()

						__SCREAMING_SNAKE_CASE						       =    ["a", "b", "c"]
						__SCREAMING_SNAKE_CASE						       =    ["a", "c"]
						__SCREAMING_SNAKE_CASE						       =    [0, 2]

						# Check that the output features and indices are set correctly
						self.assertEqual(backbone.out_features      ,      ["a", "c"]       )
						self.assertEqual(backbone.out_indices      ,      [0, 2]       )

						# Check out features and indices are updated correctly
						__SCREAMING_SNAKE_CASE						       =    ["a", "b"]
						self.assertEqual(backbone.out_features      ,      ["a", "b"]       )
						self.assertEqual(backbone.out_indices      ,      [0, 1]       )

						__SCREAMING_SNAKE_CASE						       =    [-3, -1]
						self.assertEqual(backbone.out_features      ,      ["a", "c"]       )
						self.assertEqual(backbone.out_indices      ,      [-3, -1]       )




"""simple docstring"""







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


a__    :							Union[str, Any]            =					logging.get_logger(__name__)




def        UpperCAmelCase__	(lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    R"\w+[.]\d+"
					__SCREAMING_SNAKE_CASE						       =    re.findall(lowerCAmelCase_  ,						lowerCAmelCase_       )
					for pat in pats:
										__SCREAMING_SNAKE_CASE						       =    key.replace(lowerCAmelCase_  ,						"_".join(pat.split("."       )       )       )
					return key




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    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)
					):
										__SCREAMING_SNAKE_CASE						       =    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:
										__SCREAMING_SNAKE_CASE						       =    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:
										__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("embedding",)
										return renamed_pt_tuple_key, pt_tensor

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

					# linear layer
					__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("kernel",)
					if pt_tuple_key[-1] == "weight":
										__SCREAMING_SNAKE_CASE						       =    pt_tensor.T
										return renamed_pt_tuple_key, pt_tensor

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

					# old PyTorch layer norm bias
					__SCREAMING_SNAKE_CASE						       =    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        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_=42       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    {k: v.numpy() for k, v in pt_state_dict.items()}

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

					__SCREAMING_SNAKE_CASE						       =    flatten_dict(lowerCAmelCase_       )
					__SCREAMING_SNAKE_CASE						       =    {}

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

										# Correctly rename weight parameters
										__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    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
										__SCREAMING_SNAKE_CASE						       =    jnp.asarray(lowerCAmelCase_       )

					return unflatten_dict(lowerCAmelCase_       )
