





import os
import posixpath
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union

import numpy as np
import pyarrow as pa

import datasets
from datasets.arrow_writer import ArrowWriter, ParquetWriter
from datasets.config import MAX_SHARD_SIZE
from datasets.filesystems import (
    is_remote_filesystem,
    rename,
)
from datasets.iterable_dataset import _BaseExamplesIterable
from datasets.utils.py_utils import convert_file_size_to_int


lowercase				:	Optional[Any]      						=  datasets.utils.logging.get_logger(__name__)

if TYPE_CHECKING:
    import pyspark





@dataclass
class 			A__   (							datasets.BuilderConfig     ):




   """simple docstring"""



   __A       :    Optional[datasets.Features]	  =  None



def A_     (		A__		,				A__		,				)  ->		List[Any]:
       import pyspark

       def generate_fn():
              a__						:     List[Any]			=    df.select('*'		,				pyspark.sql.functions.spark_partition_id().alias('part_id'    )    )
              for partition_id in partition_order:
                     a__						:     List[str]			=    df_with_partition_id.select('*'    ).where(F'part_id = {partition_id}'    ).drop('part_id'    )
                     a__						:     Dict			=    partition_df.collect()
                     a__						:     Tuple			=    0
                     for row in rows:
                            yield F'{partition_id}_{row_id}', row.asDict()
                            row_id += 1

       return generate_fn





class 			A__   (							_BaseExamplesIterable     ):




   """simple docstring"""



   def __init__( self ,  lowercase ,  lowercase=None ,  )      ->						int:







          '''simple docstring'''

          a__						:     Optional[int]			=    df
          a__						:     Optional[Any]			=    partition_order or range(self.df.rdd.getNumPartitions())
          a__						:     Any			=    _generate_iterable_examples(self.df ,  self.partition_order)

   def __iter__( self)      ->						Optional[int]:







          '''simple docstring'''

          yield from self.generate_examples_fn()

   def 							__lowercase		( self ,  lowercase)      ->						"SparkExamplesIterable":







          '''simple docstring'''

          a__						:     str			=    list(range(self.df.rdd.getNumPartitions()))
          generator.shuffle(lowercase)
          return SparkExamplesIterable(self.df ,  partition_order=lowercase)

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						"SparkExamplesIterable":







          '''simple docstring'''

          a__						:     List[Any]			=    self.split_shard_indices_by_worker(lowercase ,  lowercase)
          return SparkExamplesIterable(self.df ,  partition_order=lowercase)

   @property
   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          return len(self.partition_order)





