




'''simple docstring'''


import os
import unittest

from transformers import ElectraTokenizerFast
from transformers.models.electra.tokenization_electra import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    ElectraTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english






@require_tokenizers
class 	lowerCAmelCase_  (					UpperCAmelCase_					,				unittest.TestCase       ):







  '''simple docstring'''

  UpperCamelCase_ :			Union[str, Any]        =							ElectraTokenizer
  UpperCamelCase_ :			Tuple        =							ElectraTokenizerFast
  UpperCamelCase_ :			int        =							True
  UpperCamelCase_ :			List[str]        =							True
  UpperCamelCase_ :			Optional[int]        =							filter_non_english



  def 				_snake_case    (   self							:       int  ) ->		str:







       '''simple docstring'''



       super().setUp()

       A:		Union[str, Any]        =		[
           '''[UNK]''',
           '''[CLS]''',
           '''[SEP]''',
           '''[PAD]''',
           '''[MASK]''',
           '''want''',
           '''##want''',
           '''##ed''',
           '''wa''',
           '''un''',
           '''runn''',
           '''##ing''',
           ''',''',
           '''low''',
           '''lowest''',
       ]
       A:		Optional[Any]        =		os.path.join(self.tmpdirname				,     VOCAB_FILES_NAMES['''vocab_file''']  )
       with open(self.vocab_file				,     '''w'''				,     encoding='''utf-8'''  ) as vocab_writer:
            vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]  )  )



  def 				_snake_case    (   self							:       Optional[Any]				,     SCREAMING_SNAKE_CASE_							:       str  ) ->		Union[str, Any]:







       '''simple docstring'''



       A:		Tuple        =		'''UNwant\u00E9d,running'''
       A:		Optional[Any]        =		'''unwanted, running'''
       return input_text, output_text



  def 				_snake_case    (   self							:       Optional[Any]  ) ->		Tuple:







       '''simple docstring'''



       A:		List[str]        =		self.tokenizer_class(self.vocab_file  )

       A:		List[str]        =		tokenizer.tokenize('''UNwant\u00E9d,running'''  )
       self.assertListEqual(SCREAMING_SNAKE_CASE_				,     ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']  )
       self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_  )				,     [9, 6, 7, 12, 10, 11]  )



  def 				_snake_case    (   self							:       Optional[Any]  ) ->		str:







       '''simple docstring'''



       if not self.test_rust_tokenizer:
            return

       A:		str        =		self.get_tokenizer()
       A:		Union[str, Any]        =		self.get_rust_tokenizer()

       A:		Dict        =		'''UNwant\u00E9d,running'''

       A:		Optional[int]        =		tokenizer.tokenize(SCREAMING_SNAKE_CASE_  )
       A:		List[str]        =		rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_  )
       self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )

       A:		Any        =		tokenizer.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )
       A:		Tuple        =		rust_tokenizer.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )
       self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )

       A:		List[Any]        =		self.get_rust_tokenizer()
       A:		Dict        =		tokenizer.encode(SCREAMING_SNAKE_CASE_  )
       A:		Dict        =		rust_tokenizer.encode(SCREAMING_SNAKE_CASE_  )
       self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )

       # With lower casing
       A:		Tuple        =		self.get_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE_  )
       A:		List[Any]        =		self.get_rust_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE_  )

       A:		Union[str, Any]        =		'''UNwant\u00E9d,running'''

       A:		List[Any]        =		tokenizer.tokenize(SCREAMING_SNAKE_CASE_  )
       A:		Any        =		rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_  )
       self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )

       A:		Union[str, Any]        =		tokenizer.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )
       A:		List[Any]        =		rust_tokenizer.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )
       self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )

       A:		Optional[int]        =		self.get_rust_tokenizer()
       A:		Optional[int]        =		tokenizer.encode(SCREAMING_SNAKE_CASE_  )
       A:		Dict        =		rust_tokenizer.encode(SCREAMING_SNAKE_CASE_  )
       self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )



  def 				_snake_case    (   self							:       Union[str, Any]  ) ->		int:







       '''simple docstring'''



       A:		List[Any]        =		BasicTokenizer()

       self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz'''  )				,     ['''ah''', '''\u535A''', '''\u63A8''', '''zz''']  )



  def 				_snake_case    (   self							:       Dict  ) ->		List[Any]:







       '''simple docstring'''



       A:		Tuple        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  )				,     ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  )				,     ['''hello''']  )



  def 				_snake_case    (   self							:       int  ) ->		int:







       '''simple docstring'''



       A:		Tuple        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_				,     strip_accents=SCREAMING_SNAKE_CASE_  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  )				,     ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  )				,     ['''h\u00E9llo''']  )



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







       '''simple docstring'''



       A:		Dict        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_				,     strip_accents=SCREAMING_SNAKE_CASE_  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  )				,     ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  )				,     ['''hello''']  )



  def 				_snake_case    (   self							:       int  ) ->		Any:







       '''simple docstring'''



       A:		int        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  )				,     ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  )				,     ['''hello''']  )



  def 				_snake_case    (   self							:       Optional[int]  ) ->		Union[str, Any]:







       '''simple docstring'''



       A:		List[str]        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  )				,     ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )



  def 				_snake_case    (   self							:       Union[str, Any]  ) ->		Dict:







       '''simple docstring'''



       A:		Any        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_				,     strip_accents=SCREAMING_SNAKE_CASE_  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  )				,     ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )



  def 				_snake_case    (   self							:       str  ) ->		Optional[Any]:







       '''simple docstring'''



       A:		Dict        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_				,     strip_accents=SCREAMING_SNAKE_CASE_  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  )				,     ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )



  def 				_snake_case    (   self							:       List[Any]  ) ->		Union[str, Any]:







       '''simple docstring'''



       A:		Dict        =		BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_				,     never_split=['''[UNK]''']  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU? [UNK]'''  )				,     ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]''']  )



  def 				_snake_case    (   self							:       Dict  ) ->		int:







       '''simple docstring'''



       A:		Dict        =		['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']

       A:		Tuple        =		{}
       for i, token in enumerate(SCREAMING_SNAKE_CASE_  ):
            A:		str        =		i
       A:		Optional[Any]        =		WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_				,     unk_token='''[UNK]'''  )

       self.assertListEqual(tokenizer.tokenize(''''''  )				,     []  )

       self.assertListEqual(tokenizer.tokenize('''unwanted running'''  )				,     ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing''']  )

       self.assertListEqual(tokenizer.tokenize('''unwantedX running'''  )				,     ['''[UNK]''', '''runn''', '''##ing''']  )



  def 				_snake_case    (   self							:       Union[str, Any]  ) ->		Dict:







       '''simple docstring'''



       self.assertTrue(_is_whitespace(''' '''  )  )
       self.assertTrue(_is_whitespace('''\t'''  )  )
       self.assertTrue(_is_whitespace('''\r'''  )  )
       self.assertTrue(_is_whitespace('''\n'''  )  )
       self.assertTrue(_is_whitespace('''\u00A0'''  )  )

       self.assertFalse(_is_whitespace('''A'''  )  )
       self.assertFalse(_is_whitespace('''-'''  )  )



  def 				_snake_case    (   self							:       List[str]  ) ->		List[str]:







       '''simple docstring'''



       self.assertTrue(_is_control('''\u0005'''  )  )

       self.assertFalse(_is_control('''A'''  )  )
       self.assertFalse(_is_control(''' '''  )  )
       self.assertFalse(_is_control('''\t'''  )  )
       self.assertFalse(_is_control('''\r'''  )  )



  def 				_snake_case    (   self							:       int  ) ->		Any:







       '''simple docstring'''



       self.assertTrue(_is_punctuation('''-'''  )  )
       self.assertTrue(_is_punctuation('''$'''  )  )
       self.assertTrue(_is_punctuation('''`'''  )  )
       self.assertTrue(_is_punctuation('''.'''  )  )

       self.assertFalse(_is_punctuation('''A'''  )  )
       self.assertFalse(_is_punctuation(''' '''  )  )



  def 				_snake_case    (   self							:       str  ) ->		int:







       '''simple docstring'''



       A:		Dict        =		self.get_tokenizer()
       A:		Dict        =		self.get_rust_tokenizer()

       # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
       self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE_  ) for t in ['''Test''', '''\xad''', '''test''']]				,     [['''[UNK]'''], [], ['''[UNK]''']]  )

       self.assertListEqual(
           [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_  ) for t in ['''Test''', '''\xad''', '''test''']]				,     [['''[UNK]'''], [], ['''[UNK]''']]  )



  @slow
  def 				_snake_case    (   self							:       Any  ) ->		Optional[int]:







       '''simple docstring'''



       A:		str        =		self.tokenizer_class.from_pretrained('''google/electra-base-discriminator'''  )

       A:		Dict        =		tokenizer.encode('''sequence builders'''				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )
       A:		Dict        =		tokenizer.encode('''multi-sequence build'''				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )

       A:		Optional[int]        =		tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_  )
       A:		Optional[int]        =		tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )

       assert encoded_sentence == [1_01] + text + [1_02]
       assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02]



  def 				_snake_case    (   self							:       Dict  ) ->		Any:







       '''simple docstring'''



       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""  ):
                 A:		Dict        =		self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )

                 A:		Tuple        =		f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
                 A:		Tuple        =		tokenizer_r.encode_plus(
                     SCREAMING_SNAKE_CASE_				,     return_attention_mask=SCREAMING_SNAKE_CASE_				,     return_token_type_ids=SCREAMING_SNAKE_CASE_				,     return_offsets_mapping=SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_				,     )

                 A:		int        =		tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE_				,     '''do_lower_case'''  ) else False
                 A:		Any        =		(
                     [
                         ((0, 0), tokenizer_r.cls_token),
                         ((0, 1), '''A'''),
                         ((1, 2), ''','''),
                         ((3, 5), '''na'''),
                         ((5, 6), '''##ï'''),
                         ((6, 8), '''##ve'''),
                         ((9, 15), tokenizer_r.mask_token),
                         ((16, 21), '''Allen'''),
                         ((21, 23), '''##NL'''),
                         ((23, 24), '''##P'''),
                         ((25, 33), '''sentence'''),
                         ((33, 34), '''.'''),
                         ((0, 0), tokenizer_r.sep_token),
                     ]
                     if not do_lower_case
                     else [
                         ((0, 0), tokenizer_r.cls_token),
                         ((0, 1), '''a'''),
                         ((1, 2), ''','''),
                         ((3, 8), '''naive'''),
                         ((9, 15), tokenizer_r.mask_token),
                         ((16, 21), '''allen'''),
                         ((21, 23), '''##nl'''),
                         ((23, 24), '''##p'''),
                         ((25, 33), '''sentence'''),
                         ((33, 34), '''.'''),
                         ((0, 0), tokenizer_r.sep_token),
                     ]
                 )

                 self.assertEqual(
                     [e[1] for e in expected_results]				,     tokenizer_r.convert_ids_to_tokens(tokens['''input_ids''']  )  )
                 self.assertEqual([e[0] for e in expected_results]				,     tokens['''offset_mapping''']  )




  def 				_snake_case    (   self							:       str  ) ->		Optional[Any]:







       '''simple docstring'''



       A:		Optional[Any]        =		['''的''', '''人''', '''有''']
       A:		Any        =		''''''.join(SCREAMING_SNAKE_CASE_  )
       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
            with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""  ):
                 A:		Dict        =		True
                 A:		Tuple        =		self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )
                 A:		List[Any]        =		self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )

                 A:		List[str]        =		tokenizer_p.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )
                 A:		Dict        =		tokenizer_r.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )

                 A:		str        =		tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_  )
                 A:		List[Any]        =		tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_  )

                 # it is expected that each Chinese character is not preceded by "##"
                 self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )
                 self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )

                 A:		List[str]        =		False
                 A:		Tuple        =		self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )
                 A:		Optional[int]        =		self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )

                 A:		Tuple        =		tokenizer_r.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )
                 A:		Dict        =		tokenizer_p.encode(SCREAMING_SNAKE_CASE_				,     add_special_tokens=SCREAMING_SNAKE_CASE_  )

                 A:		str        =		tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_  )
                 A:		Union[str, Any]        =		tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_  )

                 # it is expected that only the first Chinese character is not preceded by "##".
                 A:		Any        =		[
                     f"""##{token}""" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE_  )
                 ]
                 self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )
                 self.assertListEqual(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )












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


