






import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
 from transformers import (
     FlaxBertModel,
     FlaxCLIPVisionModel,
     FlaxVisionTextDualEncoderModel,
     FlaxViTModel,
     VisionTextDualEncoderConfig,
     VisionTextDualEncoderProcessor,
 )
 from transformers.modeling_flax_pytorch_utils import (
     convert_pytorch_state_dict_to_flax,
     load_flax_weights_in_pytorch_model,
 )


if is_torch_available():
 import torch

 from transformers import VisionTextDualEncoderModel

if is_vision_available():
 from PIL import Image






def     _snake_case    (__lowercase):
   if isinstance(__lowercase    ,      collections.abc.Iterable):
      return x
   return (x, x)


@require_flax
class 						_a       :






  """simple docstring"""





  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[int]:
     pass




  def    _UpperCAmelCase     (     self )			-> int:
     pass




  def    _UpperCAmelCase     (     self )			-> Any:
     pass




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[int]:
     UpperCamelCase_									=     np.abs((a - b) ).max()
     self.assertLessEqual(_UpperCAmelCase		,		_UpperCAmelCase		,		f"""Difference between torch and flax is {diff} (>= {tol}).""" )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=None		,		**_UpperCAmelCase )			-> List[str]:
     UpperCamelCase_									=     VisionTextDualEncoderConfig.from_vision_text_configs(_UpperCAmelCase		,		_UpperCAmelCase )

     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel(_UpperCAmelCase )

     UpperCamelCase_									=     model(input_ids=_UpperCAmelCase		,		pixel_values=_UpperCAmelCase		,		attention_mask=_UpperCAmelCase )

     self.assertEqual(output['text_embeds'].shape		,		(input_ids.shape[0], config.projection_dim) )
     self.assertEqual(output['image_embeds'].shape		,		(pixel_values.shape[0], config.projection_dim) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=None		,		**_UpperCAmelCase )			-> Optional[int]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.get_vision_text_model(_UpperCAmelCase		,		_UpperCAmelCase )
     UpperCamelCase_									=     {'vision_model': vision_model, 'text_model': text_model}
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_UpperCAmelCase )

     UpperCamelCase_									=     model(input_ids=_UpperCAmelCase		,		pixel_values=_UpperCAmelCase		,		attention_mask=_UpperCAmelCase )

     self.assertEqual(output['text_embeds'].shape		,		(input_ids.shape[0], model.config.projection_dim) )
     self.assertEqual(output['image_embeds'].shape		,		(pixel_values.shape[0], model.config.projection_dim) )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=None		,		**_UpperCAmelCase )			-> Optional[int]:
     UpperCamelCase_		,      UpperCamelCase_									=     self.get_vision_text_model(_UpperCAmelCase		,		_UpperCAmelCase )
     UpperCamelCase_									=     {'vision_model': vision_model, 'text_model': text_model}
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_UpperCAmelCase )

     UpperCamelCase_									=     model(input_ids=_UpperCAmelCase		,		pixel_values=_UpperCAmelCase		,		attention_mask=_UpperCAmelCase )
     UpperCamelCase_									=     output[0]

     with tempfile.TemporaryDirectory() as tmpdirname:
        model.save_pretrained(_UpperCAmelCase )
        UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_pretrained(_UpperCAmelCase )

        UpperCamelCase_									=     model(input_ids=_UpperCAmelCase		,		pixel_values=_UpperCAmelCase		,		attention_mask=_UpperCAmelCase )
        UpperCamelCase_									=     after_output[0]
        UpperCamelCase_									=     np.amax(np.abs(out_a - out_a ) )
        self.assertLessEqual(_UpperCAmelCase		,		1e-3 )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase=None		,		**_UpperCAmelCase )			-> str:
     UpperCamelCase_		,      UpperCamelCase_									=     self.get_vision_text_model(_UpperCAmelCase		,		_UpperCAmelCase )
     UpperCamelCase_									=     {'vision_model': vision_model, 'text_model': text_model}
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_UpperCAmelCase )

     UpperCamelCase_									=     model(
         input_ids=_UpperCAmelCase		,		pixel_values=_UpperCAmelCase		,		attention_mask=_UpperCAmelCase		,		output_attentions=_UpperCAmelCase )

     UpperCamelCase_									=     output.vision_model_output.attentions
     self.assertEqual(len(_UpperCAmelCase )		,		vision_config.num_hidden_layers )

     # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
     UpperCamelCase_									=     to_atuple(vision_model.config.image_size )
     UpperCamelCase_									=     to_atuple(vision_model.config.patch_size )
     UpperCamelCase_									=     (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
     UpperCamelCase_									=     num_patches + 1
     self.assertEqual(vision_attentions[0].shape[-3:]		,		(vision_config.num_attention_heads, seq_len, seq_len) )

     UpperCamelCase_									=     output.text_model_output.attentions
     self.assertEqual(len(_UpperCAmelCase )		,		text_config.num_hidden_layers )

     self.assertEqual(
         text_attentions[0].shape[-3:]		,		(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])		,		)




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Optional[Any]:
     pt_model.to(_UpperCAmelCase )
     pt_model.eval()

     # prepare inputs
     UpperCamelCase_									=     inputs_dict
     UpperCamelCase_									=     {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()}

     with torch.no_grad():
        UpperCamelCase_									=     pt_model(**_UpperCAmelCase ).to_tuple()

     UpperCamelCase_									=     fx_model(**_UpperCAmelCase ).to_tuple()
     self.assertEqual(len(_UpperCAmelCase )		,		len(_UpperCAmelCase )		,		'Output lengths differ between Flax and PyTorch' )
     for fx_output, pt_output in zip(fx_outputs[:4]		,		pt_outputs[:4] ):
        self.assert_almost_equals(_UpperCAmelCase		,		pt_output.numpy()		,		4e-2 )

     # PT -> Flax
     with tempfile.TemporaryDirectory() as tmpdirname:
        pt_model.save_pretrained(_UpperCAmelCase )
        UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_pretrained(_UpperCAmelCase		,		from_pt=_UpperCAmelCase )

     UpperCamelCase_									=     fx_model_loaded(**_UpperCAmelCase ).to_tuple()
     self.assertEqual(len(_UpperCAmelCase )		,		len(_UpperCAmelCase )		,		'Output lengths differ between Flax and PyTorch' )
     for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]		,		pt_outputs[:4] ):
        self.assert_almost_equals(_UpperCAmelCase		,		pt_output.numpy()		,		4e-2 )

     # Flax -> PT
     with tempfile.TemporaryDirectory() as tmpdirname:
        fx_model.save_pretrained(_UpperCAmelCase )
        UpperCamelCase_									=     VisionTextDualEncoderModel.from_pretrained(_UpperCAmelCase		,		from_flax=_UpperCAmelCase )

     pt_model_loaded.to(_UpperCAmelCase )
     pt_model_loaded.eval()

     with torch.no_grad():
        UpperCamelCase_									=     pt_model_loaded(**_UpperCAmelCase ).to_tuple()

     self.assertEqual(len(_UpperCAmelCase )		,		len(_UpperCAmelCase )		,		'Output lengths differ between Flax and PyTorch' )
     for fx_output, pt_output_loaded in zip(fx_outputs[:4]		,		pt_outputs_loaded[:4] ):
        self.assert_almost_equals(_UpperCAmelCase		,		pt_output_loaded.numpy()		,		4e-2 )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> Tuple:
     UpperCamelCase_									=     VisionTextDualEncoderConfig.from_vision_text_configs(_UpperCAmelCase		,		_UpperCAmelCase )

     UpperCamelCase_									=     VisionTextDualEncoderModel(_UpperCAmelCase )
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel(_UpperCAmelCase )

     UpperCamelCase_									=     convert_pytorch_state_dict_to_flax(pt_model.state_dict()		,		_UpperCAmelCase )
     UpperCamelCase_									=     fx_state

     self.check_pt_flax_equivalence(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> List[Any]:
     UpperCamelCase_									=     VisionTextDualEncoderConfig.from_vision_text_configs(_UpperCAmelCase		,		_UpperCAmelCase )

     UpperCamelCase_									=     VisionTextDualEncoderModel(_UpperCAmelCase )
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel(_UpperCAmelCase )

     UpperCamelCase_									=     load_flax_weights_in_pytorch_model(_UpperCAmelCase		,		fx_model.params )

     self.check_pt_flax_equivalence(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     self.check_model_from_pretrained_configs(**_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Dict:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_from_pretrained(**_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     self.check_save_load(**_UpperCAmelCase )




  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     self.check_vision_text_output_attention(**_UpperCAmelCase )




  @is_pt_flax_cross_test
  def    _UpperCAmelCase     (     self )			-> Any:
     UpperCamelCase_									=     self.prepare_config_and_inputs()
     UpperCamelCase_									=     config_inputs_dict.pop('vision_config' )
     UpperCamelCase_									=     config_inputs_dict.pop('text_config' )

     UpperCamelCase_									=     config_inputs_dict

     self.check_equivalence_pt_to_flax(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )
     self.check_equivalence_flax_to_pt(_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase )




  @slow
  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_		,      UpperCamelCase_									=     self.get_pretrained_model_and_inputs()

     UpperCamelCase_									=     model_a(**_UpperCAmelCase )
     UpperCamelCase_									=     outputs[0]

     with tempfile.TemporaryDirectory() as tmp_dirname:
        model_a.save_pretrained(_UpperCAmelCase )
        UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_pretrained(_UpperCAmelCase )

        UpperCamelCase_									=     model_a(**_UpperCAmelCase )
        UpperCamelCase_									=     after_outputs[0]
        UpperCamelCase_									=     np.amax(np.abs(out_a - out_a ) )
        self.assertLessEqual(_UpperCAmelCase		,		1e-5 )




@require_flax
class 						_a       (  UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  def    _UpperCAmelCase     (     self )			-> int:
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         'hf-internal-testing/tiny-random-vit'		,		'hf-internal-testing/tiny-bert'		,		vision_from_pt=_UpperCAmelCase		,		text_from_pt=_UpperCAmelCase		,		)
     UpperCamelCase_									=     13
     UpperCamelCase_									=     floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ] )
     UpperCamelCase_									=     ids_tensor([batch_size, 4]		,		model.config.text_config.vocab_size )
     UpperCamelCase_									=     random_attention_mask([batch_size, 4] )
     UpperCamelCase_									=     {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> int:
     UpperCamelCase_									=     FlaxViTModel(_UpperCAmelCase )
     UpperCamelCase_									=     FlaxBertModel(_UpperCAmelCase )
     return vision_model, text_model




  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     FlaxViTModelTester(self )
     UpperCamelCase_									=     FlaxBertModelTester(self )
     UpperCamelCase_									=     vit_model_tester.prepare_config_and_inputs()
     UpperCamelCase_									=     bert_model_tester.prepare_config_and_inputs()

     UpperCamelCase_		,      UpperCamelCase_									=     vision_config_and_inputs

     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     text_config_and_inputs

     # make sure that cross attention layers are added
     return {
         "text_config": text_config,
         "vision_config": vision_config,
         "pixel_values": pixel_values,
         "attention_mask": attention_mask,
         "input_ids": input_ids,
         "token_type_ids": token_type_ids,
     }




@require_torch
class 						_a       (  UpperCAmelCase__						,       unittest.TestCase    ):






  """simple docstring"""





  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         'hf-internal-testing/tiny-random-clip'		,		'hf-internal-testing/tiny-bert'		,		vision_from_pt=_UpperCAmelCase		,		text_from_pt=_UpperCAmelCase		,		)
     UpperCamelCase_									=     13
     UpperCamelCase_									=     floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ] )
     UpperCamelCase_									=     ids_tensor([batch_size, 4]		,		model.config.text_config.vocab_size )
     UpperCamelCase_									=     random_attention_mask([batch_size, 4] )
     UpperCamelCase_									=     {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs




  def    _UpperCAmelCase     (     self		,		_UpperCAmelCase		,		_UpperCAmelCase )			-> int:
     UpperCamelCase_									=     FlaxCLIPVisionModel(_UpperCAmelCase )
     UpperCamelCase_									=     FlaxBertModel(_UpperCAmelCase )
     return vision_model, text_model




  def    _UpperCAmelCase     (     self )			-> str:
     UpperCamelCase_									=     FlaxCLIPVisionModelTester(self )
     UpperCamelCase_									=     FlaxBertModelTester(self )
     UpperCamelCase_									=     clip_model_tester.prepare_config_and_inputs()
     UpperCamelCase_									=     bert_model_tester.prepare_config_and_inputs()

     UpperCamelCase_		,      UpperCamelCase_									=     vision_config_and_inputs

     UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_		,      UpperCamelCase_									=     text_config_and_inputs

     # make sure that cross attention layers are added
     return {
         "text_config": text_config,
         "vision_config": vision_config,
         "pixel_values": pixel_values,
         "attention_mask": attention_mask,
         "input_ids": input_ids,
         "token_type_ids": token_type_ids,
     }




@require_flax
@require_vision
class 						_a       (  unittest.TestCase    ):






  """simple docstring"""





  @slow
  def    _UpperCAmelCase     (     self )			-> Union[str, Any]:
     UpperCamelCase_									=     FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'		,		logit_scale_init_value=1.0 )
     UpperCamelCase_									=     VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' )

     UpperCamelCase_									=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
     UpperCamelCase_									=     processor(
         text=['una foto di un gatto', 'una foto di un cane']		,		images=_UpperCAmelCase		,		padding=_UpperCAmelCase		,		return_tensors='np' )

     UpperCamelCase_									=     model(**_UpperCAmelCase )

     # verify the logits
     self.assertEqual(outputs.logits_per_image.shape		,		(inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) )
     self.assertEqual(
         outputs.logits_per_text.shape		,		(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])		,		)

     UpperCamelCase_									=     np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] )

     self.assertTrue(np.allclose(outputs.logits_per_image		,		_UpperCAmelCase		,		atol=1e-3 ) )













