





"""simple docstring"""


import argparse
import json

import torch

from diffusers import AutoencoderKL, DDPMPipeline, DDPMScheduler, UNetaDModel, VQModel




def     lowercase__			(    lowercase_						,lowercase_=1	)    ->						Tuple:




      """simple docstring"""

      if n_shave_prefix_segments >= 0:
            return ".".join(path.split("."	)[n_shave_prefix_segments:]	)
      else:
            return ".".join(path.split("."	)[:n_shave_prefix_segments]	)




def     lowercase__			(    lowercase_						,lowercase_=0	)    ->						Optional[int]:




      """simple docstring"""

      _UpperCamelCase					:		Optional[int]  =				[]
      for old_item in old_list:
            _UpperCamelCase					:		Union[str, Any]  =				old_item
            _UpperCamelCase					:		Tuple  =				new_item.replace("block."						,"resnets."	)
            _UpperCamelCase					:		Optional[Any]  =				new_item.replace("conv_shorcut"						,"conv1"	)
            _UpperCamelCase					:		Dict  =				new_item.replace("in_shortcut"						,"conv_shortcut"	)
            _UpperCamelCase					:		Union[str, Any]  =				new_item.replace("temb_proj"						,"time_emb_proj"	)

            _UpperCamelCase					:		Dict  =				shave_segments(lowercase_						,n_shave_prefix_segments=lowercase_	)

            mapping.append({"old": old_item, "new": new_item}	)

      return mapping




def     lowercase__			(    lowercase_						,lowercase_=0						,lowercase_=False	)    ->						Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase					:		int  =				[]
      for old_item in old_list:
            _UpperCamelCase					:		List[str]  =				old_item

            # In `model.mid`, the layer is called `attn`.
            if not in_mid:
                  _UpperCamelCase					:		Optional[int]  =				new_item.replace("attn"						,"attentions"	)
            _UpperCamelCase					:		List[Any]  =				new_item.replace(".k."						,".key."	)
            _UpperCamelCase					:		Dict  =				new_item.replace(".v."						,".value."	)
            _UpperCamelCase					:		Optional[Any]  =				new_item.replace(".q."						,".query."	)

            _UpperCamelCase					:		Tuple  =				new_item.replace("proj_out"						,"proj_attn"	)
            _UpperCamelCase					:		Dict  =				new_item.replace("norm"						,"group_norm"	)

            _UpperCamelCase					:		Dict  =				shave_segments(lowercase_						,n_shave_prefix_segments=lowercase_	)
            mapping.append({"old": old_item, "new": new_item}	)

      return mapping




