


"""simple docstring"""


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 _lowerCamelCase			(	_UpperCamelCase   ):

			'''simple docstring'''




			if isinstance(_UpperCamelCase					,				collections.abc.Iterable   ):
						return x
			return (x, x)
@require_tf
class 						_UpperCamelCase						:
							'''simple docstring'''







							def     snake_case       (  self					,     __a					,     __a			):
										pass

							def     snake_case       (  self			):
										pass

							def     snake_case       (  self			):
										pass

							def     snake_case       (  self					,     __a					,     __a					,     __a					,     __a					,     __a=None					,     **__a			):
										__lowerCAmelCase       					=    VisionTextDualEncoderConfig.from_vision_text_configs(__a					,     __a			)

										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel(__a			)

										__lowerCAmelCase       					=    model(input_ids=__a					,     pixel_values=__a					,     attention_mask=__a			)

										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     snake_case       (  self					,     __a					,     __a					,     __a					,     __a					,     __a=None					,     **__a			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.get_vision_text_model(__a					,     __a			)
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel(vision_model=__a					,     text_model=__a			)

										__lowerCAmelCase       					=    model(input_ids=__a					,     pixel_values=__a					,     attention_mask=__a			)

										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     snake_case       (  self					,     __a					,     __a					,     __a					,     __a					,     __a=None					,     **__a			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.get_vision_text_model(__a					,     __a			)
										__lowerCAmelCase       					=    {"vision_model": vision_model, "text_model": text_model}
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(**__a			)

										__lowerCAmelCase       					=    model(input_ids=__a					,     pixel_values=__a					,     attention_mask=__a			)

										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     snake_case       (  self					,     __a					,     __a					,     __a					,     __a					,     __a=None					,     **__a			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.get_vision_text_model(__a					,     __a			)
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel(vision_model=__a					,     text_model=__a			)

										__lowerCAmelCase       					=    model(input_ids=__a					,     pixel_values=__a					,     attention_mask=__a			)
										__lowerCAmelCase       					=    output[0].numpy()

										with tempfile.TemporaryDirectory() as tmpdirname:
													model.save_pretrained(__a			)
													__lowerCAmelCase       					=    TFVisionTextDualEncoderModel.from_pretrained(__a			)

													__lowerCAmelCase       					=    model(input_ids=__a					,     pixel_values=__a					,     attention_mask=__a			)
													__lowerCAmelCase       					=    after_output[0].numpy()
													__lowerCAmelCase       					=    np.amax(np.abs(out_a - out_a			)			)
													self.assertLessEqual(__a					,     1e-5			)

							def     snake_case       (  self					,     __a					,     __a					,     __a					,     __a					,     __a=None					,     **__a			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.get_vision_text_model(__a					,     __a			)
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel(vision_model=__a					,     text_model=__a			)

										__lowerCAmelCase       					=    model(
										    input_ids=__a					,     pixel_values=__a					,     attention_mask=__a					,     output_attentions=__a			)

										__lowerCAmelCase       					=    output.vision_model_output.attentions
										self.assertEqual(len(__a			)					,     vision_config.num_hidden_layers			)

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

										__lowerCAmelCase       					=    output.text_model_output.attentions
										self.assertEqual(len(__a			)					,     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     snake_case       (  self					,     __a					,     __a					,     __a			):
										__lowerCAmelCase       					=    np.abs((a - b)			).max()
										self.assertLessEqual(__a					,     __a					,     f"Difference between torch and flax is {diff} (>= {tol})."			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.prepare_config_and_inputs()
										self.check_vision_text_dual_encoder_model(**__a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.prepare_config_and_inputs()
										self.check_model_from_pretrained_configs(**__a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.prepare_config_and_inputs()
										self.check_vision_text_dual_encoder_from_pretrained(**__a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.prepare_config_and_inputs()
										self.check_save_load(**__a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.prepare_config_and_inputs()
										self.check_vision_text_output_attention(**__a			)



							@slow
							def     snake_case       (  self			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.get_pretrained_model_and_inputs()

										__lowerCAmelCase       					=    model_a(**__a			)
										__lowerCAmelCase       					=    outputs[0].numpy()

										with tempfile.TemporaryDirectory() as tmp_dirname:
													model_a.save_pretrained(__a			)
													__lowerCAmelCase       					=    TFVisionTextDualEncoderModel.from_pretrained(__a			)

													__lowerCAmelCase       					=    model_a(**__a			)
													__lowerCAmelCase       					=    after_outputs[0].numpy()
													__lowerCAmelCase       					=    np.amax(np.abs(out_a - out_a			)			)
													self.assertLessEqual(__a					,     1e-5			)
@require_tf
class 						_UpperCamelCase						(     lowerCAmelCase__ ,unittest.TestCase	):
							'''simple docstring'''







							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(
										    "hf-internal-testing/tiny-random-vit"					,     "hf-internal-testing/tiny-random-bert"			)
										__lowerCAmelCase       					=    13
										__lowerCAmelCase       					=    floats_tensor(
										    [
										        batch_size,
										        model.vision_model.config.num_channels,
										        model.vision_model.config.image_size,
										        model.vision_model.config.image_size,
										    ]			)
										__lowerCAmelCase       					=    ids_tensor([batch_size, 4]					,     model.text_model.config.vocab_size			)
										__lowerCAmelCase       					=    random_attention_mask([batch_size, 4]			)
										__lowerCAmelCase       					=    {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

										return model, inputs

							def     snake_case       (  self					,     __a					,     __a			):
										__lowerCAmelCase       					=    TFViTModel(__a					,     name="vision_model"			)
										__lowerCAmelCase       					=    TFBertModel(__a					,     name="text_model"			)
										return vision_model, text_model



							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFViTModelTester(self			)
										__lowerCAmelCase       					=    TFBertModelTester(self			)
										__lowerCAmelCase       					=    vit_model_tester.prepare_config_and_inputs()
										__lowerCAmelCase       					=    bert_model_tester.prepare_config_and_inputs()

										__lowerCAmelCase					,			__lowerCAmelCase					,			__lowerCAmelCase       					=    vision_config_and_inputs

										(
										    (
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			
										)       					=    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 						_UpperCamelCase						(     lowerCAmelCase__ ,unittest.TestCase	):
							'''simple docstring'''







							def     snake_case       (  self			):
										# DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
										# just reinitialize it.
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(
										    "Rocketknight1/tiny-random-deit-tf"					,     "hf-internal-testing/tiny-random-roberta"			)
										__lowerCAmelCase       					=    13
										__lowerCAmelCase       					=    floats_tensor(
										    [
										        batch_size,
										        model.vision_model.config.num_channels,
										        model.vision_model.config.image_size,
										        model.vision_model.config.image_size,
										    ]			)
										__lowerCAmelCase       					=    ids_tensor([batch_size, 4]					,     model.text_model.config.vocab_size			)
										__lowerCAmelCase       					=    random_attention_mask([batch_size, 4]			)
										__lowerCAmelCase       					=    {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

										return model, inputs

							def     snake_case       (  self					,     __a					,     __a					,     __a					,     __a					,     __a=None					,     **__a			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.get_vision_text_model(__a					,     __a			)
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel(vision_model=__a					,     text_model=__a			)

										__lowerCAmelCase       					=    model(
										    input_ids=__a					,     pixel_values=__a					,     attention_mask=__a					,     output_attentions=__a			)

										__lowerCAmelCase       					=    output.vision_model_output.attentions
										self.assertEqual(len(__a			)					,     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)
										__lowerCAmelCase       					=    to_atuple(vision_model.config.image_size			)
										__lowerCAmelCase       					=    to_atuple(vision_model.config.patch_size			)
										__lowerCAmelCase       					=    (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
										__lowerCAmelCase       					=    num_patches + 2
										self.assertEqual(vision_attentions[0].shape[-3:]					,     (vision_config.num_attention_heads, seq_len, seq_len)			)

										__lowerCAmelCase       					=    output.text_model_output.attentions
										self.assertEqual(len(__a			)					,     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     snake_case       (  self					,     __a					,     __a			):
										__lowerCAmelCase       					=    TFDeiTModel(__a					,     name="vision_model"			)
										__lowerCAmelCase       					=    TFRobertaModel(__a					,     name="text_model"			)
										return vision_model, text_model



							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFDeiTModelTester(self			)
										__lowerCAmelCase       					=    TFRobertaModelTester(self			)
										__lowerCAmelCase       					=    vit_model_tester.prepare_config_and_inputs()
										__lowerCAmelCase       					=    bert_model_tester.prepare_config_and_inputs()

										__lowerCAmelCase					,			__lowerCAmelCase					,			__lowerCAmelCase       					=    vision_config_and_inputs

										(
										    (
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			
										)       					=    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 						_UpperCamelCase						(     lowerCAmelCase__ ,unittest.TestCase	):
							'''simple docstring'''







							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(
										    "Rocketknight1/tiny-random-clip-tf"					,     "hf-internal-testing/tiny-random-bert"			)
										__lowerCAmelCase       					=    13
										__lowerCAmelCase       					=    floats_tensor(
										    [
										        batch_size,
										        model.vision_model.config.num_channels,
										        model.vision_model.config.image_size,
										        model.vision_model.config.image_size,
										    ]			)
										__lowerCAmelCase       					=    ids_tensor([batch_size, 4]					,     model.text_model.config.vocab_size			)
										__lowerCAmelCase       					=    random_attention_mask([batch_size, 4]			)
										__lowerCAmelCase       					=    {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

										return model, inputs

							def     snake_case       (  self					,     __a					,     __a			):
										__lowerCAmelCase       					=    TFCLIPVisionModel(__a					,     name="vision_model"			)
										__lowerCAmelCase       					=    TFBertModel(__a					,     name="text_model"			)
										return vision_model, text_model



							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFCLIPVisionModelTester(self			)
										__lowerCAmelCase       					=    TFBertModelTester(self			)
										__lowerCAmelCase       					=    clip_model_tester.prepare_config_and_inputs()
										__lowerCAmelCase       					=    bert_model_tester.prepare_config_and_inputs()

										__lowerCAmelCase					,			__lowerCAmelCase       					=    vision_config_and_inputs

										(
										    (
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			(
										    __lowerCAmelCase
										)					,			
										)       					=    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 						_UpperCamelCase						(     unittest.TestCase	):
							'''simple docstring'''







							@slow
							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFVisionTextDualEncoderModel.from_pretrained(
										    "clip-italian/clip-italian"					,     logit_scale_init_value=1.0					,     from_pt=__a			)
										__lowerCAmelCase       					=    VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"			)

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

										__lowerCAmelCase       					=    model(**__a			)

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

										__lowerCAmelCase       					=    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.numpy()					,     __a					,     atol=1e-3			)			)








"""simple docstring"""


import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
	from sagemaker import Session, TrainingJobAnalytics
	from sagemaker.huggingface import HuggingFace
@pytest.mark.skipif(
    literal_eval(os.getenv("""TEST_SAGEMAKER""" ,"""False"""	)	) is not True ,reason="""Skipping test because should only be run when releasing minor transformers version""" ,)
@pytest.mark.usefixtures("""sm_env"""	)
@parameterized_class(
    [
        {
            """framework""": """pytorch""",
            """script""": """run_glue_model_parallelism.py""",
            """model_name_or_path""": """roberta-large""",
            """instance_type""": """ml.p3dn.24xlarge""",
            """results""": {"""train_runtime""": 1_6_0_0, """eval_accuracy""": 0.3, """eval_loss""": 1.2},
        },
        {
            """framework""": """pytorch""",
            """script""": """run_glue.py""",
            """model_name_or_path""": """roberta-large""",
            """instance_type""": """ml.p3dn.24xlarge""",
            """results""": {"""train_runtime""": 1_6_0_0, """eval_accuracy""": 0.3, """eval_loss""": 1.2},
        },
    ]	)
class 						_UpperCamelCase						(     unittest.TestCase	):
							'''simple docstring'''







							def     snake_case       (  self			):
										if self.framework == "pytorch":
													subprocess.run(
													    f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split()					,     encoding="utf-8"					,     check=__a					,     )
										assert hasattr(self					,     "env"			)

							def     snake_case       (  self					,     __a			):
										# configuration for running training on smdistributed Model Parallel
										__lowerCAmelCase       					=    {
										    "enabled": True,
										    "processes_per_host": 8,
										}
										__lowerCAmelCase       					=    {
										    "enabled": True,
										    "parameters": {
										        "microbatches": 4,
										        "placement_strategy": "spread",
										        "pipeline": "interleaved",
										        "optimize": "speed",
										        "partitions": 4,
										        "ddp": True,
										    },
										}

										__lowerCAmelCase       					=    {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options}

										__lowerCAmelCase       					=    "trainer" if self.script == "run_glue.py" else "smtrainer"
										# creates estimator
										return HuggingFace(
										    entry_point=self.script					,     source_dir=self.env.test_path					,     role=self.env.role					,     image_uri=self.env.image_uri					,     base_job_name=f"{self.env.base_job_name}-{instance_count}-smp-{name_extension}"					,     instance_count=__a					,     instance_type=self.instance_type					,     debugger_hook_config=__a					,     hyperparameters={
										        **self.env.hyperparameters,
										        "model_name_or_path": self.model_name_or_path,
										        "max_steps": 5_00,
										    }					,     metric_definitions=self.env.metric_definitions					,     distribution=__a					,     py_version="py36"					,     )

							def     snake_case       (  self					,     __a			):
										TrainingJobAnalytics(__a			).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv"			)



							@parameterized.expand([(1,)]			)
							def     snake_case       (  self					,     __a			):
										# create estimator
										__lowerCAmelCase       					=    self.create_estimator(__a			)

										# run training
										estimator.fit()

										# result dataframe
										__lowerCAmelCase       					=    TrainingJobAnalytics(estimator.latest_training_job.name			).dataframe()

										# extract kpis
										__lowerCAmelCase       					=    list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]			)
										__lowerCAmelCase       					=    list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]			)
										# get train time from SageMaker job, this includes starting, preprocessing, stopping
										__lowerCAmelCase       					=    (
										    Session().describe_training_job(estimator.latest_training_job.name			).get("TrainingTimeInSeconds"					,     99_99_99			)
										)

										# assert kpis
										assert train_runtime <= self.results["train_runtime"]
										assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy			)
										assert all(t <= self.results["eval_loss"] for t in eval_loss			)

										# dump tests result into json file to share in PR
										with open(f"{estimator.latest_training_job.name}.json"					,     "w"			) as outfile:
													json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}					,     __a			)