class 			A__   (							datasets.DatasetBuilder     ):




   """simple docstring"""



   __A       :    str	  =  SparkConfig

   def __init__( self ,  lowercase ,  lowercase = None ,  lowercase = None ,  **lowercase ,  )      ->						List[Any]:







          '''simple docstring'''

          import pyspark

          a__						:     Tuple			=    pyspark.sql.SparkSession.builder.getOrCreate()
          a__						:     int			=    df
          a__						:     Tuple			=    working_dir

          super().__init__(
              cache_dir=lowercase ,  config_name=str(self.df.semanticHash()) ,  **lowercase ,  )

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







          '''simple docstring'''

          def create_cache_and_write_probe(lowercase):
                 # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories
                 # already exist.
                 os.makedirs(self._cache_dir ,  exist_ok=lowercase)
                 a__						:     List[str]			=    os.path.join(self._cache_dir ,  'fs_test' + uuid.uuida().hex)
                 # Opening the file in append mode will create a new file unless it already exists, in which case it will not
                 # change the file contents.
                 open(lowercase ,  'a')
                 return [probe_file]

          if self._spark.conf.get('spark.master' ,  '').startswith('local'):
                 return

          # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS
          # accessible to the driver.
          # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error.
          if self._cache_dir:
                 a__						:     Union[str, Any]			=    (
                     self._spark.sparkContext.parallelize(range(1) ,  1).mapPartitions(lowercase).collect()
                 )
                 if os.path.isfile(probe[0]):
                        return

          raise ValueError(
              'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir')

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          return datasets.DatasetInfo(features=self.config.features)

   def 							__lowercase		( self ,  lowercase)      ->						str:







          '''simple docstring'''

          return [datasets.SplitGenerator(name=datasets.Split.TRAIN)]

   def 							__lowercase		( self ,  lowercase)      ->						Union[str, Any]:







          '''simple docstring'''

          import pyspark

          def get_arrow_batch_size(lowercase):
                 for batch in it:
                        yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]})

          a__						:     int			=    self.df.count()
          a__						:     Dict			=    df_num_rows if df_num_rows <= 100 else 100
          # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample.
          a__						:     List[Any]			=    (
              self.df.limit(lowercase)
              .repartition(1)
              .mapInArrow(lowercase ,  'batch_bytes: long')
              .agg(pyspark.sql.functions.sum('batch_bytes').alias('sample_bytes'))
              .collect()[0]
              .sample_bytes
              / sample_num_rows
          )
          a__						:     List[str]			=    approx_bytes_per_row * df_num_rows
          if approx_total_size > max_shard_size:
                 # Make sure there is at least one row per partition.
                 a__						:     Tuple			=    min(lowercase ,  int(approx_total_size / max_shard_size))
                 a__						:     Optional[int]			=    self.df.repartition(lowercase)

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  )      ->						Iterable[Tuple[int, bool, Union[int, tuple]]]:







          '''simple docstring'''

          import pyspark

          a__						:     List[Any]			=    ParquetWriter if file_format == 'parquet' else ArrowWriter
          a__						:     Any			=    os.path.join(self._working_dir ,  os.path.basename(lowercase)) if self._working_dir else fpath
          a__						:     int			=    file_format == 'parquet'

          # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to
          # pickling the SparkContext.
          a__						:     Dict			=    self.config.features
          a__						:     Tuple			=    self._writer_batch_size
          a__						:     str			=    self._fs.storage_options

          def write_arrow(lowercase):
                 # Within the same SparkContext, no two task attempts will share the same attempt ID.
                 a__						:     Optional[Any]			=    pyspark.TaskContext().taskAttemptId()
                 a__						:     Optional[Any]			=    next(lowercase ,  lowercase)
                 if first_batch is None:
                        # Some partitions might not receive any data.
                        return pa.RecordBatch.from_arrays(
                            [[task_id], [0], [0]] ,  names=['task_id', 'num_examples', 'num_bytes'] ,  )
                 a__						:     Optional[int]			=    0
                 a__						:     int			=    writer_class(
                     features=lowercase ,  path=working_fpath.replace('SSSSS' ,  F'{shard_id:05d}').replace('TTTTT' ,  F'{task_id:05d}') ,  writer_batch_size=lowercase ,  storage_options=lowercase ,  embed_local_files=lowercase ,  )
                 a__						:     Dict			=    pa.Table.from_batches([first_batch])
                 writer.write_table(lowercase)
                 for batch in it:
                        if max_shard_size is not None and writer._num_bytes >= max_shard_size:
                               a__			,							a__						:     str			=    writer.finalize()
                               writer.close()
                               yield pa.RecordBatch.from_arrays(
                                   [[task_id], [num_examples], [num_bytes]] ,  names=['task_id', 'num_examples', 'num_bytes'] ,  )
                               shard_id += 1
                               a__						:     Optional[int]			=    writer_class(
                                   features=writer._features ,  path=working_fpath.replace('SSSSS' ,  F'{shard_id:05d}').replace('TTTTT' ,  F'{task_id:05d}') ,  writer_batch_size=lowercase ,  storage_options=lowercase ,  embed_local_files=lowercase ,  )
                        a__						:     Optional[int]			=    pa.Table.from_batches([batch])
                        writer.write_table(lowercase)

                 if writer._num_bytes > 0:
                        a__			,							a__						:     Dict			=    writer.finalize()
                        writer.close()
                        yield pa.RecordBatch.from_arrays(
                            [[task_id], [num_examples], [num_bytes]] ,  names=['task_id', 'num_examples', 'num_bytes'] ,  )

                 if working_fpath != fpath:
                        for file in os.listdir(os.path.dirname(lowercase)):
                               a__						:     Dict			=    os.path.join(os.path.dirname(lowercase) ,  os.path.basename(lowercase))
                               shutil.move(lowercase ,  lowercase)

          a__						:     Optional[int]			=    (
              self.df.mapInArrow(lowercase ,  'task_id: long, num_examples: long, num_bytes: long')
              .groupBy('task_id')
              .agg(
                  pyspark.sql.functions.sum('num_examples').alias('total_num_examples') ,  pyspark.sql.functions.sum('num_bytes').alias('total_num_bytes') ,  pyspark.sql.functions.count('num_bytes').alias('num_shards') ,  pyspark.sql.functions.collect_list('num_examples').alias('shard_lengths') ,  )
              .collect()
          )
          for row in stats:
                 yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths)

   def 							__lowercase		( self ,  lowercase ,  lowercase = "arrow" ,  lowercase = None ,  lowercase = None ,  **lowercase ,  )      ->						int:







          '''simple docstring'''

          self._validate_cache_dir()

          a__						:     Union[str, Any]			=    convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE)
          self._repartition_df_if_needed(lowercase)
          a__						:     List[str]			=    not is_remote_filesystem(self._fs)
          a__						:     Optional[Any]			=    os.path.join if is_local else posixpath.join

          a__						:     Dict			=    '-TTTTT-SSSSS-of-NNNNN'
          a__						:     Dict			=    F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}'
          a__						:     Any			=    path_join(self._output_dir ,  lowercase)

          a__						:     Any			=    0
          a__						:     List[str]			=    0
          a__						:     Any			=    0
          a__						:     Optional[int]			=    []
          a__						:     Optional[int]			=    []

          for task_id, content in self._prepare_split_single(lowercase ,  lowercase ,  lowercase):
                 (
                     (
                     a__
                 )			,							(
                     a__
                 )			,							(
                     a__
                 )			,							(
                     a__
                 )			,							
                 )						:     List[Any]			=    content
                 if num_bytes > 0:
                        total_num_examples += num_examples
                        total_num_bytes += num_bytes
                        total_shards += num_shards
                        task_id_and_num_shards.append((task_id, num_shards))
                        all_shard_lengths.extend(lowercase)

          a__						:     Optional[int]			=    total_num_examples
          a__						:     Tuple			=    total_num_bytes

          # should rename everything at the end
          logger.debug(F'Renaming {total_shards} shards.')
          if total_shards > 1:
                 a__						:     Any			=    all_shard_lengths

                 # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a
                 # pickling error due to pickling the SparkContext.
                 a__						:     Optional[int]			=    self._fs

                 # use the -SSSSS-of-NNNNN pattern
                 def _rename_shard(
                     lowercase ,  lowercase ,  lowercase ,  ):
                        rename(
                            lowercase ,  fpath.replace('SSSSS' ,  F'{shard_id:05d}').replace('TTTTT' ,  F'{task_id:05d}') ,  fpath.replace('TTTTT-SSSSS' ,  F'{global_shard_id:05d}').replace('NNNNN' ,  F'{total_shards:05d}') ,  )

                 a__						:     List[str]			=    []
                 a__						:     List[str]			=    0
                 for i in range(len(lowercase)):
                        a__			,							a__						:     Optional[Any]			=    task_id_and_num_shards[i]
                        for shard_id in range(lowercase):
                               args.append([task_id, shard_id, global_shard_id])
                               global_shard_id += 1
                 self._spark.sparkContext.parallelize(lowercase ,  len(lowercase)).map(lambda lowercase: _rename_shard(*lowercase)).collect()
          else:
                 # don't use any pattern
                 a__						:     Optional[int]			=    0
                 a__						:     List[Any]			=    task_id_and_num_shards[0][0]
                 self._rename(
                     fpath.replace('SSSSS' ,  F'{shard_id:05d}').replace('TTTTT' ,  F'{task_id:05d}') ,  fpath.replace(lowercase ,  '') ,  )

   def 							__lowercase		( self ,  lowercase ,  )      ->						SparkExamplesIterable:







          '''simple docstring'''

          return SparkExamplesIterable(self.df)









