

from logging import getLogger
from typing import Any, Callable, List, Optional, Union

import numpy as np
import PIL
import torch

from ...schedulers import DDPMScheduler
from ..onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
from ..pipeline_utils import ImagePipelineOutput
from . import StableDiffusionUpscalePipeline


SCREAMING_SNAKE_CASE						:Optional[Any]      =			getLogger(__name__)


SCREAMING_SNAKE_CASE						:List[str]      =			4
SCREAMING_SNAKE_CASE						:List[str]      =			7

SCREAMING_SNAKE_CASE						:Union[str, Any]      =			{
    """float16""": torch.floataa,
    """float32""": torch.floataa,
}




def        lowerCAmelCase(	SCREAMING_SNAKE_CASE_       )->		Tuple:



    """simple docstring"""






    if isinstance(SCREAMING_SNAKE_CASE_       ,		torch.Tensor       ):
        return image
    elif isinstance(SCREAMING_SNAKE_CASE_       ,		PIL.Image.Image       ):
        UpperCamelCase_          =		[image]

    if isinstance(image[0]       ,		PIL.Image.Image       ):
        UpperCamelCase_   ,    UpperCamelCase_          =		image[0].size
        UpperCamelCase_   ,    UpperCamelCase_          =		(x - x % 6_4 for x in (w, h))  # resize to integer multiple of 32

        UpperCamelCase_          =		[np.array(i.resize((w, h)       )       )[None, :] for i in image]
        UpperCamelCase_          =		np.concatenate(SCREAMING_SNAKE_CASE_       ,		axis=0       )
        UpperCamelCase_          =		np.array(SCREAMING_SNAKE_CASE_       ).astype(np.floataa       ) / 255.0
        UpperCamelCase_          =		image.transpose(0       ,		3       ,		1       ,		2       )
        UpperCamelCase_          =		2.0 * image - 1.0
        UpperCamelCase_          =		torch.from_numpy(SCREAMING_SNAKE_CASE_       )
    elif isinstance(image[0]       ,		torch.Tensor       ):
        UpperCamelCase_          =		torch.cat(SCREAMING_SNAKE_CASE_       ,		dim=0       )

    return image