import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


snake_case__      :	Any       	=      logging.get_logger(__name__)


@dataclass
class 						_a       :






  """simple docstring"""





  A_						=   field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys()    )}    )
  A_						=   field(
      metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}    )
  A_						=   field(
      default=128						,       metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }						,       )
  A_						=   field(
      default=UpperCAmelCase__						,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}    )




  def    _UpperCAmelCase     (     self )			-> Optional[Any]:
     UpperCamelCase_									=     self.task_name.lower()




class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   """train"""
  A_						=   """dev"""
  A_						=   """test"""




class 						_a       (  UpperCAmelCase__    ):






  """simple docstring"""





  A_						=   42
  A_						=   42
  A_						=   42




  def __init__(     self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase = None		,		_UpperCAmelCase = Split.train		,		_UpperCAmelCase = None		,		)			-> Tuple:
     warnings.warn(
         'This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets '
         'library. You can have a look at this example script for pointers: '
         'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'		,		_UpperCAmelCase		,		)
     UpperCamelCase_									=     args
     UpperCamelCase_									=     glue_processors[args.task_name]()
     UpperCamelCase_									=     glue_output_modes[args.task_name]
     if isinstance(_UpperCAmelCase		,		_UpperCAmelCase ):
        try:
           UpperCamelCase_									=     Split[mode]
        except KeyError:
           raise KeyError('mode is not a valid split name' )
        # Load data features from cache or dataset file
     UpperCamelCase_									=     os.path.join(
         cache_dir if cache_dir is not None else args.data_dir		,		f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}"""		,		)
     UpperCamelCase_									=     self.processor.get_labels()
     if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
         "RobertaTokenizer",
         "RobertaTokenizerFast",
         "XLMRobertaTokenizer",
         "BartTokenizer",
         "BartTokenizerFast",
     ):
        # HACK(label indices are swapped in RoBERTa pretrained model)
        UpperCamelCase_		,      UpperCamelCase_									=     label_list[2], label_list[1]
     UpperCamelCase_									=     label_list

     # Make sure only the first process in distributed training processes the dataset,
     # and the others will use the cache.
     UpperCamelCase_									=     cached_features_file + '.lock'
     with FileLock(_UpperCAmelCase ):
        if os.path.exists(_UpperCAmelCase ) and not args.overwrite_cache:
           UpperCamelCase_									=     time.time()
           UpperCamelCase_									=     torch.load(_UpperCAmelCase )
           logger.info(
               f"""Loading features from cached file {cached_features_file} [took %.3f s]"""		,		time.time() - start )
        else:
           logger.info(f"""Creating features from dataset file at {args.data_dir}""" )

           if mode == Split.dev:
              UpperCamelCase_									=     self.processor.get_dev_examples(args.data_dir )
           elif mode == Split.test:
              UpperCamelCase_									=     self.processor.get_test_examples(args.data_dir )
           else:
              UpperCamelCase_									=     self.processor.get_train_examples(args.data_dir )
           if limit_length is not None:
              UpperCamelCase_									=     examples[:limit_length]
           UpperCamelCase_									=     glue_convert_examples_to_features(
               _UpperCAmelCase		,		_UpperCAmelCase		,		max_length=args.max_seq_length		,		label_list=_UpperCAmelCase		,		output_mode=self.output_mode		,		)
           UpperCamelCase_									=     time.time()
           torch.save(self.features		,		_UpperCAmelCase )
           # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
           logger.info(
               f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" )




  def __len__(     self )			-> List[str]:
     return len(self.features )




  def __getitem__(     self		,		_UpperCAmelCase )			-> InputFeatures:
     return self.features[i]




  def    _UpperCAmelCase     (     self )			-> Tuple:
     return self.label_list





