


"""simple docstring"""







import logging
import os

from .state import PartialState




class 			UpperCamelCase_     (			logging.LoggerAdapter):

	"""simple docstring"""





	@staticmethod
	def   UpperCAmelCase_				(			UpperCAmelCase__      :    Union[str, Any]       )	->     str:
						__SCREAMING_SNAKE_CASE						       =    PartialState()
						return not main_process_only or (main_process_only and state.is_main_process)




	def   UpperCAmelCase_				(			self      :    Any      ,      UpperCAmelCase__      :    int      ,      UpperCAmelCase__      :    Tuple      ,      *UpperCAmelCase__      :    str      ,      **UpperCAmelCase__      :    str       )	->     Optional[Any]:
						if PartialState._shared_state == {}:
											raise RuntimeError(
											    "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility."       )
						__SCREAMING_SNAKE_CASE						       =    kwargs.pop("main_process_only"      ,      _lowerCAmelCase       )
						__SCREAMING_SNAKE_CASE						       =    kwargs.pop("in_order"      ,      _lowerCAmelCase       )

						if self.isEnabledFor(_lowerCAmelCase       ):
											if self._should_log(_lowerCAmelCase       ):
																__SCREAMING_SNAKE_CASE						       =    self.process(_lowerCAmelCase      ,      _lowerCAmelCase       )
																self.logger.log(_lowerCAmelCase      ,      _lowerCAmelCase      ,      *_lowerCAmelCase      ,      **_lowerCAmelCase       )

											elif in_order:
																__SCREAMING_SNAKE_CASE						       =    PartialState()
																for i in range(state.num_processes       ):
																					if i == state.process_index:
																										__SCREAMING_SNAKE_CASE						       =    self.process(_lowerCAmelCase      ,      _lowerCAmelCase       )
																										self.logger.log(_lowerCAmelCase      ,      _lowerCAmelCase      ,      *_lowerCAmelCase      ,      **_lowerCAmelCase       )
																					state.wait_for_everyone()




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_ = None       ):




					'''simple docstring'''


					if log_level is None:
										__SCREAMING_SNAKE_CASE						       =    os.environ.get("ACCELERATE_LOG_LEVEL"  ,						__SCREAMING_SNAKE_CASE       )
					__SCREAMING_SNAKE_CASE						       =    logging.getLogger(__SCREAMING_SNAKE_CASE       )
					if log_level is not None:
										logger.setLevel(log_level.upper()       )
										logger.root.setLevel(log_level.upper()       )
					return MultiProcessAdapter(__SCREAMING_SNAKE_CASE  ,						{}       )




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