






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


__snake_case     :     Any       =  logging.get_logger(__name__)


class      __SCREAMING_SNAKE_CASE       ( nn.Module):
						_SCREAMING_SNAKE_CASE						:							HybridCLIPConfig
						_SCREAMING_SNAKE_CASE						:							jnp.dtype				=       jnp.floataa






						def    UpperCamelCase__   (						self ):






												"""simple docstring"""
												lowerCAmelCase__         =    self.config.text_config
												lowerCAmelCase__         =    self.config.vision_config

												lowerCAmelCase__         =    self.config.projection_dim
												lowerCAmelCase__         =    text_config.hidden_size
												lowerCAmelCase__         =    vision_config.hidden_size

												lowerCAmelCase__         =    FLAX_MODEL_MAPPING[self.config.text_config.__class__].module_class
												lowerCAmelCase__         =    FLAX_MODEL_MAPPING.get(self.config.vision_config.__class__  ,    _UpperCamelCase ).module_class

												lowerCAmelCase__         =    text_module(_UpperCamelCase  ,    dtype=self.dtype )
												lowerCAmelCase__         =    vision_module(_UpperCamelCase  ,    dtype=self.dtype )

												lowerCAmelCase__         =    nn.Dense(
												    self.projection_dim  ,    dtype=self.dtype  ,    kernel_init=jax.nn.initializers.normal(0.02 )  ,    use_bias=_UpperCamelCase  ,    )
												lowerCAmelCase__         =    nn.Dense(
												    self.projection_dim  ,    dtype=self.dtype  ,    kernel_init=jax.nn.initializers.normal(0.02 )  ,    use_bias=_UpperCamelCase  ,    )
												lowerCAmelCase__         =    self.param('logit_scale'  ,    jax.nn.initializers.ones  ,    [] )







						def __call__(						self  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase = True  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    ):






												"""simple docstring"""
												lowerCAmelCase__         =    return_dict if return_dict is not None else self.config.return_dict

												lowerCAmelCase__         =    self.vision_model(
												    pixel_values=_UpperCamelCase  ,    deterministic=_UpperCamelCase  ,    output_attentions=_UpperCamelCase  ,    output_hidden_states=_UpperCamelCase  ,    return_dict=_UpperCamelCase  ,    )

												lowerCAmelCase__         =    self.text_model(
												    input_ids=_UpperCamelCase  ,    attention_mask=_UpperCamelCase  ,    token_type_ids=_UpperCamelCase  ,    position_ids=_UpperCamelCase  ,    deterministic=_UpperCamelCase  ,    output_attentions=_UpperCamelCase  ,    output_hidden_states=_UpperCamelCase  ,    return_dict=_UpperCamelCase  ,    )

												lowerCAmelCase__         =    vision_outputs[1]
												lowerCAmelCase__         =    self.visual_projection(_UpperCamelCase )

												lowerCAmelCase__         =    text_outputs[1]
												lowerCAmelCase__         =    self.text_projection(_UpperCamelCase )

												# normalized features
												lowerCAmelCase__         =    image_embeds / jnp.linalg.norm(_UpperCamelCase  ,    axis=-1  ,    keepdims=_UpperCamelCase )
												lowerCAmelCase__         =    text_embeds / jnp.linalg.norm(_UpperCamelCase  ,    axis=-1  ,    keepdims=_UpperCamelCase )

												# cosine similarity as logits
												lowerCAmelCase__         =    jnp.exp(self.logit_scale )
												lowerCAmelCase__         =    jnp.matmul(_UpperCamelCase  ,    image_embeds.T ) * logit_scale
												lowerCAmelCase__         =    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=_UpperCamelCase  ,    logits_per_text=_UpperCamelCase  ,    text_embeds=_UpperCamelCase  ,    image_embeds=_UpperCamelCase  ,    text_model_output=_UpperCamelCase  ,    vision_model_output=_UpperCamelCase  ,    )




