



'''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						:		List[Any]						      = logging.get_logger(__name__)






class        UpperCAmelCase__						(		nn.Module			):
					a   :  HybridCLIPConfig
					a   :  jnp.dtype   =				jnp.floataa



					def 							UpperCAmelCase_			(     self  )  ->      Optional[Any]:
						__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      ,					)  ->      List[str]:
						__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        UpperCAmelCase__						(		UpperCamelCase__			):
					a   :  Dict   =				HybridCLIPConfig
					a   :  Union[str, Any]   =				FlaxHybridCLIPModule



					def __init__(     self      ,					UpperCamelCase      ,					UpperCamelCase = None      ,					UpperCamelCase = 0      ,					UpperCamelCase = jnp.floataa      ,					**UpperCamelCase      ,					)  ->      int:
						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  )  ->      FrozenDict:
						# 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      ,					)  ->      str:
						__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      ,					)  ->      List[str]:
						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  )  ->      List[str]:
						__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      ,					)  ->      FlaxPreTrainedModel:
						__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




'''simple docstring'''



from sklearn.metrics import accuracy_score

import datasets


lowerCAmelCase						:		Optional[Any]						      = '''
Accuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:
Accuracy = (TP + TN) / (TP + TN + FP + FN)
 Where:
TP: True positive
TN: True negative
FP: False positive
FN: False negative
'''


lowerCAmelCase						:		str						      = '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.

Examples:

    Example 1-A simple example
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])
        >>> print(results)
        {\'accuracy\': 0.5}

    Example 2-The same as Example 1, except with `normalize` set to `False`.
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)
        >>> print(results)
        {\'accuracy\': 3.0}

    Example 3-The same as Example 1, except with `sample_weight` set.
        >>> accuracy_metric = datasets.load_metric("accuracy")
        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])
        >>> print(results)
        {\'accuracy\': 0.8778625954198473}
'''


lowerCAmelCase						:		int						      = '''
@article{scikit-learn,
  title={Scikit-learn: Machine Learning in {P}ython},
  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
  journal={Journal of Machine Learning Research},
  volume={12},
  pages={2825--2830},
  year={2011}
}
'''






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION				,							_KWARGS_DESCRIPTION			)
class        UpperCAmelCase__						(		datasets.Metric			):



					def 							UpperCAmelCase_			(     self  )  ->      Optional[Any]:
						return datasets.MetricInfo(
						    description=_DESCRIPTION      ,					citation=_CITATION      ,					inputs_description=_KWARGS_DESCRIPTION      ,					features=datasets.Features(
						        {
						            "predictions": datasets.Sequence(datasets.Value("int32"  )  ),
						            "references": datasets.Sequence(datasets.Value("int32"  )  ),
						        }
						        if self.config_name == "multilabel"
						        else {
						            "predictions": datasets.Value("int32"  ),
						            "references": datasets.Value("int32"  ),
						        }  )      ,					reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"]      ,					)



					def 							UpperCAmelCase_			(     self      ,					UpperCamelCase      ,					UpperCamelCase      ,					UpperCamelCase=True      ,					UpperCamelCase=None  )  ->      List[str]:
						return {
						    "accuracy": float(
						        accuracy_score(UpperCamelCase      ,					UpperCamelCase      ,					normalize=UpperCamelCase      ,					sample_weight=UpperCamelCase  )  )
						}