




'''simple docstring'''


import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


UpperCamelCase     =				logging.getLogger(__name__)

require_version('''pytorch_lightning>=1.0.4''')

UpperCamelCase     =				{
    '''base''': AutoModel,
    '''sequence-classification''': AutoModelForSequenceClassification,
    '''question-answering''': AutoModelForQuestionAnswering,
    '''pretraining''': AutoModelForPreTraining,
    '''token-classification''': AutoModelForTokenClassification,
    '''language-modeling''': AutoModelWithLMHead,
    '''summarization''': AutoModelForSeqaSeqLM,
    '''translation''': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
UpperCamelCase     =				{
    '''linear''': get_linear_schedule_with_warmup,
    '''cosine''': get_cosine_schedule_with_warmup,
    '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,
    '''polynomial''': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
UpperCamelCase     =				sorted(arg_to_scheduler.keys())
UpperCamelCase     =				'''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}'''






class 	lowerCAmelCase_  (					pl.LightningModule       ):







  '''simple docstring'''

  def __init__(   self							:       int				,     SCREAMING_SNAKE_CASE_							:       argparse.Namespace				,     SCREAMING_SNAKE_CASE_							:       Any=None				,     SCREAMING_SNAKE_CASE_							:       int="base"				,     SCREAMING_SNAKE_CASE_							:       List[str]=None				,     SCREAMING_SNAKE_CASE_							:       Dict=None				,     SCREAMING_SNAKE_CASE_							:       Dict=None				,     **SCREAMING_SNAKE_CASE_							:       Optional[Any]				,     ) ->		Tuple:







       '''simple docstring'''



       super().__init__()
       # TODO: move to self.save_hyperparameters()
       # self.save_hyperparameters()
       # can also expand arguments into trainer signature for easier reading

       self.save_hyperparameters(SCREAMING_SNAKE_CASE_  )
       A:		int        =		0
       A:		str        =		Path(self.hparams.output_dir  )
       A:		str        =		self.hparams.cache_dir if self.hparams.cache_dir else None
       if config is None:
            A:		int        =		AutoConfig.from_pretrained(
                self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path				,     **({'''num_labels''': num_labels} if num_labels is not None else {})				,     cache_dir=SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_				,     )
       else:
            A:		PretrainedConfig        =		config

       A:		Optional[Any]        =		('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''')
       for p in extra_model_params:
            if getattr(self.hparams				,     SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  ):
                 assert hasattr(self.config				,     SCREAMING_SNAKE_CASE_  ), f"""model config doesn't have a `{p}` attribute"""
                 setattr(self.config				,     SCREAMING_SNAKE_CASE_				,     getattr(self.hparams				,     SCREAMING_SNAKE_CASE_  )  )

       if tokenizer is None:
            A:		Optional[int]        =		AutoTokenizer.from_pretrained(
                self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path				,     cache_dir=SCREAMING_SNAKE_CASE_				,     )
       else:
            A:		PreTrainedTokenizer        =		tokenizer
       A:		Union[str, Any]        =		MODEL_MODES[mode]
       if model is None:
            A:		str        =		self.model_type.from_pretrained(
                self.hparams.model_name_or_path				,     from_tf=bool('''.ckpt''' in self.hparams.model_name_or_path  )				,     config=self.config				,     cache_dir=SCREAMING_SNAKE_CASE_				,     )
       else:
            A:		List[str]        =		model



  def 				_snake_case    (   self							:       List[Any]				,     *SCREAMING_SNAKE_CASE_							:       Dict				,     **SCREAMING_SNAKE_CASE_							:       Tuple  ) ->		int:







       '''simple docstring'''



       A:		str        =		self.model_type.from_pretrained(*SCREAMING_SNAKE_CASE_				,     **SCREAMING_SNAKE_CASE_  )



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







       '''simple docstring'''



       A:		Tuple        =		arg_to_scheduler[self.hparams.lr_scheduler]
       A:		int        =		get_schedule_func(
           self.opt				,     num_warmup_steps=self.hparams.warmup_steps				,     num_training_steps=self.total_steps()  )
       A:		Union[str, Any]        =		{'''scheduler''': scheduler, '''interval''': '''step''', '''frequency''': 1}
       return scheduler



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







       '''simple docstring'''



       A:		List[str]        =		self.model
       A:		Optional[int]        =		['''bias''', '''LayerNorm.weight''']
       A:		Any        =		[
           {
               '''params''': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay  )],
               '''weight_decay''': self.hparams.weight_decay,
           },
           {
               '''params''': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay  )],
               '''weight_decay''': 0.0,
           },
       ]
       if self.hparams.adafactor:
            A:		Optional[int]        =		Adafactor(
                SCREAMING_SNAKE_CASE_				,     lr=self.hparams.learning_rate				,     scale_parameter=SCREAMING_SNAKE_CASE_				,     relative_step=SCREAMING_SNAKE_CASE_  )

       else:
            A:		int        =		AdamW(
                SCREAMING_SNAKE_CASE_				,     lr=self.hparams.learning_rate				,     eps=self.hparams.adam_epsilon  )
       A:		Tuple        =		optimizer

       A:		Tuple        =		self.get_lr_scheduler()

       return [optimizer], [scheduler]



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







       '''simple docstring'''



       return self.validation_step(SCREAMING_SNAKE_CASE_				,     SCREAMING_SNAKE_CASE_  )



  def 				_snake_case    (   self							:       Any				,     SCREAMING_SNAKE_CASE_							:       str  ) ->		int:







       '''simple docstring'''



       return self.validation_end(SCREAMING_SNAKE_CASE_  )



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







       '''simple docstring'''



       A:		Optional[Any]        =		max(1				,     self.hparams.gpus  )  # TODO: consider num_tpu_cores
       A:		Optional[Any]        =		self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
       return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs



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







       '''simple docstring'''



       if mode == "test":
            A:		List[Any]        =		len(self.test_dataloader().dataset  )
       else:
            A:		List[Any]        =		self.get_dataloader('''train'''				,     self.hparams.train_batch_size				,     shuffle=SCREAMING_SNAKE_CASE_  )
            A:		Any        =		len(self.train_dataloader().dataset  )



  def 				_snake_case    (   self							:       Union[str, Any]				,     SCREAMING_SNAKE_CASE_							:       str				,     SCREAMING_SNAKE_CASE_							:       int				,     SCREAMING_SNAKE_CASE_							:       bool = False  ) ->		str:







       '''simple docstring'''



       raise NotImplementedError('''You must implement this for your task'''  )



  def 				_snake_case    (   self							:       str  ) ->		str:







       '''simple docstring'''



       return self.train_loader



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







       '''simple docstring'''



       return self.get_dataloader('''dev'''				,     self.hparams.eval_batch_size				,     shuffle=SCREAMING_SNAKE_CASE_  )



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







       '''simple docstring'''



       return self.get_dataloader('''test'''				,     self.hparams.eval_batch_size				,     shuffle=SCREAMING_SNAKE_CASE_  )



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







       '''simple docstring'''



       return os.path.join(
           self.hparams.data_dir				,     '''cached_{}_{}_{}'''.format(
               SCREAMING_SNAKE_CASE_				,     list(filter(SCREAMING_SNAKE_CASE_				,     self.hparams.model_name_or_path.split('''/'''  )  )  ).pop()				,     str(self.hparams.max_seq_length  )				,     )				,     )



  @pl.utilities.rank_zero_only
  def 				_snake_case    (   self							:       str				,     SCREAMING_SNAKE_CASE_							:       Dict[str, Any]  ) ->		None:







       '''simple docstring'''



       A:		Optional[Any]        =		self.output_dir.joinpath('''best_tfmr'''  )
       A:		Dict        =		self.step_count
       self.model.save_pretrained(SCREAMING_SNAKE_CASE_  )
       self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_  )




  @staticmethod
  def 				_snake_case    (   SCREAMING_SNAKE_CASE_							:       Tuple				,     SCREAMING_SNAKE_CASE_							:       Any  ) ->		List[str]:







       '''simple docstring'''



       parser.add_argument(
           '''--model_name_or_path'''				,     default=SCREAMING_SNAKE_CASE_				,     type=SCREAMING_SNAKE_CASE_				,     required=SCREAMING_SNAKE_CASE_				,     help='''Path to pretrained model or model identifier from huggingface.co/models'''				,     )
       parser.add_argument(
           '''--config_name'''				,     default=''''''				,     type=SCREAMING_SNAKE_CASE_				,     help='''Pretrained config name or path if not the same as model_name'''  )
       parser.add_argument(
           '''--tokenizer_name'''				,     default=SCREAMING_SNAKE_CASE_				,     type=SCREAMING_SNAKE_CASE_				,     help='''Pretrained tokenizer name or path if not the same as model_name'''				,     )
       parser.add_argument(
           '''--cache_dir'''				,     default=''''''				,     type=SCREAMING_SNAKE_CASE_				,     help='''Where do you want to store the pre-trained models downloaded from huggingface.co'''				,     )
       parser.add_argument(
           '''--encoder_layerdrop'''				,     type=SCREAMING_SNAKE_CASE_				,     help='''Encoder layer dropout probability (Optional). Goes into model.config'''				,     )
       parser.add_argument(
           '''--decoder_layerdrop'''				,     type=SCREAMING_SNAKE_CASE_				,     help='''Decoder layer dropout probability (Optional). Goes into model.config'''				,     )
       parser.add_argument(
           '''--dropout'''				,     type=SCREAMING_SNAKE_CASE_				,     help='''Dropout probability (Optional). Goes into model.config'''				,     )
       parser.add_argument(
           '''--attention_dropout'''				,     type=SCREAMING_SNAKE_CASE_				,     help='''Attention dropout probability (Optional). Goes into model.config'''				,     )
       parser.add_argument('''--learning_rate'''				,     default=5E-5				,     type=SCREAMING_SNAKE_CASE_				,     help='''The initial learning rate for Adam.'''  )
       parser.add_argument(
           '''--lr_scheduler'''				,     default='''linear'''				,     choices=SCREAMING_SNAKE_CASE_				,     metavar=SCREAMING_SNAKE_CASE_				,     type=SCREAMING_SNAKE_CASE_				,     help='''Learning rate scheduler'''				,     )
       parser.add_argument('''--weight_decay'''				,     default=0.0				,     type=SCREAMING_SNAKE_CASE_				,     help='''Weight decay if we apply some.'''  )
       parser.add_argument('''--adam_epsilon'''				,     default=1E-8				,     type=SCREAMING_SNAKE_CASE_				,     help='''Epsilon for Adam optimizer.'''  )
       parser.add_argument('''--warmup_steps'''				,     default=0				,     type=SCREAMING_SNAKE_CASE_				,     help='''Linear warmup over warmup_steps.'''  )
       parser.add_argument('''--num_workers'''				,     default=4				,     type=SCREAMING_SNAKE_CASE_				,     help='''kwarg passed to DataLoader'''  )
       parser.add_argument('''--num_train_epochs'''				,     dest='''max_epochs'''				,     default=3				,     type=SCREAMING_SNAKE_CASE_  )
       parser.add_argument('''--train_batch_size'''				,     default=32				,     type=SCREAMING_SNAKE_CASE_  )
       parser.add_argument('''--eval_batch_size'''				,     default=32				,     type=SCREAMING_SNAKE_CASE_  )
       parser.add_argument('''--adafactor'''				,     action='''store_true'''  )