class      __SCREAMING_SNAKE_CASE       ( __lowercase):
						_SCREAMING_SNAKE_CASE						:							Optional[int]				=       HybridCLIPConfig
						_SCREAMING_SNAKE_CASE						:							Dict				=       FlaxHybridCLIPModule






						def __init__(						self  ,    _UpperCamelCase  ,    _UpperCamelCase = None  ,    _UpperCamelCase = 0  ,    _UpperCamelCase = jnp.floataa  ,    **_UpperCamelCase  ,    ):






												"""simple docstring"""
												if input_shape is None:
																		lowerCAmelCase__         =    ((1, 1), (1, config.vision_config.image_size, config.vision_config.image_size, 3))

												lowerCAmelCase__         =    self.module_class(config=_UpperCamelCase  ,    dtype=_UpperCamelCase  ,    **_UpperCamelCase )
												super().__init__(_UpperCamelCase  ,    _UpperCamelCase  ,    input_shape=_UpperCamelCase  ,    seed=_UpperCamelCase  ,    dtype=_UpperCamelCase )






						def    UpperCamelCase__   (						self  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase = None ):






												"""simple docstring"""
												# init input tensor
												lowerCAmelCase__         =    jnp.zeros(input_shape[0]  ,    dtype='i4' )
												lowerCAmelCase__         =    jnp.broadcast_to(jnp.arange(jnp.atleast_ad(_UpperCamelCase ).shape[-1] )  ,    input_shape[0] )
												lowerCAmelCase__         =    jnp.ones_like(_UpperCamelCase )
												lowerCAmelCase__         =    jnp.ones_like(_UpperCamelCase )

												lowerCAmelCase__         =    jax.random.normal(_UpperCamelCase  ,    input_shape[1] )

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

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






						def __call__(						self  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    _UpperCamelCase = False  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    ):






												"""simple docstring"""
												lowerCAmelCase__         =    output_attentions if output_attentions is not None else self.config.output_attentions
												lowerCAmelCase__         =    (
												    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
												)
												lowerCAmelCase__         =    return_dict if return_dict is not None else self.config.return_dict

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

												if token_type_ids is None:
																		lowerCAmelCase__         =    jnp.zeros_like(_UpperCamelCase )

												if attention_mask is None:
																		lowerCAmelCase__         =    jnp.ones_like(_UpperCamelCase )

												# Handle any PRNG if needed
												lowerCAmelCase__         =    {}
												if dropout_rng is not None:
																		lowerCAmelCase__         =    dropout_rng

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






						def    UpperCamelCase__   (						self  ,    _UpperCamelCase  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase=None  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    _UpperCamelCase=False  ,    ):






												"""simple docstring"""
												if position_ids is None:
																		lowerCAmelCase__         =    jnp.broadcast_to(jnp.arange(jnp.atleast_ad(_UpperCamelCase ).shape[-1] )  ,    input_ids.shape )

												if token_type_ids is None:
																		lowerCAmelCase__         =    jnp.zeros_like(_UpperCamelCase )

												if attention_mask is None:
																		lowerCAmelCase__         =    jnp.ones_like(_UpperCamelCase )

												# Handle any PRNG if needed
												lowerCAmelCase__         =    {}
												if dropout_rng is not None:
																		lowerCAmelCase__         =    dropout_rng

												def _get_features(_UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase ):
																		lowerCAmelCase__         =    module.text_model(
																		    input_ids=_UpperCamelCase  ,    attention_mask=_UpperCamelCase  ,    position_ids=_UpperCamelCase  ,    token_type_ids=_UpperCamelCase  ,    deterministic=_UpperCamelCase  ,    )
																		lowerCAmelCase__         =    text_outputs[1]
																		lowerCAmelCase__         =    module.text_projection(_UpperCamelCase )
																		return text_features

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






						def    UpperCamelCase__   (						self  ,    _UpperCamelCase  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    _UpperCamelCase=False ):






												"""simple docstring"""
												lowerCAmelCase__         =    {}
												if dropout_rng is not None:
																		lowerCAmelCase__         =    dropout_rng

												def _get_features(_UpperCamelCase  ,    _UpperCamelCase  ,    _UpperCamelCase ):
																		lowerCAmelCase__         =    module.vision_model(pixel_values=_UpperCamelCase  ,    deterministic=_UpperCamelCase )
																		lowerCAmelCase__         =    vision_outputs[1]  # pooled_output
																		lowerCAmelCase__         =    module.visual_projection(_UpperCamelCase )
																		return image_features

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







						@classmethod
						def    UpperCamelCase__   (						cls  ,    _UpperCamelCase = None  ,    _UpperCamelCase = None  ,    *_UpperCamelCase  ,    **_UpperCamelCase  ,    ):






												"""simple docstring"""
												lowerCAmelCase__         =    {
												    argument[len('text_' ) :]: value for argument, value in kwargs.items() if argument.startswith('text_' )
												}

												lowerCAmelCase__         =    {
												    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
												lowerCAmelCase__         =    kwargs_text.pop('model'  ,    _UpperCamelCase )
												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

																								lowerCAmelCase__         =    AutoConfig.from_pretrained(_UpperCamelCase )
																								lowerCAmelCase__         =    text_config

																		lowerCAmelCase__         =    FlaxAutoModel.from_pretrained(_UpperCamelCase  ,    *_UpperCamelCase  ,    **_UpperCamelCase )

												lowerCAmelCase__         =    kwargs_vision.pop('model'  ,    _UpperCamelCase )
												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

																								lowerCAmelCase__         =    AutoConfig.from_pretrained(_UpperCamelCase )
																								lowerCAmelCase__         =    vision_config

																		lowerCAmelCase__         =    FlaxAutoModel.from_pretrained(_UpperCamelCase  ,    *_UpperCamelCase  ,    **_UpperCamelCase )

												# instantiate config with corresponding kwargs
												lowerCAmelCase__         =    kwargs.pop('dtype'  ,    jnp.floataa )
												lowerCAmelCase__         =    HybridCLIPConfig.from_text_vision_configs(text_model.config  ,    vision_model.config  ,    **_UpperCamelCase )

												# init model
												lowerCAmelCase__         =    cls(_UpperCamelCase  ,    *_UpperCamelCase  ,    dtype=_UpperCamelCase  ,    **_UpperCamelCase )

												if vision_config.model_type == "clip":
																		lowerCAmelCase__         =    vision_model.params['vision_model']
																		lowerCAmelCase__         =    vision_model.params['visual_projection']['kernel']
												else:
																		lowerCAmelCase__         =    vision_model.params

												lowerCAmelCase__         =    text_model.params

												return model













from __future__ import annotations







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]		)	-> list[int]:

						"""simple docstring"""



						if not list_of_ints:
												return []

						if min(UpperCamelCase_		) < 0:
												raise ValueError('All numbers must be positive'		)

						lowerCAmelCase__         =    max(len(bin(UpperCamelCase_		)[2:]		) for x in list_of_ints		)
						return _msd_radix_sort(UpperCamelCase_     ,							UpperCamelCase_		)







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]     ,							UpperCamelCase_							:       int		)	-> list[int]:

						"""simple docstring"""



						if bit_position == 0 or len(UpperCamelCase_		) in [0, 1]:
												return list_of_ints

						lowerCAmelCase__         =    []
						lowerCAmelCase__         =    []
						# Split numbers based on bit at bit_position from the right
						for number in list_of_ints:
												if (number >> (bit_position - 1)) & 1:
																		# number has a one at bit bit_position
																		ones.append(UpperCamelCase_		)
												else:
																		# number has a zero at bit bit_position
																		zeros.append(UpperCamelCase_		)

    # recursively split both lists further
						lowerCAmelCase__         =    _msd_radix_sort(UpperCamelCase_     ,							bit_position - 1		)
						lowerCAmelCase__         =    _msd_radix_sort(UpperCamelCase_     ,							bit_position - 1		)

						# recombine lists
						lowerCAmelCase__         =    zeros
						res.extend(UpperCamelCase_		)

						return res







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]		)	-> Any:

						"""simple docstring"""



						lowerCAmelCase__         =    len(UpperCamelCase_		)
						if not list_of_ints or length == 1:
												return

						if min(UpperCamelCase_		) < 0:
												raise ValueError('All numbers must be positive'		)

						lowerCAmelCase__         =    max(len(bin(UpperCamelCase_		)[2:]		) for x in list_of_ints		)
						_msd_radix_sort_inplace(UpperCamelCase_     ,							UpperCamelCase_     ,							0     ,							UpperCamelCase_		)







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]     ,							UpperCamelCase_							:       int     ,							UpperCamelCase_							:       int     ,							UpperCamelCase_							:       int		)	-> int:

						"""simple docstring"""



						if bit_position == 0 or end_index - begin_index <= 1:
												return

						bit_position -= 1

						lowerCAmelCase__         =    begin_index
						lowerCAmelCase__         =    end_index - 1
						while i <= j:
												lowerCAmelCase__         =    False
												if not (list_of_ints[i] >> bit_position) & 1:
																		# found zero at the beginning
																		i += 1
																		lowerCAmelCase__         =    True
												if (list_of_ints[j] >> bit_position) & 1:
																		# found one at the end
																		j -= 1
																		lowerCAmelCase__         =    True

												if changed:
																		continue

												lowerCAmelCase__    ,							lowerCAmelCase__         =    list_of_ints[j], list_of_ints[i]
												j -= 1
												if j != i:
																		i += 1

						_msd_radix_sort_inplace(UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_		)
						_msd_radix_sort_inplace(UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_		)


if __name__ == "__main__":
					import doctest

					doctest.testmod()





