





"""simple docstring"""


from __future__ import annotations

import unittest

from transformers import AlbertConfig, is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TF_MODEL_FOR_PRETRAINING_MAPPING
  from transformers.models.albert.modeling_tf_albert import (
      TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFAlbertForMaskedLM,
      TFAlbertForMultipleChoice,
      TFAlbertForPreTraining,
      TFAlbertForQuestionAnswering,
      TFAlbertForSequenceClassification,
      TFAlbertForTokenClassification,
      TFAlbertModel,
  )



class    __SCREAMING_SNAKE_CASE			:







  '''simple docstring'''


  def __init__(						self      :				List[str]    ,      __a      :				Union[str, Any]    ,      __a      :				int=13    ,      __a      :				int=7    ,      __a      :				Any=True    ,      __a      :				List[Any]=True    ,      __a      :				Dict=True    ,      __a      :				Union[str, Any]=True    ,      __a      :				Any=99    ,      __a      :				Union[str, Any]=16    ,      __a      :				Any=32    ,      __a      :				Tuple=2    ,      __a      :				int=4    ,      __a      :				str=37    ,      __a      :				str="gelu"    ,      __a      :				Optional[Any]=0.1    ,      __a      :				List[Any]=0.1    ,      __a      :				Any=512    ,      __a      :				Optional[Any]=16    ,      __a      :				Optional[Any]=2    ,      __a      :				Optional[Any]=0.02    ,      __a      :				str=3    ,      __a      :				Tuple=4    ,      __a      :				Tuple=None    ,      )						-> Tuple:
        _UpperCamelCase					:		str  =				parent
        _UpperCamelCase					:		Optional[Any]  =				13
        _UpperCamelCase					:		Any  =				7
        _UpperCamelCase					:		Optional[Any]  =				True
        _UpperCamelCase					:		Optional[int]  =				True
        _UpperCamelCase					:		Optional[int]  =				True
        _UpperCamelCase					:		Optional[Any]  =				True
        _UpperCamelCase					:		Optional[int]  =				99
        _UpperCamelCase					:		Any  =				16
        _UpperCamelCase					:		Optional[Any]  =				32
        _UpperCamelCase					:		int  =				2
        _UpperCamelCase					:		List[Any]  =				4
        _UpperCamelCase					:		Dict  =				37
        _UpperCamelCase					:		Tuple  =				"gelu"
        _UpperCamelCase					:		List[str]  =				0.1
        _UpperCamelCase					:		int  =				0.1
        _UpperCamelCase					:		List[str]  =				512
        _UpperCamelCase					:		Union[str, Any]  =				16
        _UpperCamelCase					:		Any  =				2
        _UpperCamelCase					:		int  =				0.02
        _UpperCamelCase					:		Any  =				3
        _UpperCamelCase					:		Any  =				4
        _UpperCamelCase					:		int  =				None

  def       __SCREAMING_SNAKE_CASE (						self      :				List[str]		)						-> str:
        _UpperCamelCase					:		int  =				ids_tensor([self.batch_size, self.seq_length]    ,      self.vocab_size		)

        _UpperCamelCase					:		Tuple  =				None
        if self.use_input_mask:
              _UpperCamelCase					:		Union[str, Any]  =				random_attention_mask([self.batch_size, self.seq_length]		)

        _UpperCamelCase					:		Optional[Any]  =				None
        if self.use_token_type_ids:
              _UpperCamelCase					:		List[str]  =				ids_tensor([self.batch_size, self.seq_length]    ,      self.type_vocab_size		)

        _UpperCamelCase					:		Optional[int]  =				None
        _UpperCamelCase					:		Optional[Any]  =				None
        _UpperCamelCase					:		Optional[int]  =				None
        if self.use_labels:
              _UpperCamelCase					:		List[str]  =				ids_tensor([self.batch_size]    ,      self.type_sequence_label_size		)
              _UpperCamelCase					:		List[Any]  =				ids_tensor([self.batch_size, self.seq_length]    ,      self.num_labels		)
              _UpperCamelCase					:		Any  =				ids_tensor([self.batch_size]    ,      self.num_choices		)

        _UpperCamelCase					:		List[Any]  =				AlbertConfig(
            vocab_size=self.vocab_size    ,      hidden_size=self.hidden_size    ,      embedding_size=self.embedding_size    ,      num_hidden_layers=self.num_hidden_layers    ,      num_attention_heads=self.num_attention_heads    ,      intermediate_size=self.intermediate_size    ,      hidden_act=self.hidden_act    ,      hidden_dropout_prob=self.hidden_dropout_prob    ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,      max_position_embeddings=self.max_position_embeddings    ,      type_vocab_size=self.type_vocab_size    ,      initializer_range=self.initializer_range    ,      )

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

  def       __SCREAMING_SNAKE_CASE (						self      :				Tuple    ,      __a      :				str    ,      __a      :				Any    ,      __a      :				int    ,      __a      :				int    ,      __a      :				List[str]    ,      __a      :				Tuple    ,      __a      :				Union[str, Any]		)						-> int:
        _UpperCamelCase					:		List[Any]  =				TFAlbertModel(config=__a		)
        # inputs = {'input_ids': input_ids,
        #           'attention_mask': input_mask,
        #           'token_type_ids': token_type_ids}
        # sequence_output, pooled_output = model(**inputs)
        _UpperCamelCase					:		List[Any]  =				{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
        _UpperCamelCase					:		List[str]  =				model(__a		)

        _UpperCamelCase					:		str  =				[input_ids, input_mask]
        _UpperCamelCase					:		Optional[int]  =				model(__a		)

        _UpperCamelCase					:		Optional[Any]  =				model(__a		)

        self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, self.seq_length, self.hidden_size)		)
        self.parent.assertEqual(result.pooler_output.shape    ,      (self.batch_size, self.hidden_size)		)

  def       __SCREAMING_SNAKE_CASE (						self      :				str    ,      __a      :				str    ,      __a      :				int    ,      __a      :				List[str]    ,      __a      :				Any    ,      __a      :				Any    ,      __a      :				Optional[int]    ,      __a      :				Optional[int]		)						-> Optional[int]:
        _UpperCamelCase					:		List[Any]  =				self.num_labels
        _UpperCamelCase					:		Optional[Any]  =				TFAlbertForPreTraining(config=__a		)
        _UpperCamelCase					:		Tuple  =				{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
        _UpperCamelCase					:		Dict  =				model(__a		)
        self.parent.assertEqual(result.prediction_logits.shape    ,      (self.batch_size, self.seq_length, self.vocab_size)		)
        self.parent.assertEqual(result.sop_logits.shape    ,      (self.batch_size, self.num_labels)		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Any    ,      __a      :				str    ,      __a      :				str    ,      __a      :				str    ,      __a      :				Dict    ,      __a      :				Optional[int]    ,      __a      :				List[Any]    ,      __a      :				str		)						-> Optional[int]:
        _UpperCamelCase					:		Any  =				TFAlbertForMaskedLM(config=__a		)
        _UpperCamelCase					:		Optional[int]  =				{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
        _UpperCamelCase					:		Optional[Any]  =				model(__a		)
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.seq_length, self.vocab_size)		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Any    ,      __a      :				str    ,      __a      :				int    ,      __a      :				Union[str, Any]    ,      __a      :				Union[str, Any]    ,      __a      :				str    ,      __a      :				Dict    ,      __a      :				Any		)						-> Dict:
        _UpperCamelCase					:		List[str]  =				self.num_labels
        _UpperCamelCase					:		Optional[Any]  =				TFAlbertForSequenceClassification(config=__a		)
        _UpperCamelCase					:		int  =				{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
        _UpperCamelCase					:		int  =				model(__a		)
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.num_labels)		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[int]    ,      __a      :				Optional[int]    ,      __a      :				int    ,      __a      :				Tuple    ,      __a      :				Union[str, Any]    ,      __a      :				List[Any]    ,      __a      :				str    ,      __a      :				Optional[int]		)						-> List[Any]:
        _UpperCamelCase					:		Union[str, Any]  =				TFAlbertForQuestionAnswering(config=__a		)
        _UpperCamelCase					:		Any  =				{"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
        _UpperCamelCase					:		Dict  =				model(__a		)
        self.parent.assertEqual(result.start_logits.shape    ,      (self.batch_size, self.seq_length)		)
        self.parent.assertEqual(result.end_logits.shape    ,      (self.batch_size, self.seq_length)		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Any    ,      __a      :				Optional[int]    ,      __a      :				Optional[Any]    ,      __a      :				Tuple    ,      __a      :				List[str]    ,      __a      :				List[str]    ,      __a      :				Tuple    ,      __a      :				Union[str, Any]		)						-> Dict:
        _UpperCamelCase					:		Tuple  =				self.num_choices
        _UpperCamelCase					:		Tuple  =				TFAlbertForMultipleChoice(config=__a		)
        _UpperCamelCase					:		Optional[Any]  =				tf.tile(tf.expand_dims(__a    ,      1		)    ,      (1, self.num_choices, 1)		)
        _UpperCamelCase					:		Dict  =				tf.tile(tf.expand_dims(__a    ,      1		)    ,      (1, self.num_choices, 1)		)
        _UpperCamelCase					:		Union[str, Any]  =				tf.tile(tf.expand_dims(__a    ,      1		)    ,      (1, self.num_choices, 1)		)
        _UpperCamelCase					:		Tuple  =				{
            "input_ids": multiple_choice_inputs_ids,
            "attention_mask": multiple_choice_input_mask,
            "token_type_ids": multiple_choice_token_type_ids,
        }
        _UpperCamelCase					:		Tuple  =				model(__a		)
        self.parent.assertListEqual(list(result["logits"].shape		)    ,      [self.batch_size, self.num_choices]		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Tuple    ,      __a      :				Optional[int]    ,      __a      :				Union[str, Any]    ,      __a      :				Union[str, Any]    ,      __a      :				int    ,      __a      :				int    ,      __a      :				Union[str, Any]    ,      __a      :				str		)						-> str:
        _UpperCamelCase					:		Any  =				self.num_labels
        _UpperCamelCase					:		int  =				TFAlbertForTokenClassification(config=__a		)
        _UpperCamelCase					:		Optional[Any]  =				{
            "input_ids": input_ids,
            "attention_mask": input_mask,
            "token_type_ids": token_type_ids,
        }
        _UpperCamelCase					:		Optional[Any]  =				model(__a		)
        self.parent.assertListEqual(list(result["logits"].shape		)    ,      [self.batch_size, self.seq_length, self.num_labels]		)


  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Optional[int]:
        _UpperCamelCase					:		Tuple  =				self.prepare_config_and_inputs()
        (
            (
            _UpperCamelCase
        ),     (
            _UpperCamelCase
        ),     (
            _UpperCamelCase
        ),     (
            _UpperCamelCase
        ),     (
            _UpperCamelCase
        ),     (
            _UpperCamelCase
        ),     (
            _UpperCamelCase
        ),     
        )					:		List[Any]  =				config_and_inputs
        _UpperCamelCase					:		Union[str, Any]  =				{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
        return config, inputs_dict





@require_tf
class    __SCREAMING_SNAKE_CASE			(  _UpperCamelCase						,     _UpperCamelCase						,     unittest.TestCase      ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Optional[int]		   =    (
      (
          TFAlbertModel,
          TFAlbertForPreTraining,
          TFAlbertForMaskedLM,
          TFAlbertForSequenceClassification,
          TFAlbertForQuestionAnswering,
          TFAlbertForTokenClassification,
          TFAlbertForMultipleChoice,
      )
      if is_tf_available()
      else ()
  )
  SCREAMING_SNAKE_CASE__							:Optional[int]		   =    (
      {
          "feature-extraction": TFAlbertModel,
          "fill-mask": TFAlbertForMaskedLM,
          "question-answering": TFAlbertForQuestionAnswering,
          "text-classification": TFAlbertForSequenceClassification,
          "token-classification": TFAlbertForTokenClassification,
          "zero-shot": TFAlbertForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  SCREAMING_SNAKE_CASE__							:Dict		   =    False
  SCREAMING_SNAKE_CASE__							:str		   =    False

  def       __SCREAMING_SNAKE_CASE (						self      :				Any    ,      __a      :				Optional[int]    ,      __a      :				List[Any]    ,      __a      :				Union[str, Any]=False		)						-> Tuple:
        _UpperCamelCase					:		Tuple  =				super()._prepare_for_class(__a    ,      __a    ,      return_labels=__a		)

        if return_labels:
              if model_class in get_values(__a		):
                    _UpperCamelCase					:		Dict  =				tf.zeros(self.model_tester.batch_size    ,      dtype=tf.intaa		)

        return inputs_dict

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> List[Any]:
        _UpperCamelCase					:		Union[str, Any]  =				TFAlbertModelTester(self		)
        _UpperCamelCase					:		Optional[int]  =				ConfigTester(self    ,      config_class=__a    ,      hidden_size=37		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Tuple		)						-> Optional[int]:
        self.config_tester.run_common_tests()

  def       __SCREAMING_SNAKE_CASE (						self      :				Any		)						-> int:
        _UpperCamelCase					:		Any  =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_albert_model(*__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				List[str]		)						-> str:
        _UpperCamelCase					:		Optional[Any]  =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_albert_for_pretraining(*__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				int		)						-> Dict:
        _UpperCamelCase					:		Any  =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_albert_for_masked_lm(*__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> Optional[Any]:
        _UpperCamelCase					:		Any  =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_albert_for_multiple_choice(*__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Any		)						-> Optional[int]:
        _UpperCamelCase					:		Dict  =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_albert_for_sequence_classification(*__a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				Dict		)						-> List[str]:
        _UpperCamelCase					:		Union[str, Any]  =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_albert_for_question_answering(*__a		)


  @slow
  def       __SCREAMING_SNAKE_CASE (						self      :				Union[str, Any]		)						-> List[Any]:
        for model_name in TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase					:		List[Any]  =				TFAlbertModel.from_pretrained(__a		)
              self.assertIsNotNone(__a		)





@require_tf
class    __SCREAMING_SNAKE_CASE			(  unittest.TestCase      ):







  '''simple docstring'''


  @slow
  def       __SCREAMING_SNAKE_CASE (						self      :				str		)						-> str:
        _UpperCamelCase					:		List[Any]  =				TFAlbertForPreTraining.from_pretrained("albert-base-v2"		)
        _UpperCamelCase					:		str  =				tf.constant([[0, 1, 2, 3, 4, 5]]		)
        _UpperCamelCase					:		Dict  =				model(__a		)[0]

        _UpperCamelCase					:		Any  =				[1, 6, 3_0000]
        self.assertEqual(output.shape    ,      __a		)

        _UpperCamelCase					:		Optional[int]  =				tf.constant(
            [
                [
                    [4.59_56_68, 0.74_46_27_54, -1.81_81_47],
                    [4.5_95_43_47, 0.7_45_41_84, -1.8_18_82_58],
                    [4.5_95_49_05, 0.7_44_82_35, -1.8_18_23_16],
                ]
            ]		)
        tf.debugging.assert_near(output[:, :3, :3]    ,      __a    ,      atol=1e-4		)







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