





"""simple docstring"""


import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest



class    __SCREAMING_SNAKE_CASE			(  _UpperCamelCase      ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Tuple		   =    (DPMSolverMultistepScheduler,)
  SCREAMING_SNAKE_CASE__							:Tuple		   =    (("num_inference_steps", 25),)

  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[int]    ,      **__a      :				Tuple		)						-> Tuple:
        _UpperCamelCase					:		List[str]  =				{
            "num_train_timesteps": 1000,
            "beta_start": 0.00_01,
            "beta_end": 0.02,
            "beta_schedule": "linear",
            "solver_order": 2,
            "prediction_type": "epsilon",
            "thresholding": False,
            "sample_max_value": 1.0,
            "algorithm_type": "dpmsolver++",
            "solver_type": "midpoint",
            "lower_order_final": False,
            "lambda_min_clipped": -float("inf"		),
            "variance_type": None,
        }

        config.update(**__a		)
        return config

  def       __SCREAMING_SNAKE_CASE (						self      :				Any    ,      __a      :				Dict=0    ,      **__a      :				Any		)						-> Optional[int]:
        _UpperCamelCase					:		Union[str, Any]  =				dict(self.forward_default_kwargs		)
        _UpperCamelCase					:		Any  =				kwargs.pop("num_inference_steps"    ,      __a		)
        _UpperCamelCase					:		Dict  =				self.dummy_sample
        _UpperCamelCase					:		List[Any]  =				0.1 * sample
        _UpperCamelCase					:		Dict  =				[residual + 0.2, residual + 0.15, residual + 0.10]

        for scheduler_class in self.scheduler_classes:
              _UpperCamelCase					:		Tuple  =				self.get_scheduler_config(**__a		)
              _UpperCamelCase					:		Dict  =				scheduler_class(**__a		)
              scheduler.set_timesteps(__a		)
              # copy over dummy past residuals
              _UpperCamelCase					:		str  =				dummy_past_residuals[: scheduler.config.solver_order]

              with tempfile.TemporaryDirectory() as tmpdirname:
                    scheduler.save_config(__a		)
                    _UpperCamelCase					:		Optional[int]  =				scheduler_class.from_pretrained(__a		)
                    new_scheduler.set_timesteps(__a		)
                    # copy over dummy past residuals
                    _UpperCamelCase					:		int  =				dummy_past_residuals[: new_scheduler.config.solver_order]

              _UpperCamelCase,     _UpperCamelCase					:		Optional[int]  =				sample, sample
              for t in range(__a    ,      time_step + scheduler.config.solver_order + 1		):
                    _UpperCamelCase					:		List[Any]  =				scheduler.step(__a    ,      __a    ,      __a    ,      **__a		).prev_sample
                    _UpperCamelCase					:		Optional[Any]  =				new_scheduler.step(__a    ,      __a    ,      __a    ,      **__a		).prev_sample

                    assert torch.sum(torch.abs(output - new_output		)		) < 1e-5, "Scheduler outputs are not identical"

  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[int]		)						-> str:
        pass

  def       __SCREAMING_SNAKE_CASE (						self      :				Any    ,      __a      :				Union[str, Any]=0    ,      **__a      :				Union[str, Any]		)						-> Any:
        _UpperCamelCase					:		str  =				dict(self.forward_default_kwargs		)
        _UpperCamelCase					:		List[str]  =				kwargs.pop("num_inference_steps"    ,      __a		)
        _UpperCamelCase					:		Optional[int]  =				self.dummy_sample
        _UpperCamelCase					:		int  =				0.1 * sample
        _UpperCamelCase					:		str  =				[residual + 0.2, residual + 0.15, residual + 0.10]

        for scheduler_class in self.scheduler_classes:
              _UpperCamelCase					:		Optional[Any]  =				self.get_scheduler_config()
              _UpperCamelCase					:		List[str]  =				scheduler_class(**__a		)
              scheduler.set_timesteps(__a		)

              # copy over dummy past residuals (must be after setting timesteps)
              _UpperCamelCase					:		Dict  =				dummy_past_residuals[: scheduler.config.solver_order]

              with tempfile.TemporaryDirectory() as tmpdirname:
                    scheduler.save_config(__a		)
                    _UpperCamelCase					:		List[str]  =				scheduler_class.from_pretrained(__a		)
                    # copy over dummy past residuals
                    new_scheduler.set_timesteps(__a		)

                    # copy over dummy past residual (must be after setting timesteps)
                    _UpperCamelCase					:		Optional[int]  =				dummy_past_residuals[: new_scheduler.config.solver_order]

              _UpperCamelCase					:		Optional[int]  =				scheduler.step(__a    ,      __a    ,      __a    ,      **__a		).prev_sample
              _UpperCamelCase					:		Dict  =				new_scheduler.step(__a    ,      __a    ,      __a    ,      **__a		).prev_sample

              assert torch.sum(torch.abs(output - new_output		)		) < 1e-5, "Scheduler outputs are not identical"

  def       __SCREAMING_SNAKE_CASE (						self      :				str    ,      __a      :				Optional[Any]=None    ,      **__a      :				int		)						-> List[Any]:
        if scheduler is None:
              _UpperCamelCase					:		List[str]  =				self.scheduler_classes[0]
              _UpperCamelCase					:		str  =				self.get_scheduler_config(**__a		)
              _UpperCamelCase					:		Union[str, Any]  =				scheduler_class(**__a		)

        _UpperCamelCase					:		Union[str, Any]  =				10
        _UpperCamelCase					:		int  =				self.dummy_model()
        _UpperCamelCase					:		Union[str, Any]  =				self.dummy_sample_deter
        scheduler.set_timesteps(__a		)

        for i, t in enumerate(scheduler.timesteps		):
              _UpperCamelCase					:		Dict  =				model(__a    ,      __a		)
              _UpperCamelCase					:		Any  =				scheduler.step(__a    ,      __a    ,      __a		).prev_sample

        return sample

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Union[str, Any]:
        _UpperCamelCase					:		str  =				dict(self.forward_default_kwargs		)

        _UpperCamelCase					:		Dict  =				kwargs.pop("num_inference_steps"    ,      __a		)

        for scheduler_class in self.scheduler_classes:
              _UpperCamelCase					:		Optional[Any]  =				self.get_scheduler_config()
              _UpperCamelCase					:		List[str]  =				scheduler_class(**__a		)

              _UpperCamelCase					:		Any  =				self.dummy_sample
              _UpperCamelCase					:		int  =				0.1 * sample

              if num_inference_steps is not None and hasattr(__a    ,      "set_timesteps"		):
                    scheduler.set_timesteps(__a		)
              elif num_inference_steps is not None and not hasattr(__a    ,      "set_timesteps"		):
                    _UpperCamelCase					:		Dict  =				num_inference_steps

              # copy over dummy past residuals (must be done after set_timesteps)
              _UpperCamelCase					:		List[str]  =				[residual + 0.2, residual + 0.15, residual + 0.10]
              _UpperCamelCase					:		List[Any]  =				dummy_past_residuals[: scheduler.config.solver_order]

              _UpperCamelCase					:		Optional[int]  =				scheduler.timesteps[5]
              _UpperCamelCase					:		Dict  =				scheduler.timesteps[6]

              _UpperCamelCase					:		Optional[int]  =				scheduler.step(__a    ,      __a    ,      __a    ,      **__a		).prev_sample
              _UpperCamelCase					:		Optional[int]  =				scheduler.step(__a    ,      __a    ,      __a    ,      **__a		).prev_sample

              self.assertEqual(output_a.shape    ,      sample.shape		)
              self.assertEqual(output_a.shape    ,      output_a.shape		)

  def       __SCREAMING_SNAKE_CASE (						self      :				str		)						-> List[Any]:
        for timesteps in [25, 50, 100, 999, 1000]:
              self.check_over_configs(num_train_timesteps=__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[int]		)						-> Tuple:
        self.check_over_configs(thresholding=__a		)
        for order in [1, 2, 3]:
              for solver_type in ["midpoint", "heun"]:
                    for threshold in [0.5, 1.0, 2.0]:
                          for prediction_type in ["epsilon", "sample"]:
                                self.check_over_configs(
                                    thresholding=__a    ,      prediction_type=__a    ,      sample_max_value=__a    ,      algorithm_type="dpmsolver++"    ,      solver_order=__a    ,      solver_type=__a    ,      )

  def       __SCREAMING_SNAKE_CASE (						self      :				List[str]		)						-> str:
        for prediction_type in ["epsilon", "v_prediction"]:
              self.check_over_configs(prediction_type=__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Dict:
        for algorithm_type in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
              for solver_type in ["midpoint", "heun"]:
                    for order in [1, 2, 3]:
                          for prediction_type in ["epsilon", "sample"]:
                                if algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
                                      if order == 3:
                                            continue
                                else:
                                      self.check_over_configs(
                                          solver_order=__a    ,      solver_type=__a    ,      prediction_type=__a    ,      algorithm_type=__a    ,      )
                                _UpperCamelCase					:		Dict  =				self.full_loop(
                                    solver_order=__a    ,      solver_type=__a    ,      prediction_type=__a    ,      algorithm_type=__a    ,      )
                                assert not torch.isnan(__a		).any(), "Samples have nan numbers"

  def       __SCREAMING_SNAKE_CASE (						self      :				Tuple		)						-> List[Any]:
        self.check_over_configs(lower_order_final=__a		)
        self.check_over_configs(lower_order_final=__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				List[Any]		)						-> int:
        self.check_over_configs(lambda_min_clipped=-float("inf"		)		)
        self.check_over_configs(lambda_min_clipped=-5.1		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Dict:
        self.check_over_configs(variance_type=__a		)
        self.check_over_configs(variance_type="learned_range"		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Optional[Any]:
        for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]:
              self.check_over_forward(num_inference_steps=__a    ,      time_step=0		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Dict:
        _UpperCamelCase					:		Union[str, Any]  =				self.full_loop()
        _UpperCamelCase					:		Optional[int]  =				torch.mean(torch.abs(__a		)		)

        assert abs(result_mean.item() - 0.33_01		) < 1e-3

  def       __SCREAMING_SNAKE_CASE (						self      :				List[Any]		)						-> str:
        _UpperCamelCase					:		Union[str, Any]  =				self.full_loop(thresholding=__a    ,      dynamic_thresholding_ratio=0.87    ,      sample_max_value=0.5		)
        _UpperCamelCase					:		Optional[Any]  =				torch.mean(torch.abs(__a		)		)

        assert abs(result_mean.item() - 1.13_64		) < 1e-3

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Tuple:
        _UpperCamelCase					:		Union[str, Any]  =				self.full_loop(prediction_type="v_prediction"		)
        _UpperCamelCase					:		Dict  =				torch.mean(torch.abs(__a		)		)

        assert abs(result_mean.item() - 0.22_51		) < 1e-3

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Optional[int]:
        _UpperCamelCase					:		str  =				self.full_loop(prediction_type="v_prediction"    ,      use_karras_sigmas=__a		)
        _UpperCamelCase					:		str  =				torch.mean(torch.abs(__a		)		)

        assert abs(result_mean.item() - 0.20_96		) < 1e-3

  def       __SCREAMING_SNAKE_CASE (						self      :				int		)						-> Any:
        # make sure that iterating over schedulers with same config names gives same results
        # for defaults
        _UpperCamelCase					:		str  =				DPMSolverMultistepScheduler(**self.get_scheduler_config()		)
        _UpperCamelCase					:		Tuple  =				self.full_loop(scheduler=__a		)
        _UpperCamelCase					:		List[str]  =				torch.mean(torch.abs(__a		)		)

        assert abs(result_mean.item() - 0.33_01		) < 1e-3

        _UpperCamelCase					:		Optional[int]  =				DPMSolverSinglestepScheduler.from_config(scheduler.config		)
        _UpperCamelCase					:		int  =				UniPCMultistepScheduler.from_config(scheduler.config		)
        _UpperCamelCase					:		List[str]  =				DEISMultistepScheduler.from_config(scheduler.config		)
        _UpperCamelCase					:		Union[str, Any]  =				DPMSolverMultistepScheduler.from_config(scheduler.config		)

        _UpperCamelCase					:		Tuple  =				self.full_loop(scheduler=__a		)
        _UpperCamelCase					:		Any  =				torch.mean(torch.abs(__a		)		)

        assert abs(result_mean.item() - 0.33_01		) < 1e-3

  def       __SCREAMING_SNAKE_CASE (						self      :				str		)						-> List[str]:
        _UpperCamelCase					:		Any  =				self.scheduler_classes[0]
        _UpperCamelCase					:		List[str]  =				self.get_scheduler_config(thresholding=__a    ,      dynamic_thresholding_ratio=0		)
        _UpperCamelCase					:		List[Any]  =				scheduler_class(**__a		)

        _UpperCamelCase					:		Optional[Any]  =				10
        _UpperCamelCase					:		Union[str, Any]  =				self.dummy_model()
        _UpperCamelCase					:		str  =				self.dummy_sample_deter.half()
        scheduler.set_timesteps(__a		)

        for i, t in enumerate(scheduler.timesteps		):
              _UpperCamelCase					:		Optional[Any]  =				model(__a    ,      __a		)
              _UpperCamelCase					:		List[str]  =				scheduler.step(__a    ,      __a    ,      __a		).prev_sample

        assert sample.dtype == torch.floataa


  def       __SCREAMING_SNAKE_CASE (						self      :				int    ,      **__a      :				List[Any]		)						-> Optional[Any]:
        for scheduler_class in self.scheduler_classes:
              _UpperCamelCase					:		Optional[int]  =				self.get_scheduler_config(**__a		)
              _UpperCamelCase					:		Optional[Any]  =				scheduler_class(**__a		)

              scheduler.set_timesteps(scheduler.config.num_train_timesteps		)
              assert len(scheduler.timesteps.unique()		) == scheduler.num_inference_steps







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