from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
    from transformers import (
        TFBertModel,
        TFCLIPVisionModel,
        TFDeiTModel,
        TFRobertaModel,
        TFVisionTextDualEncoderModel,
        TFViTModel,
        VisionTextDualEncoderConfig,
    )

if is_vision_available():
    from PIL import Image

    from transformers import VisionTextDualEncoderProcessor



def A_     (		A__    )  ->		Dict:
       if isinstance(A__		,				collections.abc.Iterable    ):
              return x
       return (x, x)





@require_tf
class 			A__   :




   """simple docstring"""



   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Union[str, Any]:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          pass

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Any			=    VisionTextDualEncoderConfig.from_vision_text_configs(lowercase ,  lowercase)

          a__						:     Any			=    TFVisionTextDualEncoderModel(lowercase)

          a__						:     Dict			=    model(input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase)

          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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__			,							a__						:     List[Any]			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     List[str]			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

          a__						:     Dict			=    model(input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase)

          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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Tuple:







          '''simple docstring'''

          a__			,							a__						:     Any			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Tuple			=    {'vision_model': vision_model, 'text_model': text_model}
          a__						:     Union[str, Any]			=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase)

          a__						:     Any			=    model(input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase)

          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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__			,							a__						:     int			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     List[Any]			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

          a__						:     Optional[Any]			=    model(input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase)
          a__						:     int			=    output[0].numpy()

          with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_pretrained(lowercase)
                 a__						:     str			=    TFVisionTextDualEncoderModel.from_pretrained(lowercase)

                 a__						:     List[str]			=    model(input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase)
                 a__						:     str			=    after_output[0].numpy()
                 a__						:     str			=    np.amax(np.abs(out_a - out_a))
                 self.assertLessEqual(lowercase ,  1e-5)

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Optional[int]:







          '''simple docstring'''

          a__			,							a__						:     Optional[Any]			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Dict			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

          a__						:     Optional[int]			=    model(
              input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase ,  output_attentions=lowercase)

          a__						:     List[str]			=    output.vision_model_output.attentions
          self.assertEqual(len(lowercase) ,  vision_config.num_hidden_layers)

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

          a__						:     Union[str, Any]			=    output.text_model_output.attentions
          self.assertEqual(len(lowercase) ,  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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						Any:







          '''simple docstring'''

          a__						:     str			=    np.abs((a - b)).max()
          self.assertLessEqual(lowercase ,  lowercase ,  F'Difference between torch and flax is {diff} (>= {tol}).')

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     List[Any]			=    self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_model(**lowercase)

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     List[Any]			=    self.prepare_config_and_inputs()
          self.check_model_from_pretrained_configs(**lowercase)

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Any			=    self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_from_pretrained(**lowercase)

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     int			=    self.prepare_config_and_inputs()
          self.check_save_load(**lowercase)

   def 							__lowercase		( self)      ->						Optional[int]:







          '''simple docstring'''

          a__						:     List[str]			=    self.prepare_config_and_inputs()
          self.check_vision_text_output_attention(**lowercase)

   @slow
   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__			,							a__						:     Union[str, Any]			=    self.get_pretrained_model_and_inputs()

          a__						:     Optional[int]			=    model_a(**lowercase)
          a__						:     int			=    outputs[0].numpy()

          with tempfile.TemporaryDirectory() as tmp_dirname:
                 model_a.save_pretrained(lowercase)
                 a__						:     Union[str, Any]			=    TFVisionTextDualEncoderModel.from_pretrained(lowercase)

                 a__						:     int			=    model_a(**lowercase)
                 a__						:     str			=    after_outputs[0].numpy()
                 a__						:     List[Any]			=    np.amax(np.abs(out_a - out_a))
                 self.assertLessEqual(lowercase ,  1e-5)





@require_tf
class 			A__   (							__UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



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







          '''simple docstring'''

          a__						:     Any			=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              'hf-internal-testing/tiny-random-vit' ,  'hf-internal-testing/tiny-random-bert')
          a__						:     str			=    13
          a__						:     Optional[int]			=    floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ])
          a__						:     Tuple			=    ids_tensor([batch_size, 4] ,  model.text_model.config.vocab_size)
          a__						:     Optional[int]			=    random_attention_mask([batch_size, 4])
          a__						:     str			=    {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Optional[Any]			=    TFViTModel(lowercase ,  name='vision_model')
          a__						:     Tuple			=    TFBertModel(lowercase ,  name='text_model')
          return vision_model, text_model

   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Tuple			=    TFViTModelTester(self)
          a__						:     int			=    TFBertModelTester(self)
          a__						:     Optional[Any]			=    vit_model_tester.prepare_config_and_inputs()
          a__						:     Any			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__			,							a__						:     Optional[int]			=    vision_config_and_inputs

          (
              (
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							
          )						:     Any			=    text_config_and_inputs

          return {
              "text_config": text_config,
              "vision_config": vision_config,
              "pixel_values": pixel_values,
              "attention_mask": input_mask,
              "input_ids": input_ids,
              "text_token_type_ids": token_type_ids,
              "text_sequence_labels": sequence_labels,
              "text_token_labels": token_labels,
              "text_choice_labels": choice_labels,
          }





@require_tf
class 			A__   (							__UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



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







          '''simple docstring'''

          a__						:     Optional[Any]			=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              'Rocketknight1/tiny-random-deit-tf' ,  'hf-internal-testing/tiny-random-roberta')
          a__						:     Union[str, Any]			=    13
          a__						:     Dict			=    floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ])
          a__						:     Optional[Any]			=    ids_tensor([batch_size, 4] ,  model.text_model.config.vocab_size)
          a__						:     Any			=    random_attention_mask([batch_size, 4])
          a__						:     int			=    {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__			,							a__						:     List[Any]			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Any			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

          a__						:     int			=    model(
              input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase ,  output_attentions=lowercase)

          a__						:     Optional[Any]			=    output.vision_model_output.attentions
          self.assertEqual(len(lowercase) ,  vision_config.num_hidden_layers)

          # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
          a__						:     Optional[int]			=    to_atuple(vision_model.config.image_size)
          a__						:     str			=    to_atuple(vision_model.config.patch_size)
          a__						:     Tuple			=    (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
          a__						:     List[str]			=    num_patches + 2
          self.assertEqual(vision_attentions[0].shape[-3:] ,  (vision_config.num_attention_heads, seq_len, seq_len))

          a__						:     List[Any]			=    output.text_model_output.attentions
          self.assertEqual(len(lowercase) ,  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 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     List[str]			=    TFDeiTModel(lowercase ,  name='vision_model')
          a__						:     Optional[int]			=    TFRobertaModel(lowercase ,  name='text_model')
          return vision_model, text_model

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Optional[int]			=    TFDeiTModelTester(self)
          a__						:     str			=    TFRobertaModelTester(self)
          a__						:     str			=    vit_model_tester.prepare_config_and_inputs()
          a__						:     Dict			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__			,							a__						:     Any			=    vision_config_and_inputs

          (
              (
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							
          )						:     Tuple			=    text_config_and_inputs

          return {
              "text_config": text_config,
              "vision_config": vision_config,
              "pixel_values": pixel_values,
              "attention_mask": input_mask,
              "input_ids": input_ids,
              "text_token_type_ids": token_type_ids,
              "text_sequence_labels": sequence_labels,
              "text_token_labels": token_labels,
              "text_choice_labels": choice_labels,
          }





@require_tf
class 			A__   (							__UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Dict			=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              'Rocketknight1/tiny-random-clip-tf' ,  'hf-internal-testing/tiny-random-bert')
          a__						:     Optional[int]			=    13
          a__						:     Optional[Any]			=    floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ])
          a__						:     int			=    ids_tensor([batch_size, 4] ,  model.text_model.config.vocab_size)
          a__						:     str			=    random_attention_mask([batch_size, 4])
          a__						:     int			=    {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     str			=    TFCLIPVisionModel(lowercase ,  name='vision_model')
          a__						:     str			=    TFBertModel(lowercase ,  name='text_model')
          return vision_model, text_model

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







          '''simple docstring'''

          a__						:     List[str]			=    TFCLIPVisionModelTester(self)
          a__						:     Dict			=    TFBertModelTester(self)
          a__						:     Optional[Any]			=    clip_model_tester.prepare_config_and_inputs()
          a__						:     List[Any]			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__						:     Union[str, Any]			=    vision_config_and_inputs

          (
              (
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							
          )						:     Optional[int]			=    text_config_and_inputs

          return {
              "text_config": text_config,
              "vision_config": vision_config,
              "pixel_values": pixel_values,
              "attention_mask": input_mask,
              "input_ids": input_ids,
              "text_token_type_ids": token_type_ids,
              "text_sequence_labels": sequence_labels,
              "text_token_labels": token_labels,
              "text_choice_labels": choice_labels,
          }





@require_vision
@require_tf
class 			A__   (							unittest.TestCase     ):




   """simple docstring"""



   @slow
   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Tuple			=    TFVisionTextDualEncoderModel.from_pretrained(
              'clip-italian/clip-italian' ,  logit_scale_init_value=1.0 ,  from_pt=lowercase)
          a__						:     str			=    VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')

          a__						:     Tuple			=    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
          a__						:     Optional[Any]			=    processor(
              text=['una foto di un gatto', 'una foto di un cane'] ,  images=lowercase ,  padding=lowercase ,  return_tensors='np')

          a__						:     int			=    model(**lowercase)

          # 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]) ,  )

          a__						:     List[str]			=    np.array([[1.2_28_47_27, 0.3_10_41_22]])

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