def     lowercase__			(    lowercase_						,lowercase_						,lowercase_						,lowercase_=None						,lowercase_=None						,lowercase_=None	)    ->						Union[str, Any]:




      """simple docstring"""

      assert isinstance(lowercase_						,lowercase_	), "Paths should be a list of dicts containing 'old' and 'new' keys."

      if attention_paths_to_split is not None:
            if config is None:
                  raise ValueError("Please specify the config if setting 'attention_paths_to_split' to 'True'."	)

            for path, path_map in attention_paths_to_split.items():
                  _UpperCamelCase					:		Dict  =				old_checkpoint[path]
                  _UpperCamelCase					:		Dict  =				old_tensor.shape[0] // 3

                  _UpperCamelCase					:		List[Any]  =				(-1, channels) if len(old_tensor.shape	) == 3 else (-1)

                  _UpperCamelCase					:		List[str]  =				old_tensor.shape[0] // config.get("num_head_channels"						,1	) // 3

                  _UpperCamelCase					:		Union[str, Any]  =				old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:]	)
                  _UpperCamelCase,     _UpperCamelCase,     _UpperCamelCase					:		Any  =				old_tensor.split(channels // num_heads						,dim=1	)

                  _UpperCamelCase					:		Any  =				query.reshape(lowercase_	).squeeze()
                  _UpperCamelCase					:		List[Any]  =				key.reshape(lowercase_	).squeeze()
                  _UpperCamelCase					:		Dict  =				value.reshape(lowercase_	).squeeze()

      for path in paths:
            _UpperCamelCase					:		Union[str, Any]  =				path["new"]

            if attention_paths_to_split is not None and new_path in attention_paths_to_split:
                  continue

            _UpperCamelCase					:		Any  =				new_path.replace("down."						,"down_blocks."	)
            _UpperCamelCase					:		int  =				new_path.replace("up."						,"up_blocks."	)

            if additional_replacements is not None:
                  for replacement in additional_replacements:
                        _UpperCamelCase					:		Union[str, Any]  =				new_path.replace(replacement["old"]						,replacement["new"]	)

            if "attentions" in new_path:
                  _UpperCamelCase					:		Dict  =				old_checkpoint[path["old"]].squeeze()
            else:
                  _UpperCamelCase					:		List[str]  =				old_checkpoint[path["old"]]




def     lowercase__			(    lowercase_						,lowercase_	)    ->						int:




      """simple docstring"""

      _UpperCamelCase					:		List[Any]  =				{}

      _UpperCamelCase					:		str  =				checkpoint["temb.dense.0.weight"]
      _UpperCamelCase					:		List[Any]  =				checkpoint["temb.dense.0.bias"]
      _UpperCamelCase					:		Optional[int]  =				checkpoint["temb.dense.1.weight"]
      _UpperCamelCase					:		Dict  =				checkpoint["temb.dense.1.bias"]

      _UpperCamelCase					:		Optional[Any]  =				checkpoint["norm_out.weight"]
      _UpperCamelCase					:		int  =				checkpoint["norm_out.bias"]

      _UpperCamelCase					:		str  =				checkpoint["conv_in.weight"]
      _UpperCamelCase					:		List[str]  =				checkpoint["conv_in.bias"]
      _UpperCamelCase					:		Optional[int]  =				checkpoint["conv_out.weight"]
      _UpperCamelCase					:		Dict  =				checkpoint["conv_out.bias"]

      _UpperCamelCase					:		Dict  =				len({".".join(layer.split("."	)[:2]	) for layer in checkpoint if "down" in layer}	)
      _UpperCamelCase					:		List[str]  =				{
          layer_id: [key for key in checkpoint if F'''down.{layer_id}''' in key] for layer_id in range(lowercase_	)
      }

      _UpperCamelCase					:		List[str]  =				len({".".join(layer.split("."	)[:2]	) for layer in checkpoint if "up" in layer}	)
      _UpperCamelCase					:		Dict  =				{layer_id: [key for key in checkpoint if F'''up.{layer_id}''' in key] for layer_id in range(lowercase_	)}

      for i in range(lowercase_	):
            _UpperCamelCase					:		Union[str, Any]  =				(i - 1) // (config["layers_per_block"] + 1)

            if any("downsample" in layer for layer in down_blocks[i]	):
                  _UpperCamelCase					:		Tuple  =				checkpoint[
                      F'''down.{i}.downsample.op.weight'''
                  ]
                  _UpperCamelCase					:		List[str]  =				checkpoint[F'''down.{i}.downsample.op.bias''']
            #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.weight'] = checkpoint[f'down.{i}.downsample.conv.weight']
            #            new_checkpoint[f'down_blocks.{i}.downsamplers.0.op.bias'] = checkpoint[f'down.{i}.downsample.conv.bias']

            if any("block" in layer for layer in down_blocks[i]	):
                  _UpperCamelCase					:		Union[str, Any]  =				len(
                      {".".join(shave_segments(lowercase_						,2	).split("."	)[:2]	) for layer in down_blocks[i] if "block" in layer}	)
                  _UpperCamelCase					:		List[Any]  =				{
                      layer_id: [key for key in down_blocks[i] if F'''block.{layer_id}''' in key]
                      for layer_id in range(lowercase_	)
                  }

                  if num_blocks > 0:
                        for j in range(config["layers_per_block"]	):
                              _UpperCamelCase					:		Any  =				renew_resnet_paths(blocks[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_	)

            if any("attn" in layer for layer in down_blocks[i]	):
                  _UpperCamelCase					:		Any  =				len(
                      {".".join(shave_segments(lowercase_						,2	).split("."	)[:2]	) for layer in down_blocks[i] if "attn" in layer}	)
                  _UpperCamelCase					:		Union[str, Any]  =				{
                      layer_id: [key for key in down_blocks[i] if F'''attn.{layer_id}''' in key]
                      for layer_id in range(lowercase_	)
                  }

                  if num_attn > 0:
                        for j in range(config["layers_per_block"]	):
                              _UpperCamelCase					:		Dict  =				renew_attention_paths(attns[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_						,config=lowercase_	)

      _UpperCamelCase					:		str  =				[key for key in checkpoint if "mid.block_1" in key]
      _UpperCamelCase					:		Optional[int]  =				[key for key in checkpoint if "mid.block_2" in key]
      _UpperCamelCase					:		Dict  =				[key for key in checkpoint if "mid.attn_1" in key]

      # Mid new 2
      _UpperCamelCase					:		str  =				renew_resnet_paths(lowercase_	)
      assign_to_checkpoint(
          lowercase_						,lowercase_						,lowercase_						,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_1", "new": "resnets.0"}]						,)

      _UpperCamelCase					:		Tuple  =				renew_resnet_paths(lowercase_	)
      assign_to_checkpoint(
          lowercase_						,lowercase_						,lowercase_						,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_2", "new": "resnets.1"}]						,)

      _UpperCamelCase					:		Any  =				renew_attention_paths(lowercase_						,in_mid=lowercase_	)
      assign_to_checkpoint(
          lowercase_						,lowercase_						,lowercase_						,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "attn_1", "new": "attentions.0"}]						,)

      for i in range(lowercase_	):
            _UpperCamelCase					:		List[str]  =				num_up_blocks - 1 - i

            if any("upsample" in layer for layer in up_blocks[i]	):
                  _UpperCamelCase					:		str  =				checkpoint[
                      F'''up.{i}.upsample.conv.weight'''
                  ]
                  _UpperCamelCase					:		int  =				checkpoint[F'''up.{i}.upsample.conv.bias''']

            if any("block" in layer for layer in up_blocks[i]	):
                  _UpperCamelCase					:		str  =				len(
                      {".".join(shave_segments(lowercase_						,2	).split("."	)[:2]	) for layer in up_blocks[i] if "block" in layer}	)
                  _UpperCamelCase					:		str  =				{
                      layer_id: [key for key in up_blocks[i] if F'''block.{layer_id}''' in key] for layer_id in range(lowercase_	)
                  }

                  if num_blocks > 0:
                        for j in range(config["layers_per_block"] + 1	):
                              _UpperCamelCase					:		Dict  =				{"old": F'''up_blocks.{i}''', "new": F'''up_blocks.{block_id}'''}
                              _UpperCamelCase					:		Union[str, Any]  =				renew_resnet_paths(blocks[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_						,additional_replacements=[replace_indices]	)

            if any("attn" in layer for layer in up_blocks[i]	):
                  _UpperCamelCase					:		Tuple  =				len(
                      {".".join(shave_segments(lowercase_						,2	).split("."	)[:2]	) for layer in up_blocks[i] if "attn" in layer}	)
                  _UpperCamelCase					:		Tuple  =				{
                      layer_id: [key for key in up_blocks[i] if F'''attn.{layer_id}''' in key] for layer_id in range(lowercase_	)
                  }

                  if num_attn > 0:
                        for j in range(config["layers_per_block"] + 1	):
                              _UpperCamelCase					:		str  =				{"old": F'''up_blocks.{i}''', "new": F'''up_blocks.{block_id}'''}
                              _UpperCamelCase					:		Union[str, Any]  =				renew_attention_paths(attns[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_						,additional_replacements=[replace_indices]	)

      _UpperCamelCase					:		Tuple  =				{k.replace("mid_new_2"						,"mid_block"	): v for k, v in new_checkpoint.items()}
      return new_checkpoint




def     lowercase__			(    lowercase_						,lowercase_	)    ->						Optional[int]:




      """simple docstring"""

      _UpperCamelCase					:		int  =				{}

      _UpperCamelCase					:		List[Any]  =				checkpoint["encoder.norm_out.weight"]
      _UpperCamelCase					:		str  =				checkpoint["encoder.norm_out.bias"]

      _UpperCamelCase					:		str  =				checkpoint["encoder.conv_in.weight"]
      _UpperCamelCase					:		Tuple  =				checkpoint["encoder.conv_in.bias"]
      _UpperCamelCase					:		Optional[Any]  =				checkpoint["encoder.conv_out.weight"]
      _UpperCamelCase					:		Tuple  =				checkpoint["encoder.conv_out.bias"]

      _UpperCamelCase					:		Any  =				checkpoint["decoder.norm_out.weight"]
      _UpperCamelCase					:		str  =				checkpoint["decoder.norm_out.bias"]

      _UpperCamelCase					:		List[Any]  =				checkpoint["decoder.conv_in.weight"]
      _UpperCamelCase					:		List[Any]  =				checkpoint["decoder.conv_in.bias"]
      _UpperCamelCase					:		int  =				checkpoint["decoder.conv_out.weight"]
      _UpperCamelCase					:		Union[str, Any]  =				checkpoint["decoder.conv_out.bias"]

      _UpperCamelCase					:		Dict  =				len({".".join(layer.split("."	)[:3]	) for layer in checkpoint if "down" in layer}	)
      _UpperCamelCase					:		Dict  =				{
          layer_id: [key for key in checkpoint if F'''down.{layer_id}''' in key] for layer_id in range(lowercase_	)
      }

      _UpperCamelCase					:		str  =				len({".".join(layer.split("."	)[:3]	) for layer in checkpoint if "up" in layer}	)
      _UpperCamelCase					:		int  =				{layer_id: [key for key in checkpoint if F'''up.{layer_id}''' in key] for layer_id in range(lowercase_	)}

      for i in range(lowercase_	):
            _UpperCamelCase					:		Optional[int]  =				(i - 1) // (config["layers_per_block"] + 1)

            if any("downsample" in layer for layer in down_blocks[i]	):
                  _UpperCamelCase					:		Optional[int]  =				checkpoint[
                      F'''encoder.down.{i}.downsample.conv.weight'''
                  ]
                  _UpperCamelCase					:		Tuple  =				checkpoint[
                      F'''encoder.down.{i}.downsample.conv.bias'''
                  ]

            if any("block" in layer for layer in down_blocks[i]	):
                  _UpperCamelCase					:		Optional[int]  =				len(
                      {".".join(shave_segments(lowercase_						,3	).split("."	)[:3]	) for layer in down_blocks[i] if "block" in layer}	)
                  _UpperCamelCase					:		Tuple  =				{
                      layer_id: [key for key in down_blocks[i] if F'''block.{layer_id}''' in key]
                      for layer_id in range(lowercase_	)
                  }

                  if num_blocks > 0:
                        for j in range(config["layers_per_block"]	):
                              _UpperCamelCase					:		Tuple  =				renew_resnet_paths(blocks[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_	)

            if any("attn" in layer for layer in down_blocks[i]	):
                  _UpperCamelCase					:		Dict  =				len(
                      {".".join(shave_segments(lowercase_						,3	).split("."	)[:3]	) for layer in down_blocks[i] if "attn" in layer}	)
                  _UpperCamelCase					:		Union[str, Any]  =				{
                      layer_id: [key for key in down_blocks[i] if F'''attn.{layer_id}''' in key]
                      for layer_id in range(lowercase_	)
                  }

                  if num_attn > 0:
                        for j in range(config["layers_per_block"]	):
                              _UpperCamelCase					:		Optional[Any]  =				renew_attention_paths(attns[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_						,config=lowercase_	)

      _UpperCamelCase					:		Tuple  =				[key for key in checkpoint if "mid.block_1" in key]
      _UpperCamelCase					:		str  =				[key for key in checkpoint if "mid.block_2" in key]
      _UpperCamelCase					:		List[Any]  =				[key for key in checkpoint if "mid.attn_1" in key]

      # Mid new 2
      _UpperCamelCase					:		Any  =				renew_resnet_paths(lowercase_	)
      assign_to_checkpoint(
          lowercase_						,lowercase_						,lowercase_						,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_1", "new": "resnets.0"}]						,)

      _UpperCamelCase					:		Optional[Any]  =				renew_resnet_paths(lowercase_	)
      assign_to_checkpoint(
          lowercase_						,lowercase_						,lowercase_						,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "block_2", "new": "resnets.1"}]						,)

      _UpperCamelCase					:		Optional[int]  =				renew_attention_paths(lowercase_						,in_mid=lowercase_	)
      assign_to_checkpoint(
          lowercase_						,lowercase_						,lowercase_						,additional_replacements=[{"old": "mid.", "new": "mid_new_2."}, {"old": "attn_1", "new": "attentions.0"}]						,)

      for i in range(lowercase_	):
            _UpperCamelCase					:		Dict  =				num_up_blocks - 1 - i

            if any("upsample" in layer for layer in up_blocks[i]	):
                  _UpperCamelCase					:		Optional[Any]  =				checkpoint[
                      F'''decoder.up.{i}.upsample.conv.weight'''
                  ]
                  _UpperCamelCase					:		Tuple  =				checkpoint[
                      F'''decoder.up.{i}.upsample.conv.bias'''
                  ]

            if any("block" in layer for layer in up_blocks[i]	):
                  _UpperCamelCase					:		Optional[Any]  =				len(
                      {".".join(shave_segments(lowercase_						,3	).split("."	)[:3]	) for layer in up_blocks[i] if "block" in layer}	)
                  _UpperCamelCase					:		Optional[Any]  =				{
                      layer_id: [key for key in up_blocks[i] if F'''block.{layer_id}''' in key] for layer_id in range(lowercase_	)
                  }

                  if num_blocks > 0:
                        for j in range(config["layers_per_block"] + 1	):
                              _UpperCamelCase					:		Optional[Any]  =				{"old": F'''up_blocks.{i}''', "new": F'''up_blocks.{block_id}'''}
                              _UpperCamelCase					:		Optional[Any]  =				renew_resnet_paths(blocks[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_						,additional_replacements=[replace_indices]	)

            if any("attn" in layer for layer in up_blocks[i]	):
                  _UpperCamelCase					:		Optional[Any]  =				len(
                      {".".join(shave_segments(lowercase_						,3	).split("."	)[:3]	) for layer in up_blocks[i] if "attn" in layer}	)
                  _UpperCamelCase					:		Tuple  =				{
                      layer_id: [key for key in up_blocks[i] if F'''attn.{layer_id}''' in key] for layer_id in range(lowercase_	)
                  }

                  if num_attn > 0:
                        for j in range(config["layers_per_block"] + 1	):
                              _UpperCamelCase					:		int  =				{"old": F'''up_blocks.{i}''', "new": F'''up_blocks.{block_id}'''}
                              _UpperCamelCase					:		List[str]  =				renew_attention_paths(attns[j]	)
                              assign_to_checkpoint(lowercase_						,lowercase_						,lowercase_						,additional_replacements=[replace_indices]	)

      _UpperCamelCase					:		Optional[int]  =				{k.replace("mid_new_2"						,"mid_block"	): v for k, v in new_checkpoint.items()}
      _UpperCamelCase					:		List[str]  =				checkpoint["quant_conv.weight"]
      _UpperCamelCase					:		Any  =				checkpoint["quant_conv.bias"]
      if "quantize.embedding.weight" in checkpoint:
            _UpperCamelCase					:		List[Any]  =				checkpoint["quantize.embedding.weight"]
      _UpperCamelCase					:		List[Any]  =				checkpoint["post_quant_conv.weight"]
      _UpperCamelCase					:		Optional[int]  =				checkpoint["post_quant_conv.bias"]

      return new_checkpoint


if __name__ == "__main__":
  lowerCamelCase__      =      argparse.ArgumentParser()

  parser.add_argument(
      "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."
  )

  parser.add_argument(
      "--config_file",
      default=None,
      type=str,
      required=True,
      help="The config json file corresponding to the architecture.",
  )

  parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")

  lowerCamelCase__      =      parser.parse_args()
  lowerCamelCase__      =      torch.load(args.checkpoint_path)

  with open(args.config_file) as f:
    lowerCamelCase__      =      json.loads(f.read())

  # unet case
  lowerCamelCase__      =      {key.split(".")[0] for key in checkpoint.keys()}
  if "encoder" in key_prefix_set and "decoder" in key_prefix_set:
    lowerCamelCase__      =      convert_vq_autoenc_checkpoint(checkpoint, config)
  else:
    lowerCamelCase__      =      convert_ddpm_checkpoint(checkpoint, config)

  if "ddpm" in config:
    del config["ddpm"]

  if config["_class_name"] == "VQModel":
    lowerCamelCase__      =      VQModel(**config)
    model.load_state_dict(converted_checkpoint)
    model.save_pretrained(args.dump_path)
  elif config["_class_name"] == "AutoencoderKL":
    lowerCamelCase__      =      AutoencoderKL(**config)
    model.load_state_dict(converted_checkpoint)
    model.save_pretrained(args.dump_path)
  else:
    lowerCamelCase__      =      UNetaDModel(**config)
    model.load_state_dict(converted_checkpoint)

    lowerCamelCase__      =      DDPMScheduler.from_config("/".join(args.checkpoint_path.split("/")[:-1]))

    lowerCamelCase__      =      DDPMPipeline(unet=model, scheduler=scheduler)
    pipe.save_pretrained(args.dump_path)







"""simple docstring"""


from typing import Optional, Tuple

import flax.linen as nn
import jax
import jax.numpy as jnp
from configuration_hybrid_clip import HybridCLIPConfig
from flax.core.frozen_dict import FrozenDict

from transformers import FLAX_MODEL_MAPPING, FlaxCLIPVisionModel
from transformers.modeling_flax_utils import FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPOutput
from transformers.utils import logging


lowerCamelCase__      =      logging.get_logger(__name__)



class    __SCREAMING_SNAKE_CASE			(  nn.Module      ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:HybridCLIPConfig
  SCREAMING_SNAKE_CASE__							:jnp.dtype		   =    jnp.floataa

  def       __SCREAMING_SNAKE_CASE (						self      :				List[str]		)						-> Tuple:
        _UpperCamelCase					:		List[str]  =				self.config.text_config
        _UpperCamelCase					:		Union[str, Any]  =				self.config.vision_config

        _UpperCamelCase					:		Optional[int]  =				self.config.projection_dim
        _UpperCamelCase					:		List[Any]  =				text_config.hidden_size
        _UpperCamelCase					:		Optional[Any]  =				vision_config.hidden_size

        _UpperCamelCase					:		str  =				FLAX_MODEL_MAPPING[self.config.text_config.__class__].module_class
        _UpperCamelCase					:		int  =				FLAX_MODEL_MAPPING.get(self.config.vision_config.__class__    ,      __a		).module_class

        _UpperCamelCase					:		str  =				text_module(__a    ,      dtype=self.dtype		)
        _UpperCamelCase					:		List[Any]  =				vision_module(__a    ,      dtype=self.dtype		)

        _UpperCamelCase					:		List[str]  =				nn.Dense(
            self.projection_dim    ,      dtype=self.dtype    ,      kernel_init=jax.nn.initializers.normal(0.02		)    ,      use_bias=__a    ,      )
        _UpperCamelCase					:		int  =				nn.Dense(
            self.projection_dim    ,      dtype=self.dtype    ,      kernel_init=jax.nn.initializers.normal(0.02		)    ,      use_bias=__a    ,      )
        _UpperCamelCase					:		int  =				self.param("logit_scale"    ,      jax.nn.initializers.ones    ,      []		)


  def __call__(						self      :				Any    ,      __a      :				List[str]=None    ,      __a      :				Optional[int]=None    ,      __a      :				Tuple=None    ,      __a      :				Tuple=None    ,      __a      :				str=None    ,      __a      :				bool = True    ,      __a      :				Dict=None    ,      __a      :				Any=None    ,      __a      :				Any=None    ,      )						-> List[str]:
        _UpperCamelCase					:		List[str]  =				return_dict if return_dict is not None else self.config.return_dict

        _UpperCamelCase					:		Any  =				self.vision_model(
            pixel_values=__a    ,      deterministic=__a    ,      output_attentions=__a    ,      output_hidden_states=__a    ,      return_dict=__a    ,      )

        _UpperCamelCase					:		Any  =				self.text_model(
            input_ids=__a    ,      attention_mask=__a    ,      token_type_ids=__a    ,      position_ids=__a    ,      deterministic=__a    ,      output_attentions=__a    ,      output_hidden_states=__a    ,      return_dict=__a    ,      )

        _UpperCamelCase					:		str  =				vision_outputs[1]
        _UpperCamelCase					:		Dict  =				self.visual_projection(__a		)

        _UpperCamelCase					:		Dict  =				text_outputs[1]
        _UpperCamelCase					:		Dict  =				self.text_projection(__a		)

        # normalized features
        _UpperCamelCase					:		Optional[int]  =				image_embeds / jnp.linalg.norm(__a    ,      axis=-1    ,      keepdims=__a		)
        _UpperCamelCase					:		Tuple  =				text_embeds / jnp.linalg.norm(__a    ,      axis=-1    ,      keepdims=__a		)

        # cosine similarity as logits
        _UpperCamelCase					:		Dict  =				jnp.exp(self.logit_scale		)
        _UpperCamelCase					:		Union[str, Any]  =				jnp.matmul(__a    ,      image_embeds.T		) * logit_scale
        _UpperCamelCase					:		List[Any]  =				logits_per_text.T

        if not return_dict:
              return (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)

        return FlaxCLIPOutput(
            logits_per_image=__a    ,      logits_per_text=__a    ,      text_embeds=__a    ,      image_embeds=__a    ,      text_model_output=__a    ,      vision_model_output=__a    ,      )





class    __SCREAMING_SNAKE_CASE			(  _UpperCamelCase      ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Tuple		   =    HybridCLIPConfig
  SCREAMING_SNAKE_CASE__							:List[Any]		   =    FlaxHybridCLIPModule

  def __init__(						self      :				Tuple    ,      __a      :				HybridCLIPConfig    ,      __a      :				Optional[Tuple] = None    ,      __a      :				int = 0    ,      __a      :				jnp.dtype = jnp.floataa    ,      **__a      :				Tuple    ,      )						-> List[str]:
        if input_shape is None:
              _UpperCamelCase					:		str  =				((1, 1), (1, config.vision_config.image_size, config.vision_config.image_size, 3))

        _UpperCamelCase					:		List[Any]  =				self.module_class(config=__a    ,      dtype=__a    ,      **__a		)
        super().__init__(__a    ,      __a    ,      input_shape=__a    ,      seed=__a    ,      dtype=__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[Any]    ,      __a      :				jax.random.PRNGKey    ,      __a      :				Tuple    ,      __a      :				FrozenDict = None		)						-> FrozenDict:
        # init input tensor
        _UpperCamelCase					:		List[str]  =				jnp.zeros(input_shape[0]    ,      dtype="i4"		)
        _UpperCamelCase					:		List[Any]  =				jnp.broadcast_to(jnp.arange(jnp.atleast_ad(__a		).shape[-1]		)    ,      input_shape[0]		)
        _UpperCamelCase					:		Union[str, Any]  =				jnp.ones_like(__a		)
        _UpperCamelCase					:		str  =				jnp.ones_like(__a		)

        _UpperCamelCase					:		Optional[int]  =				jax.random.normal(__a    ,      input_shape[1]		)

        _UpperCamelCase,     _UpperCamelCase					:		Optional[Any]  =				jax.random.split(__a		)
        _UpperCamelCase					:		Tuple  =				{"params": params_rng, "dropout": dropout_rng}

        return self.module.init(__a    ,      __a    ,      __a    ,      __a    ,      __a    ,      __a		)["params"]

  def __call__(						self      :				Dict    ,      __a      :				int    ,      __a      :				Any    ,      __a      :				Union[str, Any]=None    ,      __a      :				Optional[int]=None    ,      __a      :				Union[str, Any]=None    ,      __a      :				dict = None    ,      __a      :				jax.random.PRNGKey = None    ,      __a      :				bool = False    ,      __a      :				Optional[bool] = None    ,      __a      :				Optional[bool] = None    ,      __a      :				Optional[bool] = None    ,      )						-> Optional[Any]:
        _UpperCamelCase					:		List[Any]  =				output_attentions if output_attentions is not None else self.config.output_attentions
        _UpperCamelCase					:		Tuple  =				(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        _UpperCamelCase					:		List[str]  =				return_dict if return_dict is not None else self.config.return_dict

        if position_ids is None:
              _UpperCamelCase					:		Union[str, Any]  =				jnp.broadcast_to(jnp.arange(jnp.atleast_ad(__a		).shape[-1]		)    ,      input_ids.shape		)

        if token_type_ids is None:
              _UpperCamelCase					:		str  =				jnp.zeros_like(__a		)

        if attention_mask is None:
              _UpperCamelCase					:		Optional[int]  =				jnp.ones_like(__a		)

        # Handle any PRNG if needed
        _UpperCamelCase					:		Optional[int]  =				{}
        if dropout_rng is not None:
              _UpperCamelCase					:		List[Any]  =				dropout_rng

        return self.module.apply(
            {"params": params or self.params}    ,      jnp.array(__a    ,      dtype="i4"		)    ,      jnp.array(__a    ,      dtype=jnp.floataa		)    ,      jnp.array(__a    ,      dtype="i4"		)    ,      jnp.array(__a    ,      dtype="i4"		)    ,      jnp.array(__a    ,      dtype="i4"		)    ,      not train    ,      __a    ,      __a    ,      __a    ,      rngs=__a    ,      )

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict    ,      __a      :				Any    ,      __a      :				List[str]=None    ,      __a      :				Union[str, Any]=None    ,      __a      :				Any=None    ,      __a      :				dict = None    ,      __a      :				jax.random.PRNGKey = None    ,      __a      :				List[str]=False    ,      )						-> str:
        if position_ids is None:
              _UpperCamelCase					:		Union[str, Any]  =				jnp.broadcast_to(jnp.arange(jnp.atleast_ad(__a		).shape[-1]		)    ,      input_ids.shape		)

        if token_type_ids is None:
              _UpperCamelCase					:		Tuple  =				jnp.zeros_like(__a		)

        if attention_mask is None:
              _UpperCamelCase					:		List[str]  =				jnp.ones_like(__a		)

        # Handle any PRNG if needed
        _UpperCamelCase					:		List[str]  =				{}
        if dropout_rng is not None:
              _UpperCamelCase					:		Dict  =				dropout_rng

        def _get_features(__a      :				Optional[int]    ,      __a      :				Optional[Any]    ,      __a      :				List[Any]    ,      __a      :				Optional[int]    ,      __a      :				Union[str, Any]    ,      __a      :				List[Any]		):
              _UpperCamelCase					:		List[Any]  =				module.text_model(
                  input_ids=__a    ,      attention_mask=__a    ,      position_ids=__a    ,      token_type_ids=__a    ,      deterministic=__a    ,      )
              _UpperCamelCase					:		Tuple  =				text_outputs[1]
              _UpperCamelCase					:		Tuple  =				module.text_projection(__a		)
              return text_features

        return self.module.apply(
            {"params": params or self.params}    ,      jnp.array(__a    ,      dtype="i4"		)    ,      jnp.array(__a    ,      dtype="i4"		)    ,      jnp.array(__a    ,      dtype="i4"		)    ,      jnp.array(__a    ,      dtype="i4"		)    ,      not train    ,      method=_get_features    ,      rngs=__a    ,      )

  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[int]    ,      __a      :				int    ,      __a      :				dict = None    ,      __a      :				jax.random.PRNGKey = None    ,      __a      :				Optional[Any]=False		)						-> Tuple:
        _UpperCamelCase					:		List[str]  =				{}
        if dropout_rng is not None:
              _UpperCamelCase					:		Tuple  =				dropout_rng

        def _get_features(__a      :				int    ,      __a      :				List[str]    ,      __a      :				Optional[Any]		):
              _UpperCamelCase					:		Optional[int]  =				module.vision_model(pixel_values=__a    ,      deterministic=__a		)
              _UpperCamelCase					:		Optional[int]  =				vision_outputs[1]  # pooled_output
              _UpperCamelCase					:		str  =				module.visual_projection(__a		)
              return image_features

        return self.module.apply(
            {"params": params or self.params}    ,      jnp.array(__a    ,      dtype=jnp.floataa		)    ,      not train    ,      method=_get_features    ,      rngs=__a    ,      )


  @classmethod
  def       __SCREAMING_SNAKE_CASE (						cls      :				List[str]    ,      __a      :				str = None    ,      __a      :				str = None    ,      *__a      :				List[Any]    ,      **__a      :				Tuple    ,      )						-> FlaxPreTrainedModel:
        _UpperCamelCase					:		Union[str, Any]  =				{
            argument[len("text_"		) :]: value for argument, value in kwargs.items() if argument.startswith("text_"		)
        }

        _UpperCamelCase					:		Optional[Any]  =				{
            argument[len("vision_"		) :]: value for argument, value in kwargs.items() if argument.startswith("vision_"		)
        }

        # remove text, vision kwargs from kwargs
        for key in kwargs_text.keys():
              del kwargs["text_" + key]
        for key in kwargs_vision.keys():
              del kwargs["vision_" + key]

        # Load and initialize the text and vision model
        _UpperCamelCase					:		int  =				kwargs_text.pop("model"    ,      __a		)
        if text_model is None:
              assert (
                  text_model_name_or_path is not None
              ), "If `model` is not defined as an argument, a `text_model_name_or_path` has to be defined"
              from transformers import FlaxAutoModel

              if "config" not in kwargs_text:
                    from transformers import AutoConfig

                    _UpperCamelCase					:		Any  =				AutoConfig.from_pretrained(__a		)
                    _UpperCamelCase					:		int  =				text_config

              _UpperCamelCase					:		Optional[Any]  =				FlaxAutoModel.from_pretrained(__a    ,      *__a    ,      **__a		)

        _UpperCamelCase					:		str  =				kwargs_vision.pop("model"    ,      __a		)
        if vision_model is None:
              assert (
                  vision_model_name_or_path is not None
              ), "If `model` is not defined as an argument, a `vision_model_name_or_path` has to be defined"
              from transformers import FlaxAutoModel

              if "config" not in kwargs_vision:
                    from transformers import AutoConfig

                    _UpperCamelCase					:		Dict  =				AutoConfig.from_pretrained(__a		)
                    _UpperCamelCase					:		str  =				vision_config

              _UpperCamelCase					:		int  =				FlaxAutoModel.from_pretrained(__a    ,      *__a    ,      **__a		)

        # instantiate config with corresponding kwargs
        _UpperCamelCase					:		Optional[int]  =				kwargs.pop("dtype"    ,      jnp.floataa		)
        _UpperCamelCase					:		Optional[int]  =				HybridCLIPConfig.from_text_vision_configs(text_model.config    ,      vision_model.config    ,      **__a		)

        # init model
        _UpperCamelCase					:		List[str]  =				cls(__a    ,      *__a    ,      dtype=__a    ,      **__a		)

        if vision_config.model_type == "clip":
              _UpperCamelCase					:		Tuple  =				vision_model.params["vision_model"]
              _UpperCamelCase					:		Tuple  =				vision_model.params["visual_projection"]["kernel"]
        else:
              _UpperCamelCase					:		Tuple  =				vision_model.params

        _UpperCamelCase					:		str  =				text_model.params

        return model
