




"""simple docstring"""


import inspect
from typing import Optional, Union

import numpy as np
import PIL
import torch
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.utils import (
    PIL_INTERPOLATION,
    randn_tensor,
)


def  UpperCAmelCase__     (snake_case__							: int		,       snake_case__							: Optional[int]		,       snake_case__							: Tuple   ):
  """simple docstring"""

  if isinstance(snake_case__		,       torch.Tensor   ):
    return image
  elif isinstance(snake_case__		,       PIL.Image.Image   ):
    _snake_case							:		Tuple								=  [image]

  if isinstance(image[0]		,       PIL.Image.Image   ):
    _snake_case							:		Union[str, Any]								=  [np.array(i.resize((w, h)		,       resample=PIL_INTERPOLATION["""lanczos"""]   )   )[None, :] for i in image]
    _snake_case							:		Tuple								=  np.concatenate(snake_case__		,       axis=0   )
    _snake_case							:		Union[str, Any]								=  np.array(snake_case__   ).astype(np.floataa   ) / 2_55.0
    _snake_case							:		str								=  image.transpose(0		,       3		,       1		,       2   )
    _snake_case							:		Optional[Any]								=  2.0 * image - 1.0
    _snake_case							:		List[str]								=  torch.from_numpy(snake_case__   )
  elif isinstance(image[0]		,       torch.Tensor   ):
    _snake_case							:		Any								=  torch.cat(snake_case__		,       dim=0   )
  return image


def  UpperCAmelCase__     (snake_case__							: Union[str, Any]		,       snake_case__							: List[str]		,       snake_case__							: Optional[int]		,       snake_case__							: str=0.99_95   ):
  """simple docstring"""

  if not isinstance(snake_case__		,       np.ndarray   ):
    _snake_case							:		Any								=  True
    _snake_case							:		List[str]								=  va.device
    _snake_case							:		Optional[Any]								=  va.cpu().numpy()
    _snake_case							:		Union[str, Any]								=  va.cpu().numpy()

  _snake_case							:		str								=  np.sum(va * va / (np.linalg.norm(snake_case__   ) * np.linalg.norm(snake_case__   ))   )
  if np.abs(snake_case__   ) > DOT_THRESHOLD:
    _snake_case							:		Tuple								=  (1 - t) * va + t * va
  else:
    _snake_case							:		Tuple								=  np.arccos(snake_case__   )
    _snake_case							:		List[Any]								=  np.sin(snake_case__   )
    _snake_case							:		Optional[int]								=  theta_a * t
    _snake_case							:		Optional[int]								=  np.sin(snake_case__   )
    _snake_case							:		str								=  np.sin(theta_a - theta_t   ) / sin_theta_a
    _snake_case							:		Tuple								=  sin_theta_t / sin_theta_a
    _snake_case							:		Union[str, Any]								=  sa * va + sa * va

  if inputs_are_torch:
    _snake_case							:		int								=  torch.from_numpy(snake_case__   ).to(snake_case__   )

  return va


def  UpperCAmelCase__     (snake_case__							: List[Any]		,       snake_case__							: int   ):
  """simple docstring"""

  _snake_case							:		Union[str, Any]								=  F.normalize(snake_case__		,       dim=-1   )
  _snake_case							:		Optional[Any]								=  F.normalize(snake_case__		,       dim=-1   )
  return (x - y).norm(dim=-1   ).div(2   ).arcsin().pow(2   ).mul(2   )


def  UpperCAmelCase__     (snake_case__							: Any		,       snake_case__							: str   ):
  """simple docstring"""

  for param in model.parameters():
    _snake_case							:		Dict								=  value