UpperCamelCase     =				logging.get_logger(__name__)






class 	lowerCAmelCase_  (					nn.Module       ):







  '''simple docstring'''

  UpperCamelCase_ :			HybridCLIPConfig
  UpperCamelCase_ :			jnp.dtype        =							jnp.floataa



  def 				_snake_case    (   self							:       List[str]  ) ->		int:







       '''simple docstring'''



       A:		List[Any]        =		self.config.text_config
       A:		Any        =		self.config.vision_config

       A:		Union[str, Any]        =		self.config.projection_dim
       A:		List[str]        =		text_config.hidden_size
       A:		List[str]        =		vision_config.hidden_size

       A:		List[Any]        =		FLAX_MODEL_MAPPING[self.config.text_config.__class__].module_class
       A:		int        =		FLAX_MODEL_MAPPING.get(self.config.vision_config.__class__				,     SCREAMING_SNAKE_CASE_  ).module_class

       A:		str        =		text_module(SCREAMING_SNAKE_CASE_				,     dtype=self.dtype  )
       A:		Union[str, Any]        =		vision_module(SCREAMING_SNAKE_CASE_				,     dtype=self.dtype  )

       A:		Any        =		nn.Dense(
           self.projection_dim				,     dtype=self.dtype				,     kernel_init=jax.nn.initializers.normal(0.02  )				,     use_bias=SCREAMING_SNAKE_CASE_				,     )
       A:		Tuple        =		nn.Dense(
           self.projection_dim				,     dtype=self.dtype				,     kernel_init=jax.nn.initializers.normal(0.02  )				,     use_bias=SCREAMING_SNAKE_CASE_				,     )
       A:		Dict        =		self.param('''logit_scale'''				,     jax.nn.initializers.ones				,     []  )




  def __call__(   self							:       List[Any]				,     SCREAMING_SNAKE_CASE_							:       Dict=None				,     SCREAMING_SNAKE_CASE_							:       List[Any]=None				,     SCREAMING_SNAKE_CASE_							:       Optional[int]=None				,     SCREAMING_SNAKE_CASE_							:       Dict=None				,     SCREAMING_SNAKE_CASE_							:       Optional[Any]=None				,     SCREAMING_SNAKE_CASE_							:       bool = True				,     SCREAMING_SNAKE_CASE_							:       Tuple=None				,     SCREAMING_SNAKE_CASE_							:       Optional[Any]=None				,     SCREAMING_SNAKE_CASE_							:       Tuple=None				,     ) ->		Tuple:







       '''simple docstring'''



       A:		Optional[int]        =		return_dict if return_dict is not None else self.config.return_dict

       A:		List[str]        =		self.vision_model(
           pixel_values=SCREAMING_SNAKE_CASE_				,     deterministic=SCREAMING_SNAKE_CASE_				,     output_attentions=SCREAMING_SNAKE_CASE_				,     output_hidden_states=SCREAMING_SNAKE_CASE_				,     return_dict=SCREAMING_SNAKE_CASE_				,     )

       A:		Tuple        =		self.text_model(
           input_ids=SCREAMING_SNAKE_CASE_				,     attention_mask=SCREAMING_SNAKE_CASE_				,     token_type_ids=SCREAMING_SNAKE_CASE_				,     position_ids=SCREAMING_SNAKE_CASE_				,     deterministic=SCREAMING_SNAKE_CASE_				,     output_attentions=SCREAMING_SNAKE_CASE_				,     output_hidden_states=SCREAMING_SNAKE_CASE_				,     return_dict=SCREAMING_SNAKE_CASE_				,     )

       A:		str        =		vision_outputs[1]
       A:		Any        =		self.visual_projection(SCREAMING_SNAKE_CASE_  )

       A:		Optional[int]        =		text_outputs[1]
       A:		str        =		self.text_projection(SCREAMING_SNAKE_CASE_  )

       # normalized features
       A:		Tuple        =		image_embeds / jnp.linalg.norm(SCREAMING_SNAKE_CASE_				,     axis=-1				,     keepdims=SCREAMING_SNAKE_CASE_  )
       A:		Tuple        =		text_embeds / jnp.linalg.norm(SCREAMING_SNAKE_CASE_				,     axis=-1				,     keepdims=SCREAMING_SNAKE_CASE_  )

       # cosine similarity as logits
       A:		Optional[int]        =		jnp.exp(self.logit_scale  )
       A:		Union[str, Any]        =		jnp.matmul(SCREAMING_SNAKE_CASE_				,     image_embeds.T  ) * logit_scale
       A:		Tuple        =		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=SCREAMING_SNAKE_CASE_				,     logits_per_text=SCREAMING_SNAKE_CASE_				,     text_embeds=SCREAMING_SNAKE_CASE_				,     image_embeds=SCREAMING_SNAKE_CASE_				,     text_model_output=SCREAMING_SNAKE_CASE_				,     vision_model_output=SCREAMING_SNAKE_CASE_				,     )






