


"""simple docstring"""







import numpy as np
from PIL import Image




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    np.array(lowerCAmelCase_       )
					if arr.shape[0] != arr.shape[1]:
										raise ValueError("The input array is not a square matrix"       )
					__SCREAMING_SNAKE_CASE						       =    0
					__SCREAMING_SNAKE_CASE						       =    0
					__SCREAMING_SNAKE_CASE						       =    0
					__SCREAMING_SNAKE_CASE						       =    0

					# compute the shape of the output matrix
					__SCREAMING_SNAKE_CASE						       =    (arr.shape[0] - size) // stride + 1
					# initialize the output matrix with zeros of shape maxpool_shape
					__SCREAMING_SNAKE_CASE						       =    np.zeros((maxpool_shape, maxpool_shape)       )

					while i < arr.shape[0]:
										if i + size > arr.shape[0]:
															# if the end of the matrix is reached, break
															break
										while j < arr.shape[1]:
															# if the end of the matrix is reached, break
															if j + size > arr.shape[1]:
																				break
															# compute the maximum of the pooling matrix
															__SCREAMING_SNAKE_CASE						       =    np.max(arr[i : i + size, j : j + size]       )
															# shift the pooling matrix by stride of column pixels
															j += stride
															mat_j += 1

										# shift the pooling matrix by stride of row pixels
										i += stride
										mat_i += 1

										# reset the column index to 0
										__SCREAMING_SNAKE_CASE						       =    0
										__SCREAMING_SNAKE_CASE						       =    0

					return updated_arr




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    np.array(lowerCAmelCase_       )
					if arr.shape[0] != arr.shape[1]:
										raise ValueError("The input array is not a square matrix"       )
					__SCREAMING_SNAKE_CASE						       =    0
					__SCREAMING_SNAKE_CASE						       =    0
					__SCREAMING_SNAKE_CASE						       =    0
					__SCREAMING_SNAKE_CASE						       =    0

					# compute the shape of the output matrix
					__SCREAMING_SNAKE_CASE						       =    (arr.shape[0] - size) // stride + 1
					# initialize the output matrix with zeros of shape avgpool_shape
					__SCREAMING_SNAKE_CASE						       =    np.zeros((avgpool_shape, avgpool_shape)       )

					while i < arr.shape[0]:
										# if the end of the matrix is reached, break
										if i + size > arr.shape[0]:
															break
										while j < arr.shape[1]:
															# if the end of the matrix is reached, break
															if j + size > arr.shape[1]:
																				break
															# compute the average of the pooling matrix
															__SCREAMING_SNAKE_CASE						       =    int(np.average(arr[i : i + size, j : j + size]       )       )
															# shift the pooling matrix by stride of column pixels
															j += stride
															mat_j += 1

										# shift the pooling matrix by stride of row pixels
										i += stride
										mat_i += 1
										# reset the column index to 0
										__SCREAMING_SNAKE_CASE						       =    0
										__SCREAMING_SNAKE_CASE						       =    0

					return updated_arr


# Main Function
if __name__ == "__main__":
		from doctest import testmod

		testmod(name='''avgpooling''', verbose=True)

		# Loading the image
		a__    :							Optional[int]            =					Image.open('''path_to_image''')

		# Converting the image to numpy array and maxpooling, displaying the result
		# Ensure that the image is a square matrix

		Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

		# Converting the image to numpy array and averagepooling, displaying the result
		# Ensure that the image is a square matrix

		Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()




"""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_       )