class  lowercase(					__a			):







 '''simple docstring'''





 def __init__(    self:		Any,				a_:		AutoencoderKL,				a_:		CLIPTextModel,				a_:		CLIPModel,				a_:		CLIPTokenizer,				a_:		UNetaDConditionModel,				a_:		Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler],				a_:		CLIPFeatureExtractor,				a_:		int=None,				a_:		Optional[int]=None,				a_:		List[str]=None,				):




   '''simple docstring'''



   super().__init__()
   self.register_modules(
       vae=a_,				text_encoder=a_,				clip_model=a_,				tokenizer=a_,				unet=a_,				scheduler=a_,				feature_extractor=a_,				coca_model=a_,				coca_tokenizer=a_,				coca_transform=a_,				)
   _snake_case							:		Any								=  (
       feature_extractor.size
       if isinstance(feature_extractor.size,				a_		)
       else feature_extractor.size["""shortest_edge"""]
   )
   _snake_case							:		List[Any]								=  transforms.Normalize(mean=feature_extractor.image_mean,				std=feature_extractor.image_std		)
   set_requires_grad(self.text_encoder,				a_		)
   set_requires_grad(self.clip_model,				a_		)


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		Optional[Union[str, int]] = "auto"		):




   '''simple docstring'''



   if slice_size == "auto":
     # half the attention head size is usually a good trade-off between
     # speed and memory
     _snake_case							:		str								=  self.unet.config.attention_head_dim // 2
   self.unet.set_attention_slice(a_		)


 def 			UpperCamelCase_       (    self:		List[str]		):




   '''simple docstring'''



   self.enable_attention_slicing(a_		)


 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   set_requires_grad(self.vae,				a_		)


 def 			UpperCamelCase_       (    self:		Optional[Any]		):




   '''simple docstring'''



   set_requires_grad(self.vae,				a_		)


 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   set_requires_grad(self.unet,				a_		)


 def 			UpperCamelCase_       (    self:		List[str]		):




   '''simple docstring'''



   set_requires_grad(self.unet,				a_		)


 def 			UpperCamelCase_       (    self:		Optional[Any],				a_:		Optional[int],				a_:		Union[str, Any],				a_:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		Any								=  min(int(num_inference_steps * strength		),				a_		)

   _snake_case							:		Union[str, Any]								=  max(num_inference_steps - init_timestep,				0		)
   _snake_case							:		int								=  self.scheduler.timesteps[t_start:]

   return timesteps, num_inference_steps - t_start


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		List[Any],				a_:		int,				a_:		Tuple,				a_:		List[Any],				a_:		Tuple,				a_:		str=None		):




   '''simple docstring'''



   if not isinstance(a_,				torch.Tensor		):
     raise ValueError(f"`image` has to be of type `torch.Tensor` but is {type(a_		)}"		)

   _snake_case							:		Tuple								=  image.to(device=a_,				dtype=a_		)

   if isinstance(a_,				a_		):
     _snake_case							:		Union[str, Any]								=  [
         self.vae.encode(image[i : i + 1]		).latent_dist.sample(generator[i]		) for i in range(a_		)
     ]
     _snake_case							:		int								=  torch.cat(a_,				dim=0		)
   else:
     _snake_case							:		int								=  self.vae.encode(a_		).latent_dist.sample(a_		)

   # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
   _snake_case							:		Dict								=  0.18_215 * init_latents
   _snake_case							:		str								=  init_latents.repeat_interleave(a_,				dim=0		)

   _snake_case							:		str								=  randn_tensor(init_latents.shape,				generator=a_,				device=a_,				dtype=a_		)

   # get latents
   _snake_case							:		int								=  self.scheduler.add_noise(a_,				a_,				a_		)
   _snake_case							:		Tuple								=  init_latents

   return latents


 def 			UpperCamelCase_       (    self:		Tuple,				a_:		Any		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  self.coca_transform(a_		).unsqueeze(0		)
   with torch.no_grad(), torch.cuda.amp.autocast():
     _snake_case							:		Tuple								=  self.coca_model.generate(transformed_image.to(device=self.device,				dtype=self.coca_model.dtype		)		)
   _snake_case							:		Union[str, Any]								=  self.coca_tokenizer.decode(generated[0].cpu().numpy()		)
   return generated.split("""<end_of_text>"""		)[0].replace("""<start_of_text>""",				""""""		).rstrip(""" .,"""		)


 def 			UpperCamelCase_       (    self:		int,				a_:		str,				a_:		Tuple		):




   '''simple docstring'''



   _snake_case							:		List[str]								=  self.feature_extractor.preprocess(a_		)
   _snake_case							:		str								=  torch.from_numpy(clip_image_input["""pixel_values"""][0]		).unsqueeze(0		).to(self.device		).half()
   _snake_case							:		int								=  self.clip_model.get_image_features(a_		)
   _snake_case							:		Optional[Any]								=  image_embeddings_clip / image_embeddings_clip.norm(p=2,				dim=-1,				keepdim=a_		)
   _snake_case							:		Union[str, Any]								=  image_embeddings_clip.repeat_interleave(a_,				dim=0		)
   return image_embeddings_clip


 @torch.enable_grad()
 def 			UpperCamelCase_       (    self:		Any,				a_:		Optional[int],				a_:		Tuple,				a_:		Dict,				a_:		Tuple,				a_:		str,				a_:		List[str],				a_:		str,				):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  latents.detach().requires_grad_()

   _snake_case							:		Optional[Any]								=  self.scheduler.scale_model_input(a_,				a_		)

   # predict the noise residual
   _snake_case							:		str								=  self.unet(a_,				a_,				encoder_hidden_states=a_		).sample

   if isinstance(self.scheduler,				(PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)		):
     _snake_case							:		int								=  self.scheduler.alphas_cumprod[timestep]
     _snake_case							:		Optional[Any]								=  1 - alpha_prod_t
     # compute predicted original sample from predicted noise also called
     # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
     _snake_case							:		List[str]								=  (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

     _snake_case							:		Union[str, Any]								=  torch.sqrt(a_		)
     _snake_case							:		Optional[Any]								=  pred_original_sample * (fac) + latents * (1 - fac)
   elif isinstance(self.scheduler,				a_		):
     _snake_case							:		Optional[int]								=  self.scheduler.sigmas[index]
     _snake_case							:		int								=  latents - sigma * noise_pred
   else:
     raise ValueError(f"scheduler type {type(self.scheduler		)} not supported"		)

   # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
   _snake_case							:		List[Any]								=  1 / 0.18_215 * sample
   _snake_case							:		List[str]								=  self.vae.decode(a_		).sample
   _snake_case							:		Tuple								=  (image / 2 + 0.5).clamp(0,				1		)

   _snake_case							:		int								=  transforms.Resize(self.feature_extractor_size		)(a_		)
   _snake_case							:		str								=  self.normalize(a_		).to(latents.dtype		)

   _snake_case							:		Dict								=  self.clip_model.get_image_features(a_		)
   _snake_case							:		Union[str, Any]								=  image_embeddings_clip / image_embeddings_clip.norm(p=2,				dim=-1,				keepdim=a_		)

   _snake_case							:		Any								=  spherical_dist_loss(a_,				a_		).mean() * clip_guidance_scale

   _snake_case							:		str								=  -torch.autograd.grad(a_,				a_		)[0]

   if isinstance(self.scheduler,				a_		):
     _snake_case							:		Dict								=  latents.detach() + grads * (sigma**2)
     _snake_case							:		List[str]								=  noise_pred_original
   else:
     _snake_case							:		List[Any]								=  noise_pred_original - torch.sqrt(a_		) * grads
   return noise_pred, latents


 @torch.no_grad()
 def __call__(    self:		List[Any],				a_:		Union[torch.FloatTensor, PIL.Image.Image],				a_:		Union[torch.FloatTensor, PIL.Image.Image],				a_:		Optional[str] = None,				a_:		Optional[str] = None,				a_:		Optional[int] = 512,				a_:		Optional[int] = 512,				a_:		float = 0.6,				a_:		Optional[int] = 50,				a_:		Optional[float] = 7.5,				a_:		Optional[int] = 1,				a_:		float = 0.0,				a_:		Optional[float] = 100,				a_:		Optional[torch.Generator] = None,				a_:		Optional[str] = "pil",				a_:		bool = True,				a_:		float = 0.8,				a_:		float = 0.1,				a_:		float = 0.1,				):




   '''simple docstring'''



   if isinstance(a_,				a_		) and len(a_		) != batch_size:
     raise ValueError(f"You have passed {batch_size} batch_size, but only {len(a_		)} generators."		)

   if height % 8 != 0 or width % 8 != 0:
     raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}."		)

   if isinstance(a_,				torch.Generator		) and batch_size > 1:
     _snake_case							:		Union[str, Any]								=  [generator] + [None] * (batch_size - 1)

   _snake_case							:		List[str]								=  [
       ("""model""", self.coca_model is None),
       ("""tokenizer""", self.coca_tokenizer is None),
       ("""transform""", self.coca_transform is None),
   ]
   _snake_case							:		List[str]								=  [x[0] for x in coca_is_none if x[1]]
   _snake_case							:		Dict								=  """, """.join(a_		)
   # generate prompts with coca model if prompt is None
   if content_prompt is None:
     if len(a_		):
       raise ValueError(
           f"Content prompt is None and CoCa [{coca_is_none_str}] is None."
           f"Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline."		)
     _snake_case							:		Union[str, Any]								=  self.get_image_description(a_		)
   if style_prompt is None:
     if len(a_		):
       raise ValueError(
           f"Style prompt is None and CoCa [{coca_is_none_str}] is None."
           f" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline."		)
     _snake_case							:		Union[str, Any]								=  self.get_image_description(a_		)

   # get prompt text embeddings for content and style
   _snake_case							:		Union[str, Any]								=  self.tokenizer(
       a_,				padding="""max_length""",				max_length=self.tokenizer.model_max_length,				truncation=a_,				return_tensors="""pt""",				)
   _snake_case							:		Optional[Any]								=  self.text_encoder(content_text_input.input_ids.to(self.device		)		)[0]

   _snake_case							:		Optional[int]								=  self.tokenizer(
       a_,				padding="""max_length""",				max_length=self.tokenizer.model_max_length,				truncation=a_,				return_tensors="""pt""",				)
   _snake_case							:		Union[str, Any]								=  self.text_encoder(style_text_input.input_ids.to(self.device		)		)[0]

   _snake_case							:		Dict								=  slerp(a_,				a_,				a_		)

   # duplicate text embeddings for each generation per prompt
   _snake_case							:		List[Any]								=  text_embeddings.repeat_interleave(a_,				dim=0		)

   # set timesteps
   _snake_case							:		List[Any]								=  """offset""" in set(inspect.signature(self.scheduler.set_timesteps		).parameters.keys()		)
   _snake_case							:		Dict								=  {}
   if accepts_offset:
     _snake_case							:		Optional[Any]								=  1

   self.scheduler.set_timesteps(a_,				**a_		)
   # Some schedulers like PNDM have timesteps as arrays
   # It's more optimized to move all timesteps to correct device beforehand
   self.scheduler.timesteps.to(self.device		)

   _snake_case							:		Optional[Any]								=  self.get_timesteps(a_,				a_,				self.device		)
   _snake_case							:		List[str]								=  timesteps[:1].repeat(a_		)

   # Preprocess image
   _snake_case							:		List[Any]								=  preprocess(a_,				a_,				a_		)
   _snake_case							:		Tuple								=  self.prepare_latents(
       a_,				a_,				a_,				text_embeddings.dtype,				self.device,				a_		)

   _snake_case							:		List[Any]								=  preprocess(a_,				a_,				a_		)
   _snake_case							:		Tuple								=  self.prepare_latents(
       a_,				a_,				a_,				text_embeddings.dtype,				self.device,				a_		)

   _snake_case							:		str								=  slerp(a_,				a_,				a_		)

   if clip_guidance_scale > 0:
     _snake_case							:		int								=  self.get_clip_image_embeddings(a_,				a_		)
     _snake_case							:		str								=  self.get_clip_image_embeddings(a_,				a_		)
     _snake_case							:		str								=  slerp(
         a_,				a_,				a_		)

   # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
   # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
   # corresponds to doing no classifier free guidance.
   _snake_case							:		List[str]								=  guidance_scale > 1.0
   # get unconditional embeddings for classifier free guidance
   if do_classifier_free_guidance:
     _snake_case							:		str								=  content_text_input.input_ids.shape[-1]
     _snake_case							:		Optional[int]								=  self.tokenizer([""""""],				padding="""max_length""",				max_length=a_,				return_tensors="""pt"""		)
     _snake_case							:		List[str]								=  self.text_encoder(uncond_input.input_ids.to(self.device		)		)[0]
     # duplicate unconditional embeddings for each generation per prompt
     _snake_case							:		List[str]								=  uncond_embeddings.repeat_interleave(a_,				dim=0		)

     # For classifier free guidance, we need to do two forward passes.
     # Here we concatenate the unconditional and text embeddings into a single batch
     # to avoid doing two forward passes
     _snake_case							:		Dict								=  torch.cat([uncond_embeddings, text_embeddings]		)

   # get the initial random noise unless the user supplied it

   # Unlike in other pipelines, latents need to be generated in the target device
   # for 1-to-1 results reproducibility with the CompVis implementation.
   # However this currently doesn't work in `mps`.
   _snake_case							:		str								=  (batch_size, self.unet.config.in_channels, height // 8, width // 8)
   _snake_case							:		List[Any]								=  text_embeddings.dtype
   if latents is None:
     if self.device.type == "mps":
       # randn does not work reproducibly on mps
       _snake_case							:		Dict								=  torch.randn(a_,				generator=a_,				device="""cpu""",				dtype=a_		).to(
           self.device		)
     else:
       _snake_case							:		Any								=  torch.randn(a_,				generator=a_,				device=self.device,				dtype=a_		)
   else:
     if latents.shape != latents_shape:
       raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"		)
     _snake_case							:		Union[str, Any]								=  latents.to(self.device		)

   # scale the initial noise by the standard deviation required by the scheduler
   _snake_case							:		Union[str, Any]								=  latents * self.scheduler.init_noise_sigma

   # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
   # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
   # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
   # and should be between [0, 1]
   _snake_case							:		Any								=  """eta""" in set(inspect.signature(self.scheduler.step		).parameters.keys()		)
   _snake_case							:		Tuple								=  {}
   if accepts_eta:
     _snake_case							:		Optional[int]								=  eta

   # check if the scheduler accepts generator
   _snake_case							:		Tuple								=  """generator""" in set(inspect.signature(self.scheduler.step		).parameters.keys()		)
   if accepts_generator:
     _snake_case							:		Any								=  generator

   with self.progress_bar(total=a_		):
     for i, t in enumerate(a_		):
       # expand the latents if we are doing classifier free guidance
       _snake_case							:		Dict								=  torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
       _snake_case							:		Optional[Any]								=  self.scheduler.scale_model_input(a_,				a_		)

       # predict the noise residual
       _snake_case							:		Tuple								=  self.unet(a_,				a_,				encoder_hidden_states=a_		).sample

       # perform classifier free guidance
       if do_classifier_free_guidance:
         _snake_case							:		List[str]								=  noise_pred.chunk(2		)
         _snake_case							:		Any								=  noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

       # perform clip guidance
       if clip_guidance_scale > 0:
         _snake_case							:		int								=  (
             text_embeddings.chunk(2		)[1] if do_classifier_free_guidance else text_embeddings
         )
         _snake_case							:		Any								=  self.cond_fn(
             a_,				a_,				a_,				a_,				a_,				a_,				a_,				)

       # compute the previous noisy sample x_t -> x_t-1
       _snake_case							:		int								=  self.scheduler.step(a_,				a_,				a_,				**a_		).prev_sample

        # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
   _snake_case							:		Optional[Any]								=  1 / 0.18_215 * latents
   _snake_case							:		Tuple								=  self.vae.decode(a_		).sample

   _snake_case							:		Optional[int]								=  (image / 2 + 0.5).clamp(0,				1		)
   _snake_case							:		List[str]								=  image.cpu().permute(0,				2,				3,				1		).numpy()

   if output_type == "pil":
     _snake_case							:		List[Any]								=  self.numpy_to_pil(a_		)

   if not return_dict:
     return (image, None)

   return StableDiffusionPipelineOutput(images=a_,				nsfw_content_detected=a_		)








"""simple docstring"""


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


A_      =    logging.get_logger(__name__)


def  UpperCAmelCase__	(snake_case__							: List[str]		,       snake_case__							: Dict		,       snake_case__							: Union[str, Any]		,       snake_case__							: int=False   ):
  """simple docstring"""

  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:
    _snake_case							:		Dict								=  os.path.abspath(snake_case__   )
    logger.info(F"Loading PyTorch weights from {pt_path}"   )

    _snake_case							:		Tuple								=  torch.load(snake_case__		,       map_location="""cpu"""   )
    logger.info(F"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()   ):,} parameters."   )

    _snake_case							:		int								=  convert_pytorch_state_dict_to_flax(snake_case__		,       snake_case__   )
  else:
    # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files
    _snake_case							:		Dict								=  convert_pytorch_sharded_state_dict_to_flax(snake_case__		,       snake_case__   )
  return flax_state_dict


def  UpperCAmelCase__	(snake_case__							: Tuple[str]		,       snake_case__							: np.ndarray		,       snake_case__							: Dict[str, jnp.ndarray]		,       snake_case__							: str		,       ):
  """simple docstring"""

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

  # layer norm
  _snake_case							:		Any								=  pt_tuple_key[:-1] + ("""scale""",)
  if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(snake_case__   ):
    return renamed_pt_tuple_key, pt_tensor

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

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

  # embedding
  _snake_case							:		Any								=  pt_tuple_key[:-1] + ("""embedding""",)
  if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(snake_case__   ):
    return renamed_pt_tuple_key, pt_tensor

  # conv layer
  _snake_case							:		Optional[int]								=  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(snake_case__   ):
    _snake_case							:		Dict								=  pt_tensor.transpose(2		,       3		,       1		,       0   )
    return renamed_pt_tuple_key, pt_tensor

  # linear layer
  _snake_case							:		List[str]								=  pt_tuple_key[:-1] + ("""kernel""",)
  if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(snake_case__   ):
    _snake_case							:		List[Any]								=  pt_tensor.T
    return renamed_pt_tuple_key, pt_tensor

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

  # old PyTorch layer norm bias
  _snake_case							:		Tuple								=  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
  _snake_case							:		Optional[Any]								=  None
  if pt_tuple_key[-3::2] == ("parametrizations", "original0"):
    _snake_case							:		Union[str, Any]								=  pt_tuple_key[-2] + """_g"""
  elif pt_tuple_key[-3::2] == ("parametrizations", "original1"):
    _snake_case							:		Dict								=  pt_tuple_key[-2] + """_v"""
  if name is not None:
    _snake_case							:		Union[str, Any]								=  pt_tuple_key[:-3] + (name,)
    return renamed_pt_tuple_key, pt_tensor

  return pt_tuple_key, pt_tensor


def  UpperCAmelCase__	(snake_case__							: Union[str, Any]		,       snake_case__							: Optional[int]   ):
  """simple docstring"""

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

  _snake_case							:		int								=  flax_model.base_model_prefix

  # use params dict if the model contains batch norm layers
  if "params" in flax_model.params:
    _snake_case							:		Dict								=  flax_model.params["""params"""]
  else:
    _snake_case							:		List[Any]								=  flax_model.params
  _snake_case							:		Tuple								=  flatten_dict(snake_case__   )

  # add batch_stats keys,values to dict
  if "batch_stats" in flax_model.params:
    _snake_case							:		Union[str, Any]								=  flatten_dict(flax_model.params["""batch_stats"""]   )
    random_flax_state_dict.update(snake_case__   )

  _snake_case							:		Tuple								=  {}

  _snake_case							:		Dict								=  (model_prefix not in flax_model_params) and (
      model_prefix in {k.split("""."""   )[0] for k in pt_state_dict.keys()}
  )
  _snake_case							:		Optional[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():
    _snake_case							:		int								=  tuple(pt_key.split("""."""   )   )

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

    # Correctly rename weight parameters
    _snake_case		, _snake_case							:		int								=  rename_key_and_reshape_tensor(
        snake_case__		,       snake_case__		,       snake_case__		,       snake_case__   )

    # add model prefix if necessary
    _snake_case							:		Dict								=  (model_prefix,) + flax_key in random_flax_state_dict
    if load_base_model_into_model_with_head and require_base_model_prefix:
      _snake_case							:		int								=  (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]:
        _snake_case							:		Union[str, Any]								=  jnp.asarray(snake_case__   )
        continue
      # remove num_batches_tracked key
      if "num_batches_tracked" in flax_key[-1]:
        flax_state_dict.pop(snake_case__		,       snake_case__   )
        continue

      # also add unexpected weight so that warning is thrown
      _snake_case							:		List[Any]								=  jnp.asarray(snake_case__   )

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

  return unflatten_dict(snake_case__   )


def  UpperCAmelCase__	(snake_case__							: Optional[int]		,       snake_case__							: Dict   ):
  """simple docstring"""

  import torch

  # Load the index
  _snake_case							:		str								=  {}
  for shard_file in shard_filenames:
    # load using msgpack utils
    _snake_case							:		Union[str, Any]								=  torch.load(snake_case__   )
    _snake_case							:		Optional[Any]								=  {k: v.numpy() for k, v in pt_state_dict.items()}

    _snake_case							:		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:
      _snake_case							:		str								=  flax_model.params["""params"""]

      _snake_case							:		List[Any]								=  flatten_dict(snake_case__   )
      random_flax_state_dict.update(flatten_dict(flax_model.params["""batch_stats"""]   )   )
    else:
      _snake_case							:		List[Any]								=  flax_model.params
      _snake_case							:		Tuple								=  flatten_dict(snake_case__   )

    _snake_case							:		Tuple								=  (model_prefix not in flax_model_params) and (
        model_prefix in {k.split("""."""   )[0] for k in pt_state_dict.keys()}
    )
    _snake_case							:		Optional[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():
      _snake_case							:		List[str]								=  tuple(pt_key.split("""."""   )   )

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

      # Correctly rename weight parameters
      _snake_case		, _snake_case							:		Optional[Any]								=  rename_key_and_reshape_tensor(
          snake_case__		,       snake_case__		,       snake_case__		,       snake_case__   )
      # add model prefix if necessary
      _snake_case							:		List[str]								=  (model_prefix,) + flax_key in random_flax_state_dict
      if load_base_model_into_model_with_head and require_base_model_prefix:
        _snake_case							:		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]:
          _snake_case							:		Optional[int]								=  jnp.asarray(snake_case__   )
          continue
        if "var" in flax_key[-1]:
          _snake_case							:		Any								=  jnp.asarray(snake_case__   )
          continue
        # remove num_batches_tracked key
        if "num_batches_tracked" in flax_key[-1]:
          flax_state_dict.pop(snake_case__		,       snake_case__   )
          continue

        # also add unexpected weight so that warning is thrown
        _snake_case							:		List[str]								=  jnp.asarray(snake_case__   )

      else:
        # also add unexpected weight so that warning is thrown
        _snake_case							:		Optional[Any]								=  jnp.asarray(snake_case__   )
  return unflatten_dict(snake_case__   )


def  UpperCAmelCase__	(snake_case__							: List[str]		,       snake_case__							: Optional[Any]   ):
  """simple docstring"""

  _snake_case							:		Optional[Any]								=  os.path.abspath(snake_case__   )
  logger.info(F"Loading Flax weights from {flax_checkpoint_path}"   )

  # import correct flax class
  _snake_case							:		Union[str, Any]								=  getattr(snake_case__		,       """Flax""" + model.__class__.__name__   )

  # load flax weight dict
  with open(snake_case__		,       """rb"""   ) as state_f:
    try:
      _snake_case							:		Dict								=  from_bytes(snake_case__		,       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(snake_case__		,       snake_case__   )






def  UpperCAmelCase__	(snake_case__							: Tuple		,       snake_case__							: Optional[int]   ):
  """simple docstring"""

  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
  _snake_case							:		Optional[int]								=  flatten_dict(jax.tree_util.tree_map(lambda snake_case__   : x.dtype == jnp.bfloataa		,       snake_case__   )   ).values()
  if any(snake_case__   ):
    # 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."""   )
    _snake_case							:		Optional[int]								=  jax.tree_util.tree_map(
        lambda snake_case__   : params.astype(np.floataa   ) if params.dtype == jnp.bfloataa else params		,       snake_case__   )

  _snake_case							:		Dict								=  flatten_dict(snake_case__   )
  _snake_case							:		Optional[Any]								=  pt_model.state_dict()

  _snake_case							:		Union[str, Any]								=  (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()}
  )
  _snake_case							:		Optional[int]								=  (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
  _snake_case							:		str								=  []
  _snake_case							:		Tuple								=  set(pt_model_dict.keys()   )

  for flax_key_tuple, flax_tensor in flax_state_dict.items():
    _snake_case							:		Tuple								=  flax_key_tuple[0] == pt_model.base_model_prefix
    _snake_case							:		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:
      _snake_case							:		List[str]								=  flax_key_tuple[1:]
    elif load_base_model_into_model_with_head and require_base_model_prefix:
      _snake_case							:		Union[str, Any]								=  (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(snake_case__   ) not in pt_model_dict:
      # conv layer
      _snake_case							:		Union[str, Any]								=  flax_key_tuple[:-1] + ("""weight""",)
      _snake_case							:		Optional[int]								=  jnp.transpose(snake_case__		,       (3, 2, 0, 1)   )
    elif flax_key_tuple[-1] == "kernel" and ".".join(snake_case__   ) not in pt_model_dict:
      # linear layer
      _snake_case							:		Optional[int]								=  flax_key_tuple[:-1] + ("""weight""",)
      _snake_case							:		Union[str, Any]								=  flax_tensor.T
    elif flax_key_tuple[-1] in ["scale", "embedding"]:
      _snake_case							:		int								=  flax_key_tuple[:-1] + ("""weight""",)

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

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

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

    if flax_key in special_pt_names:
      _snake_case							:		Union[str, 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
        _snake_case							:		List[str]								=  np.asarray(snake_case__   ) if not isinstance(snake_case__		,       np.ndarray   ) else flax_tensor
        _snake_case							:		List[Any]								=  torch.from_numpy(snake_case__   )
        # remove from missing keys
        missing_keys.remove(snake_case__   )
    else:
      # weight is not expected by PyTorch model
      unexpected_keys.append(snake_case__   )

  pt_model.load_state_dict(snake_case__   )

  # re-transform missing_keys to list
  _snake_case							:		List[str]								=  list(snake_case__   )

  if len(snake_case__   ) > 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(snake_case__   ) > 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


