



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


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






def      __lowercase       (			a__       )    ->			str:
							__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      __lowercase       (			a__							,       a__							,       a__       )    ->			Dict:
							__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      __lowercase       (			a__							,       a__							,       a__=42       )    ->			Tuple:
							__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									= 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       )











import pytest

from datasets.parallel import ParallelBackendConfig, parallel_backend
from datasets.utils.py_utils import map_nested

from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows






def      __lowercase       (			a__       )    ->			List[Any]:  # picklable for multiprocessing
							return i + 1






@require_dill_gt_0_3_2
@require_joblibspark
@require_not_windows
def      __lowercase       (			)    ->			Any:
							with parallel_backend('spark'       ):
														assert ParallelBackendConfig.backend_name == "spark"

							__SCREAMING_SNAKE_CASE									= [1, 2, 3]
							with pytest.raises(a__       ):
														with parallel_backend('unsupported backend'       ):
																					map_nested(a__							,       a__							,       num_proc=2       )

							with pytest.raises(a__       ):
														with parallel_backend('unsupported backend'       ):
																					map_nested(a__							,       a__							,       num_proc=-1       )






@require_dill_gt_0_3_2
@require_joblibspark
@require_not_windows
@pytest.mark.parametrize('num_proc'							,       [2, -1]       )
def      __lowercase       (			a__       )    ->			Union[str, Any]:
							__SCREAMING_SNAKE_CASE									= [1, 2]
							__SCREAMING_SNAKE_CASE									= {'a': 1, 'b': 2}
							__SCREAMING_SNAKE_CASE									= {'a': [1, 2], 'b': [3, 4]}
							__SCREAMING_SNAKE_CASE									= {'a': {'1': 1}, 'b': 2}
							__SCREAMING_SNAKE_CASE									= {'a': 1, 'b': 2, 'c': 3, 'd': 4}
							__SCREAMING_SNAKE_CASE									= [2, 3]
							__SCREAMING_SNAKE_CASE									= {'a': 2, 'b': 3}
							__SCREAMING_SNAKE_CASE									= {'a': [2, 3], 'b': [4, 5]}
							__SCREAMING_SNAKE_CASE									= {'a': {'1': 2}, 'b': 3}
							__SCREAMING_SNAKE_CASE									= {'a': 2, 'b': 3, 'c': 4, 'd': 5}

							with parallel_backend('spark'       ):
														assert map_nested(a__							,       a__							,       num_proc=a__       ) == expected_map_nested_sa
														assert map_nested(a__							,       a__							,       num_proc=a__       ) == expected_map_nested_sa
														assert map_nested(a__							,       a__							,       num_proc=a__       ) == expected_map_nested_sa
														assert map_nested(a__							,       a__							,       num_proc=a__       ) == expected_map_nested_sa
														assert map_nested(a__							,       a__							,       num_proc=a__       ) == expected_map_nested_sa