class 	lowerCAmelCase_  (					UpperCAmelCase_       ):







  '''simple docstring'''

  UpperCamelCase_ :			Union[str, Any]        =							HybridCLIPConfig
  UpperCamelCase_ :			List[str]        =							FlaxHybridCLIPModule



  def __init__(   self							:       Union[str, Any]				,     SCREAMING_SNAKE_CASE_							:       HybridCLIPConfig				,     SCREAMING_SNAKE_CASE_							:       Optional[Tuple] = None				,     SCREAMING_SNAKE_CASE_							:       int = 0				,     SCREAMING_SNAKE_CASE_							:       jnp.dtype = jnp.floataa				,     **SCREAMING_SNAKE_CASE_							:       str				,     ) ->		int:







       '''simple docstring'''



       if input_shape is None:
            A:		List[Any]        =		((1, 1), (1, config.vision_config.image_size, config.vision_config.image_size, 3))

       A:		int        =		self.module_class(config=SCREAMING_SNAKE_CASE_				,     dtype=SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )
       super().__init__(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_				,     input_shape=SCREAMING_SNAKE_CASE_				,     seed=SCREAMING_SNAKE_CASE_				,     dtype=SCREAMING_SNAKE_CASE_  )



  def 				_snake_case    (   self							:       List[Any]				,     SCREAMING_SNAKE_CASE_							:       jax.random.PRNGKey				,     SCREAMING_SNAKE_CASE_							:       Tuple				,     SCREAMING_SNAKE_CASE_							:       FrozenDict = None  ) ->		FrozenDict:







       '''simple docstring'''



       A:		List[Any]        =		jnp.zeros(input_shape[0]				,     dtype='''i4'''  )
       A:		List[str]        =		jnp.broadcast_to(jnp.arange(jnp.atleast_ad(SCREAMING_SNAKE_CASE_  ).shape[-1]  )				,     input_shape[0]  )
       A:		Union[str, Any]        =		jnp.ones_like(SCREAMING_SNAKE_CASE_  )
       A:		Union[str, Any]        =		jnp.ones_like(SCREAMING_SNAKE_CASE_  )

       A:		Any        =		jax.random.normal(SCREAMING_SNAKE_CASE_				,     input_shape[1]  )

       A    ,						A:		int        =		jax.random.split(SCREAMING_SNAKE_CASE_  )
       A:		Dict        =		{'''params''': params_rng, '''dropout''': dropout_rng}

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



  def __call__(   self							:       List[Any]				,     SCREAMING_SNAKE_CASE_							:       str				,     SCREAMING_SNAKE_CASE_							:       Any				,     SCREAMING_SNAKE_CASE_							:       int=None				,     SCREAMING_SNAKE_CASE_							:       Any=None				,     SCREAMING_SNAKE_CASE_							:       List[str]=None				,     SCREAMING_SNAKE_CASE_							:       dict = None				,     SCREAMING_SNAKE_CASE_							:       jax.random.PRNGKey = None				,     SCREAMING_SNAKE_CASE_							:       bool = False				,     SCREAMING_SNAKE_CASE_							:       Optional[bool] = None				,     SCREAMING_SNAKE_CASE_							:       Optional[bool] = None				,     SCREAMING_SNAKE_CASE_							:       Optional[bool] = None				,     ) ->		str:







       '''simple docstring'''



       A:		List[str]        =		output_attentions if output_attentions is not None else self.config.output_attentions
       A:		int        =		(
           output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
       )
       A:		Dict        =		return_dict if return_dict is not None else self.config.return_dict

       if position_ids is None:
            A:		Any        =		jnp.broadcast_to(jnp.arange(jnp.atleast_ad(SCREAMING_SNAKE_CASE_  ).shape[-1]  )				,     input_ids.shape  )

       if token_type_ids is None:
            A:		Tuple        =		jnp.zeros_like(SCREAMING_SNAKE_CASE_  )

       if attention_mask is None:
            A:		Any        =		jnp.ones_like(SCREAMING_SNAKE_CASE_  )

       # Handle any PRNG if needed
       A:		Union[str, Any]        =		{}
       if dropout_rng is not None:
            A:		Any        =		dropout_rng

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



  def 				_snake_case    (   self							:       str				,     SCREAMING_SNAKE_CASE_							:       Optional[int]				,     SCREAMING_SNAKE_CASE_							:       str=None				,     SCREAMING_SNAKE_CASE_							:       Optional[int]=None				,     SCREAMING_SNAKE_CASE_							:       Union[str, Any]=None				,     SCREAMING_SNAKE_CASE_							:       dict = None				,     SCREAMING_SNAKE_CASE_							:       jax.random.PRNGKey = None				,     SCREAMING_SNAKE_CASE_							:       Union[str, Any]=False				,     ) ->		Optional[Any]:







       '''simple docstring'''



       if position_ids is None:
            A:		Any        =		jnp.broadcast_to(jnp.arange(jnp.atleast_ad(SCREAMING_SNAKE_CASE_  ).shape[-1]  )				,     input_ids.shape  )

       if token_type_ids is None:
            A:		List[str]        =		jnp.zeros_like(SCREAMING_SNAKE_CASE_  )

       if attention_mask is None:
            A:		Union[str, Any]        =		jnp.ones_like(SCREAMING_SNAKE_CASE_  )

       # Handle any PRNG if needed
       A:		Any        =		{}
       if dropout_rng is not None:
            A:		Tuple        =		dropout_rng

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

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



  def 				_snake_case    (   self							:       int				,     SCREAMING_SNAKE_CASE_							:       List[Any]				,     SCREAMING_SNAKE_CASE_							:       dict = None				,     SCREAMING_SNAKE_CASE_							:       jax.random.PRNGKey = None				,     SCREAMING_SNAKE_CASE_							:       List[str]=False  ) ->		Union[str, Any]:







       '''simple docstring'''



       A:		Union[str, Any]        =		{}
       if dropout_rng is not None:
            A:		Any        =		dropout_rng

       def _get_features(SCREAMING_SNAKE_CASE_							:       Dict				,     SCREAMING_SNAKE_CASE_							:       Dict				,     SCREAMING_SNAKE_CASE_							:       Any  ):
            A:		List[str]        =		module.vision_model(pixel_values=SCREAMING_SNAKE_CASE_				,     deterministic=SCREAMING_SNAKE_CASE_  )
            A:		Union[str, Any]        =		vision_outputs[1]  # pooled_output
            A:		Any        =		module.visual_projection(SCREAMING_SNAKE_CASE_  )
            return image_features

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




  @classmethod
  def 				_snake_case    (   cls							:       Optional[int]				,     SCREAMING_SNAKE_CASE_							:       str = None				,     SCREAMING_SNAKE_CASE_							:       str = None				,     *SCREAMING_SNAKE_CASE_							:       Any				,     **SCREAMING_SNAKE_CASE_							:       List[str]				,     ) ->		FlaxPreTrainedModel:







       '''simple docstring'''



       A:		List[Any]        =		{
           argument[len('''text_'''  ) :]: value for argument, value in kwargs.items() if argument.startswith('''text_'''  )
       }

       A:		str        =		{
           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
       A:		Union[str, Any]        =		kwargs_text.pop('''model'''				,     SCREAMING_SNAKE_CASE_  )
       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

                 A:		List[str]        =		AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_  )
                 A:		Optional[int]        =		text_config

            A:		Optional[int]        =		FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_				,     *SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )

       A:		Optional[int]        =		kwargs_vision.pop('''model'''				,     SCREAMING_SNAKE_CASE_  )
       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

                 A:		Any        =		AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_  )
                 A:		Dict        =		vision_config

            A:		Union[str, Any]        =		FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE_				,     *SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )

       # instantiate config with corresponding kwargs
       A:		Dict        =		kwargs.pop('''dtype'''				,     jnp.floataa  )
       A:		Any        =		HybridCLIPConfig.from_text_vision_configs(text_model.config				,     vision_model.config				,     **SCREAMING_SNAKE_CASE_  )

       # init model
       A:		List[str]        =		cls(SCREAMING_SNAKE_CASE_				,     *SCREAMING_SNAKE_CASE_				,     dtype=SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )

       if vision_config.model_type == "clip":
            A:		List[Any]        =		vision_model.params['''vision_model''']
            A:		int        =		vision_model.params['''visual_projection''']['''kernel''']
       else:
            A:		Tuple        =		vision_model.params

       A:		Tuple        =		text_model.params

       return model