class 	lowerCAmelCase_  (					pl.Callback       ):







  '''simple docstring'''

  def 				_snake_case    (   self							:       Optional[int]				,     SCREAMING_SNAKE_CASE_							:       Optional[int]				,     SCREAMING_SNAKE_CASE_							:       Optional[Any]  ) ->		List[Any]:







       '''simple docstring'''



       A:		List[str]        =		trainer.lr_schedulers[0]['''scheduler''']
       A:		Dict        =		{f"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr()  )}
       pl_module.logger.log_metrics(SCREAMING_SNAKE_CASE_  )



  def 				_snake_case    (   self							:       Optional[int]				,     SCREAMING_SNAKE_CASE_							:       pl.Trainer				,     SCREAMING_SNAKE_CASE_							:       pl.LightningModule  ) ->		int:







       '''simple docstring'''



       rank_zero_info('''***** Validation results *****'''  )
       A:		int        =		trainer.callback_metrics
       # Log results
       for key in sorted(SCREAMING_SNAKE_CASE_  ):
            if key not in ["log", "progress_bar"]:
                 rank_zero_info('''{} = {}\n'''.format(SCREAMING_SNAKE_CASE_				,     str(metrics[key]  )  )  )




  def 				_snake_case    (   self							:       List[Any]				,     SCREAMING_SNAKE_CASE_							:       pl.Trainer				,     SCREAMING_SNAKE_CASE_							:       pl.LightningModule  ) ->		Optional[int]:







       '''simple docstring'''



       rank_zero_info('''***** Test results *****'''  )
       A:		int        =		trainer.callback_metrics
       # Log and save results to file
       A:		Dict        =		os.path.join(pl_module.hparams.output_dir				,     '''test_results.txt'''  )
       with open(SCREAMING_SNAKE_CASE_				,     '''w'''  ) as writer:
            for key in sorted(SCREAMING_SNAKE_CASE_  ):
                 if key not in ["log", "progress_bar"]:
                      rank_zero_info('''{} = {}\n'''.format(SCREAMING_SNAKE_CASE_				,     str(metrics[key]  )  )  )
                      writer.write('''{} = {}\n'''.format(SCREAMING_SNAKE_CASE_				,     str(metrics[key]  )  )  )






def 				SCREAMING_SNAKE_CASE(      __lowercase		,							__lowercase  ) ->   None:
     #  To allow all pl args uncomment the following line
     #  parser = pl.Trainer.add_argparse_args(parser)
     parser.add_argument(
         '''--output_dir'''		,							default=__lowercase		,							type=__lowercase		,							required=__lowercase		,							help='''The output directory where the model predictions and checkpoints will be written.'''		,							)
     parser.add_argument(
         '''--fp16'''		,							action='''store_true'''		,							help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'''		,							)

     parser.add_argument(
         '''--fp16_opt_level'''		,							type=__lowercase		,							default='''O2'''		,							help=(
             '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'''
             '''See details at https://nvidia.github.io/apex/amp.html'''
         )		,							)
     parser.add_argument('''--n_tpu_cores'''		,							dest='''tpu_cores'''		,							type=__lowercase  )
     parser.add_argument('''--max_grad_norm'''		,							dest='''gradient_clip_val'''		,							default=1.0		,							type=__lowercase		,							help='''Max gradient norm'''  )
     parser.add_argument('''--do_train'''		,							action='''store_true'''		,							help='''Whether to run training.'''  )
     parser.add_argument('''--do_predict'''		,							action='''store_true'''		,							help='''Whether to run predictions on the test set.'''  )
     parser.add_argument(
         '''--gradient_accumulation_steps'''		,							dest='''accumulate_grad_batches'''		,							type=__lowercase		,							default=1		,							help='''Number of updates steps to accumulate before performing a backward/update pass.'''		,							)
     parser.add_argument('''--seed'''		,							type=__lowercase		,							default=4_2		,							help='''random seed for initialization'''  )
     parser.add_argument(
         '''--data_dir'''		,							default=__lowercase		,							type=__lowercase		,							required=__lowercase		,							help='''The input data dir. Should contain the training files for the CoNLL-2003 NER task.'''		,							)