class 		__magic_name__ (				snake_case							):






     def __init__(							self						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase = 350						,		)->			List[Any]:
         super().__init__(
             vae=_lowercase						,		text_encoder=_lowercase						,		tokenizer=_lowercase						,		unet=_lowercase						,		low_res_scheduler=_lowercase						,		scheduler=_lowercase						,		safety_checker=_lowercase						,		feature_extractor=_lowercase						,		watermarker=_lowercase						,		max_noise_level=_lowercase						,		)






     def __call__(							self						,		_lowercase						,		_lowercase						,		_lowercase = 75						,		_lowercase = 9.0						,		_lowercase = 20						,		_lowercase = None						,		_lowercase = 1						,		_lowercase = 0.0						,		_lowercase = None						,		_lowercase = None						,		_lowercase = None						,		_lowercase = None						,		_lowercase = "pil"						,		_lowercase = True						,		_lowercase = None						,		_lowercase = 1						,		)->			Union[str, Any]:
         self.check_inputs(_lowercase						,		_lowercase						,		_lowercase						,		_lowercase     )

         # 2. Define call parameters
         if prompt is not None and isinstance(_lowercase						,		_lowercase     ):
             UpperCamelCase_          =		1
         elif prompt is not None and isinstance(_lowercase						,		_lowercase     ):
             UpperCamelCase_          =		len(_lowercase     )
         else:
             UpperCamelCase_          =		prompt_embeds.shape[0]

         UpperCamelCase_          =		self._execution_device
         # 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.
         UpperCamelCase_          =		guidance_scale > 1.0

         # 3. Encode input prompt
         UpperCamelCase_          =		self._encode_prompt(
             _lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		prompt_embeds=_lowercase						,		negative_prompt_embeds=_lowercase						,		)

         UpperCamelCase_          =		ORT_TO_PT_TYPE[str(text_embeddings.dtype     )]

         # 4. Preprocess image
         UpperCamelCase_          =		preprocess(_lowercase     )
         UpperCamelCase_          =		image.cpu()

         # 5. set timesteps
         self.scheduler.set_timesteps(_lowercase						,		device=_lowercase     )
         UpperCamelCase_          =		self.scheduler.timesteps

         # 5. Add noise to image
         UpperCamelCase_          =		torch.tensor([noise_level]						,		dtype=torch.long						,		device=_lowercase     )
         UpperCamelCase_          =		torch.randn(image.shape						,		generator=_lowercase						,		device=_lowercase						,		dtype=_lowercase     )
         UpperCamelCase_          =		self.low_res_scheduler.add_noise(_lowercase						,		_lowercase						,		_lowercase     )

         UpperCamelCase_          =		2 if do_classifier_free_guidance else 1
         UpperCamelCase_          =		np.concatenate([image] * batch_multiplier * num_images_per_prompt     )
         UpperCamelCase_          =		np.concatenate([noise_level] * image.shape[0]     )

         # 6. Prepare latent variables
         UpperCamelCase_   ,    UpperCamelCase_          =		image.shape[2:]
         UpperCamelCase_          =		self.prepare_latents(
             batch_size * num_images_per_prompt						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		)

         # 7. Check that sizes of image and latents match
         UpperCamelCase_          =		image.shape[1]
         if NUM_LATENT_CHANNELS + num_channels_image != NUM_UNET_INPUT_CHANNELS:
             raise ValueError(
                 "Incorrect configuration settings! The config of `pipeline.unet` expects"
                 F" {NUM_UNET_INPUT_CHANNELS} but received `num_channels_latents`: {NUM_LATENT_CHANNELS} +"
                 F" `num_channels_image`: {num_channels_image} "
                 F" = {NUM_LATENT_CHANNELS+num_channels_image}. Please verify the config of"
                 " `pipeline.unet` or your `image` input."     )

         # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
         UpperCamelCase_          =		self.prepare_extra_step_kwargs(_lowercase						,		_lowercase     )

         UpperCamelCase_          =		next(
             (input.type for input in self.unet.model.get_inputs() if input.name == "timestep")						,		"tensor(float)"     )
         UpperCamelCase_          =		ORT_TO_NP_TYPE[timestep_dtype]

         # 9. Denoising loop
         UpperCamelCase_          =		len(_lowercase     ) - num_inference_steps * self.scheduler.order
         with self.progress_bar(total=_lowercase     ) as progress_bar:
             for i, t in enumerate(_lowercase     ):
                 # expand the latents if we are doing classifier free guidance
                 UpperCamelCase_          =		np.concatenate([latents] * 2     ) if do_classifier_free_guidance else latents

                 # concat latents, mask, masked_image_latents in the channel dimension
                 UpperCamelCase_          =		self.scheduler.scale_model_input(_lowercase						,		_lowercase     )
                 UpperCamelCase_          =		np.concatenate([latent_model_input, image]						,		axis=1     )

                 # timestep to tensor
                 UpperCamelCase_          =		np.array([t]						,		dtype=_lowercase     )

                 # predict the noise residual
                 UpperCamelCase_          =		self.unet(
                     sample=_lowercase						,		timestep=_lowercase						,		encoder_hidden_states=_lowercase						,		class_labels=noise_level.astype(np.intaa     )						,		)[0]

                 # perform guidance
                 if do_classifier_free_guidance:
                     UpperCamelCase_   ,    UpperCamelCase_          =		np.split(_lowercase						,		2     )
                 UpperCamelCase_          =		noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

                 # compute the previous noisy sample x_t -> x_t-1
                 UpperCamelCase_          =		self.scheduler.step(
                     torch.from_numpy(_lowercase     )						,		_lowercase						,		_lowercase						,		**_lowercase     ).prev_sample

                 # call the callback, if provided
                 if i == len(_lowercase     ) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                     progress_bar.update()
                     if callback is not None and i % callback_steps == 0:
                         callback(_lowercase						,		_lowercase						,		_lowercase     )

        # 10. Post-processing
         UpperCamelCase_          =		self.decode_latents(latents.float()     )

         # 11. Convert to PIL
         if output_type == "pil":
             UpperCamelCase_          =		self.numpy_to_pil(_lowercase     )

         if not return_dict:
             return (image,)

         return ImagePipelineOutput(images=_lowercase     )






     def      UpperCAmelCase_							(							self						,		_lowercase     )->			Optional[int]:
         UpperCamelCase_          =		1 / 0.08_333 * latents
         UpperCamelCase_          =		self.vae(latent_sample=_lowercase     )[0]
         UpperCamelCase_          =		np.clip(image / 2 + 0.5						,		0						,		1     )
         UpperCamelCase_          =		image.transpose((0, 2, 3, 1)     )
         return image






     def      UpperCAmelCase_							(							self						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase						,		_lowercase = None						,		_lowercase = None						,		)->			Tuple:
         if prompt is not None and isinstance(_lowercase						,		_lowercase     ):
             UpperCamelCase_          =		1
         elif prompt is not None and isinstance(_lowercase						,		_lowercase     ):
             UpperCamelCase_          =		len(_lowercase     )
         else:
             UpperCamelCase_          =		prompt_embeds.shape[0]

         if prompt_embeds is None:
             UpperCamelCase_          =		self.tokenizer(
                 _lowercase						,		padding="max_length"						,		max_length=self.tokenizer.model_max_length						,		truncation=_lowercase						,		return_tensors="pt"						,		)
             UpperCamelCase_          =		text_inputs.input_ids
             UpperCamelCase_          =		self.tokenizer(_lowercase						,		padding="longest"						,		return_tensors="pt"     ).input_ids

             if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
                 _lowercase						,		_lowercase     ):
                 UpperCamelCase_          =		self.tokenizer.batch_decode(
                     untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]     )
                 logger.warning(
                     "The following part of your input was truncated because CLIP can only handle sequences up to"
                     F" {self.tokenizer.model_max_length} tokens: {removed_text}"     )

             # no positional arguments to text_encoder
             UpperCamelCase_          =		self.text_encoder(
                 input_ids=text_input_ids.int().to(_lowercase     )						,		)
             UpperCamelCase_          =		prompt_embeds[0]

         UpperCamelCase_   ,    UpperCamelCase_   ,    UpperCamelCase_          =		prompt_embeds.shape
         # duplicate text embeddings for each generation per prompt, using mps friendly method
         UpperCamelCase_          =		prompt_embeds.repeat(1						,		_lowercase     )
         UpperCamelCase_          =		prompt_embeds.reshape(bs_embed * num_images_per_prompt						,		_lowercase						,		-1     )

         # get unconditional embeddings for classifier free guidance
         if do_classifier_free_guidance and negative_prompt_embeds is None:
             UpperCamelCase_          =		42
             if negative_prompt is None:
                 UpperCamelCase_          =		[""] * batch_size
             elif type(_lowercase     ) is not type(_lowercase     ):
                 raise TypeError(
                     F"`negative_prompt` should be the same type to `prompt`, but got {type(_lowercase     )} !="
                     F" {type(_lowercase     )}."     )
             elif isinstance(_lowercase						,		_lowercase     ):
                 UpperCamelCase_          =		[negative_prompt]
             elif batch_size != len(_lowercase     ):
                 raise ValueError(
                     F"`negative_prompt`: {negative_prompt} has batch size {len(_lowercase     )}, but `prompt`:"
                     F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                     " the batch size of `prompt`."     )
             else:
                 UpperCamelCase_          =		negative_prompt

             UpperCamelCase_          =		text_input_ids.shape[-1]
             UpperCamelCase_          =		self.tokenizer(
                 _lowercase						,		padding="max_length"						,		max_length=_lowercase						,		truncation=_lowercase						,		return_tensors="pt"						,		)

             # if hasattr(uncond_input, "attention_mask"):
             #     attention_mask = uncond_input.attention_mask.to(device)
             # else:
             #     attention_mask = None

             UpperCamelCase_          =		self.text_encoder(
                 input_ids=uncond_input.input_ids.int().to(_lowercase     )						,		)
             UpperCamelCase_          =		uncond_embeddings[0]

         if do_classifier_free_guidance:
             UpperCamelCase_          =		uncond_embeddings.shape[1]
             # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
             UpperCamelCase_          =		uncond_embeddings.repeat(1						,		_lowercase     )
             UpperCamelCase_          =		uncond_embeddings.reshape(batch_size * num_images_per_prompt						,		_lowercase						,		-1     )

             # 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
             UpperCamelCase_          =		np.concatenate([uncond_embeddings, prompt_embeds]     )

         return prompt_embeds







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