"""simple docstring"""



from typing import Optional, Tuple

import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule





def    SCREAMING_SNAKE_CASE       (     snake_case,      snake_case,      snake_case=1E-12):
     __snake_case				=							jnp.divide(emb_a.T,      jnp.clip(jnp.linalg.norm(snake_case,      axis=1),      a_min=snake_case)).T
     __snake_case				=							jnp.divide(emb_a.T,      jnp.clip(jnp.linalg.norm(snake_case,      axis=1),      a_min=snake_case)).T
     return jnp.matmul(snake_case,      norm_emb_a.T)



class      _A	(						nn.Module					):




    """simple docstring"""




    UpperCamelCase_	:					CLIPConfig
    UpperCamelCase_	:					jnp.dtype							=					jnp.floataa
    def  lowercase					(		self							:     Dict    )    ->       Optional[int]:
         __snake_case				=							FlaxCLIPVisionModule(self.config.vision_config    )
         __snake_case				=							nn.Dense(self.config.projection_dim	,      use_bias=A_	,      dtype=self.dtype    )

         __snake_case				=							self.param('''concept_embeds'''	,      jax.nn.initializers.ones	,      (17, self.config.projection_dim)    )
         __snake_case				=							self.param(
             '''special_care_embeds'''	,      jax.nn.initializers.ones	,      (3, self.config.projection_dim)    )

         __snake_case				=							self.param('''concept_embeds_weights'''	,      jax.nn.initializers.ones	,      (17,)    )
         __snake_case				=							self.param('''special_care_embeds_weights'''	,      jax.nn.initializers.ones	,      (3,)    )







    def __call__(		self							:     List[Any]	,      A_							:     List[str]    )    ->       List[Any]:
         __snake_case				=							self.vision_model(A_    )[1]
         __snake_case				=							self.visual_projection(A_    )

         __snake_case				=							jax_cosine_distance(A_	,      self.special_care_embeds    )
         __snake_case				=							jax_cosine_distance(A_	,      self.concept_embeds    )

         # increase this value to create a stronger `nfsw` filter
         # at the cost of increasing the possibility of filtering benign image inputs
         __snake_case				=							0.0

         __snake_case				=							special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
         __snake_case				=							jnp.round(A_	,      3    )
         __snake_case				=							jnp.any(special_scores > 0	,      axis=1	,      keepdims=A_    )
         # Use a lower threshold if an image has any special care concept
         __snake_case				=							is_special_care * 0.01

         __snake_case				=							cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
         __snake_case				=							jnp.round(A_	,      3    )
         __snake_case				=							jnp.any(concept_scores > 0	,      axis=1    )

         return has_nsfw_concepts






class      _A	(						_UpperCAmelCase					):




    """simple docstring"""




    UpperCamelCase_	:					List[Any]							=					CLIPConfig
    UpperCamelCase_	:					Union[str, Any]							=					'''clip_input'''
    UpperCamelCase_	:					Tuple							=					FlaxStableDiffusionSafetyCheckerModule
    def __init__(		self							:     str	,      A_							:     CLIPConfig	,      A_							:     Optional[Tuple] = None	,      A_							:     int = 0	,      A_							:     jnp.dtype = jnp.floataa	,      A_							:     bool = True	,      **A_							:     Optional[Any]	,      )    ->       Union[str, Any]:
         if input_shape is None:
              __snake_case				=							(1, 224, 224, 3)
         __snake_case				=							self.module_class(config=A_	,      dtype=A_	,      **A_    )
         super().__init__(A_	,      A_	,      input_shape=A_	,      seed=A_	,      dtype=A_	,      _do_init=_do_init    )
    def  lowercase					(		self							:     List[str]	,      A_							:     jax.random.KeyArray	,      A_							:     Tuple	,      A_							:     FrozenDict = None    )    ->       FrozenDict:
         # init input tensor
         __snake_case				=							jax.random.normal(A_	,      A_    )

         __snake_case		,	__snake_case				=							jax.random.split(A_    )
         __snake_case				=							{'''params''': params_rng, '''dropout''': dropout_rng}

         __snake_case				=							self.module.init(A_	,      A_    )['''params''']

         return random_params







    def __call__(		self							:     Optional[Any]	,      A_							:     Dict	,      A_							:     dict = None	,      )    ->       Optional[Any]:
         __snake_case				=							jnp.transpose(A_	,      (0, 2, 3, 1)    )

         return self.module.apply(
             {'''params''': params or self.params}	,      jnp.array(A_	,      dtype=jnp.floataa    )	,      rngs={}	,      )
"""simple docstring"""



import argparse
from pathlib import Path

import torch
from packaging import version
from torch.onnx import export

from diffusers import AutoencoderKL


__lowercase		:		int														=							version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11")





def    SCREAMING_SNAKE_CASE       (     snake_case,      snake_case,      snake_case,      snake_case,      snake_case,      snake_case,      snake_case,      snake_case=False,      ):
     output_path.parent.mkdir(parents=snake_case,      exist_ok=snake_case)
     # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11,
     # so we check the torch version for backwards compatibility
     if is_torch_less_than_1_11:
          export(
              snake_case,      snake_case,      f=output_path.as_posix(),      input_names=snake_case,      output_names=snake_case,      dynamic_axes=snake_case,      do_constant_folding=snake_case,      use_external_data_format=snake_case,      enable_onnx_checker=snake_case,      opset_version=snake_case,      )
     else:
          export(
              snake_case,      snake_case,      f=output_path.as_posix(),      input_names=snake_case,      output_names=snake_case,      dynamic_axes=snake_case,      do_constant_folding=snake_case,      opset_version=snake_case,      )





@torch.no_grad()
def    SCREAMING_SNAKE_CASE       (     snake_case,      snake_case,      snake_case,      snake_case = False):
     __snake_case				=							torch.floataa if fpaa else torch.floataa
     if fpaa and torch.cuda.is_available():
          __snake_case				=							'''cuda'''
     elif fpaa and not torch.cuda.is_available():
          raise ValueError('''`float16` model export is only supported on GPUs with CUDA''')
     else:
          __snake_case				=							'''cpu'''
     __snake_case				=							Path(snake_case)

     # VAE DECODER
     __snake_case				=							AutoencoderKL.from_pretrained(model_path + '''/vae''')
     __snake_case				=							vae_decoder.config.latent_channels
     # forward only through the decoder part
     __snake_case				=							vae_decoder.decode
     onnx_export(
         snake_case,      model_args=(
             torch.randn(1,      snake_case,      25,      25).to(device=snake_case,      dtype=snake_case),
             False,
         ),      output_path=output_path / '''vae_decoder''' / '''model.onnx''',      ordered_input_names=['''latent_sample''', '''return_dict'''],      output_names=['''sample'''],      dynamic_axes={
             '''latent_sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''},
         },      opset=snake_case,      )
     del vae_decoder


if __name__ == "__main__":
       __lowercase		:		Union[str, Any]														=							argparse.ArgumentParser()

       parser.add_argument(
           "--model_path",
           type=str,
           required=True,
           help="Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).",
       )

       parser.add_argument("--output_path", type=str, required=True, help="Path to the output model.")
       parser.add_argument(
           "--opset",
           default=14,
           type=int,
           help="The version of the ONNX operator set to use.",
       )
       parser.add_argument("--fp16", action="store_true", default=False, help="Export the models in `float16` mode")

       __lowercase		:		List[Any]														=							parser.parse_args()
       print(args.output_path)
       convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
       print("SD: Done: ONNX")