def 				SCREAMING_SNAKE_CASE(      __lowercase		,							__lowercase		,							__lowercase=None		,							__lowercase=True		,							__lowercase=[]		,							__lowercase=None		,							__lowercase=None		,							**__lowercase		,							) ->   List[Any]:
     pl.seed_everything(args.seed  )

     # init model
     A:		Optional[int]        =		Path(model.hparams.output_dir  )
     odir.mkdir(exist_ok=__lowercase  )

     # add custom checkpoints
     if checkpoint_callback is None:
          A:		Tuple        =		pl.callbacks.ModelCheckpoint(
              filepath=args.output_dir		,							prefix='''checkpoint'''		,							monitor='''val_loss'''		,							mode='''min'''		,							save_top_k=1  )
     if early_stopping_callback:
          extra_callbacks.append(__lowercase  )
     if logging_callback is None:
          A:		Any        =		LoggingCallback()

     A:		Dict        =		{}

     # TODO: remove with PyTorch 1.6 since pl uses native amp
     if args.fpaa:
          A:		List[str]        =		1_6
          A:		Tuple        =		args.fpaa_opt_level

     if args.gpus > 1:
          A:		Optional[int]        =		'''ddp'''

     A:		Any        =		args.accumulate_grad_batches
     A:		Optional[Any]        =		extra_train_kwargs.get('''accelerator'''		,							__lowercase  )
     A:		List[str]        =		extra_train_kwargs.get('''profiler'''		,							__lowercase  )

     A:		Optional[int]        =		pl.Trainer.from_argparse_args(
         __lowercase		,							weights_summary=__lowercase		,							callbacks=[logging_callback] + extra_callbacks		,							logger=__lowercase		,							checkpoint_callback=__lowercase		,							**__lowercase		,							)

     if args.do_train:
          trainer.fit(__lowercase  )

     return trainer












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






