


import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
						from PIL import Image

						from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
						import torch

if is_tf_available():
						import tensorflow as tf







@require_vision
@require_torchvision
class  snake_case__(							unittest.TestCase							):







						'''simple docstring'''




						def   lowercase_       ( self							)    ->			Optional[int]:
										lowerCAmelCase_       :					Union[str, Any]			 = tempfile.mkdtemp()
										lowerCAmelCase_       :					Any			 = SamImageProcessor()
										lowerCAmelCase_       :					Tuple			 = SamProcessor(__lowercase							)
										processor.save_pretrained(self.tmpdirname							)




						def   lowercase_       ( self      ,  **__lowercase							)    ->			Tuple:
										return AutoProcessor.from_pretrained(self.tmpdirname      ,  **__lowercase							).image_processor




						def   lowercase_       ( self							)    ->			int:
										shutil.rmtree(self.tmpdirname							)




						def   lowercase_       ( self							)    ->			Tuple:
										lowerCAmelCase_       :					Tuple			 = [np.random.randint(2_5_5      ,  size=(3, 3_0, 4_0_0)      ,  dtype=np.uinta							)]

										lowerCAmelCase_       :					List[str]			 = [Image.fromarray(np.moveaxis(__lowercase      ,  0      ,  -1							)							) for x in image_inputs]

										return image_inputs




						def   lowercase_       ( self							)    ->			Optional[int]:
										lowerCAmelCase_       :					Optional[int]			 = SamProcessor(image_processor=self.get_image_processor()							)
										processor.save_pretrained(self.tmpdirname							)

										lowerCAmelCase_       :					Optional[int]			 = self.get_image_processor(do_normalize=__lowercase      ,  padding_value=1.0							)

										lowerCAmelCase_       :					Union[str, Any]			 = SamProcessor.from_pretrained(self.tmpdirname      ,  do_normalize=__lowercase      ,  padding_value=1.0							)

										self.assertEqual(processor.image_processor.to_json_string()      ,  image_processor_add_kwargs.to_json_string()							)
										self.assertIsInstance(processor.image_processor      ,  __lowercase							)




						def   lowercase_       ( self							)    ->			List[str]:
										lowerCAmelCase_       :					Dict			 = self.get_image_processor()

										lowerCAmelCase_       :					List[Any]			 = SamProcessor(image_processor=__lowercase							)

										lowerCAmelCase_       :					int			 = self.prepare_image_inputs()

										lowerCAmelCase_       :					Dict			 = image_processor(__lowercase      ,  return_tensors='''np'''							)
										lowerCAmelCase_       :					Optional[Any]			 = processor(images=__lowercase      ,  return_tensors='''np'''							)

										input_feat_extract.pop('''original_sizes'''							)  # pop original_sizes as it is popped in the processor
										input_feat_extract.pop('''reshaped_input_sizes'''							)  # pop original_sizes as it is popped in the processor

										for key in input_feat_extract.keys():
														self.assertAlmostEqual(input_feat_extract[key].sum()      ,  input_processor[key].sum()      ,  delta=1e-2							)




						@require_torch
						def   lowercase_       ( self							)    ->			Optional[int]:
										lowerCAmelCase_       :					str			 = self.get_image_processor()

										lowerCAmelCase_       :					str			 = SamProcessor(image_processor=__lowercase							)
										lowerCAmelCase_       :					Dict			 = [torch.ones((1, 3, 5, 5)							)]

										lowerCAmelCase_       :					int			 = [[1_7_6_4, 2_6_4_6]]

										lowerCAmelCase_       :					Optional[Any]			 = [[6_8_3, 1_0_2_4]]
										lowerCAmelCase_       :					Any			 = processor.post_process_masks(__lowercase      ,  __lowercase      ,  __lowercase							)
										self.assertEqual(masks[0].shape      ,  (1, 3, 1_7_6_4, 2_6_4_6)							)

										lowerCAmelCase_       :					Dict			 = processor.post_process_masks(
										    __lowercase      ,  torch.tensor(__lowercase							)      ,  torch.tensor(__lowercase							)							)
										self.assertEqual(masks[0].shape      ,  (1, 3, 1_7_6_4, 2_6_4_6)							)

										# should also work with np
										lowerCAmelCase_       :					str			 = [np.ones((1, 3, 5, 5)							)]
										lowerCAmelCase_       :					Union[str, Any]			 = processor.post_process_masks(__lowercase      ,  np.array(__lowercase							)      ,  np.array(__lowercase							)							)

										self.assertEqual(masks[0].shape      ,  (1, 3, 1_7_6_4, 2_6_4_6)							)

										lowerCAmelCase_       :					List[str]			 = [[1, 0], [0, 1]]
										with self.assertRaises(__lowercase							):
														lowerCAmelCase_       :					int			 = processor.post_process_masks(__lowercase      ,  np.array(__lowercase							)      ,  np.array(__lowercase							)							)







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







						'''simple docstring'''




						def   lowercase_       ( self							)    ->			str:
										lowerCAmelCase_       :					Dict			 = tempfile.mkdtemp()
										lowerCAmelCase_       :					Dict			 = SamImageProcessor()
										lowerCAmelCase_       :					int			 = SamProcessor(__lowercase							)
										processor.save_pretrained(self.tmpdirname							)




						def   lowercase_       ( self      ,  **__lowercase							)    ->			Any:
										return AutoProcessor.from_pretrained(self.tmpdirname      ,  **__lowercase							).image_processor




						def   lowercase_       ( self							)    ->			List[Any]:
										shutil.rmtree(self.tmpdirname							)




						def   lowercase_       ( self							)    ->			List[Any]:
										lowerCAmelCase_       :					List[str]			 = [np.random.randint(2_5_5      ,  size=(3, 3_0, 4_0_0)      ,  dtype=np.uinta							)]

										lowerCAmelCase_       :					Optional[Any]			 = [Image.fromarray(np.moveaxis(__lowercase      ,  0      ,  -1							)							) for x in image_inputs]

										return image_inputs




						def   lowercase_       ( self							)    ->			int:
										lowerCAmelCase_       :					Optional[int]			 = SamProcessor(image_processor=self.get_image_processor()							)
										processor.save_pretrained(self.tmpdirname							)

										lowerCAmelCase_       :					Optional[int]			 = self.get_image_processor(do_normalize=__lowercase      ,  padding_value=1.0							)

										lowerCAmelCase_       :					Optional[Any]			 = SamProcessor.from_pretrained(self.tmpdirname      ,  do_normalize=__lowercase      ,  padding_value=1.0							)

										self.assertEqual(processor.image_processor.to_json_string()      ,  image_processor_add_kwargs.to_json_string()							)
										self.assertIsInstance(processor.image_processor      ,  __lowercase							)




						def   lowercase_       ( self							)    ->			Optional[int]:
										lowerCAmelCase_       :					Any			 = self.get_image_processor()

										lowerCAmelCase_       :					int			 = SamProcessor(image_processor=__lowercase							)

										lowerCAmelCase_       :					List[Any]			 = self.prepare_image_inputs()

										lowerCAmelCase_       :					Optional[Any]			 = image_processor(__lowercase      ,  return_tensors='''np'''							)
										lowerCAmelCase_       :					List[str]			 = processor(images=__lowercase      ,  return_tensors='''np'''							)

										input_feat_extract.pop('''original_sizes'''							)  # pop original_sizes as it is popped in the processor
										input_feat_extract.pop('''reshaped_input_sizes'''							)  # pop reshaped_input_sizes as it is popped in the processor

										for key in input_feat_extract.keys():
														self.assertAlmostEqual(input_feat_extract[key].sum()      ,  input_processor[key].sum()      ,  delta=1e-2							)




						@require_tf
						def   lowercase_       ( self							)    ->			Union[str, Any]:
										lowerCAmelCase_       :					Dict			 = self.get_image_processor()

										lowerCAmelCase_       :					Any			 = SamProcessor(image_processor=__lowercase							)
										lowerCAmelCase_       :					Optional[int]			 = [tf.ones((1, 3, 5, 5)							)]

										lowerCAmelCase_       :					Dict			 = [[1_7_6_4, 2_6_4_6]]

										lowerCAmelCase_       :					Dict			 = [[6_8_3, 1_0_2_4]]
										lowerCAmelCase_       :					Union[str, Any]			 = processor.post_process_masks(__lowercase      ,  __lowercase      ,  __lowercase      ,  return_tensors='''tf'''							)
										self.assertEqual(masks[0].shape      ,  (1, 3, 1_7_6_4, 2_6_4_6)							)

										lowerCAmelCase_       :					List[str]			 = processor.post_process_masks(
										    __lowercase      ,  tf.convert_to_tensor(__lowercase							)      ,  tf.convert_to_tensor(__lowercase							)      ,  return_tensors='''tf'''      ,  )
										self.assertEqual(masks[0].shape      ,  (1, 3, 1_7_6_4, 2_6_4_6)							)

										# should also work with np
										lowerCAmelCase_       :					Dict			 = [np.ones((1, 3, 5, 5)							)]
										lowerCAmelCase_       :					str			 = processor.post_process_masks(
										    __lowercase      ,  np.array(__lowercase							)      ,  np.array(__lowercase							)      ,  return_tensors='''tf'''							)

										self.assertEqual(masks[0].shape      ,  (1, 3, 1_7_6_4, 2_6_4_6)							)

										lowerCAmelCase_       :					Optional[Any]			 = [[1, 0], [0, 1]]
										with self.assertRaises(tf.errors.InvalidArgumentError							):
														lowerCAmelCase_       :					List[str]			 = processor.post_process_masks(
														    __lowercase      ,  np.array(__lowercase							)      ,  np.array(__lowercase							)      ,  return_tensors='''tf'''							)







@require_vision
@require_torchvision
class  snake_case__(							unittest.TestCase							):







						'''simple docstring'''




						def   lowercase_       ( self							)    ->			str:
										lowerCAmelCase_       :					int			 = tempfile.mkdtemp()
										lowerCAmelCase_       :					str			 = SamImageProcessor()
										lowerCAmelCase_       :					Optional[int]			 = SamProcessor(__lowercase							)
										processor.save_pretrained(self.tmpdirname							)




						def   lowercase_       ( self      ,  **__lowercase							)    ->			List[str]:
										return AutoProcessor.from_pretrained(self.tmpdirname      ,  **__lowercase							).image_processor




						def   lowercase_       ( self							)    ->			List[str]:
										shutil.rmtree(self.tmpdirname							)




						def   lowercase_       ( self							)    ->			str:
										lowerCAmelCase_       :					Tuple			 = [np.random.randint(2_5_5      ,  size=(3, 3_0, 4_0_0)      ,  dtype=np.uinta							)]

										lowerCAmelCase_       :					str			 = [Image.fromarray(np.moveaxis(__lowercase      ,  0      ,  -1							)							) for x in image_inputs]

										return image_inputs




						@is_pt_tf_cross_test
						def   lowercase_       ( self							)    ->			Tuple:
										lowerCAmelCase_       :					int			 = self.get_image_processor()

										lowerCAmelCase_       :					Optional[Any]			 = SamProcessor(image_processor=__lowercase							)
										lowerCAmelCase_       :					Optional[int]			 = np.random.randint(0      ,  2      ,  size=(1, 3, 5, 5)							).astype(np.floataa							)
										lowerCAmelCase_       :					Optional[int]			 = [tf.convert_to_tensor(__lowercase							)]
										lowerCAmelCase_       :					Optional[int]			 = [torch.tensor(__lowercase							)]

										lowerCAmelCase_       :					Dict			 = [[1_7_6_4, 2_6_4_6]]

										lowerCAmelCase_       :					Optional[Any]			 = [[6_8_3, 1_0_2_4]]
										lowerCAmelCase_       :					List[str]			 = processor.post_process_masks(
										    __lowercase      ,  __lowercase      ,  __lowercase      ,  return_tensors='''tf'''							)
										lowerCAmelCase_       :					Union[str, Any]			 = processor.post_process_masks(
										    __lowercase      ,  __lowercase      ,  __lowercase      ,  return_tensors='''pt'''							)

										self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()							)							)




						@is_pt_tf_cross_test
						def   lowercase_       ( self							)    ->			int:
										lowerCAmelCase_       :					Optional[Any]			 = self.get_image_processor()

										lowerCAmelCase_       :					Any			 = SamProcessor(image_processor=__lowercase							)

										lowerCAmelCase_       :					Union[str, Any]			 = self.prepare_image_inputs()

										lowerCAmelCase_       :					Optional[Any]			 = image_processor(__lowercase      ,  return_tensors='''pt'''							)["""pixel_values"""].numpy()
										lowerCAmelCase_       :					Dict			 = processor(images=__lowercase      ,  return_tensors='''pt'''							)["""pixel_values"""].numpy()

										lowerCAmelCase_       :					int			 = image_processor(__lowercase      ,  return_tensors='''tf'''							)["""pixel_values"""].numpy()
										lowerCAmelCase_       :					Optional[Any]			 = processor(images=__lowercase      ,  return_tensors='''tf'''							)["""pixel_values"""].numpy()

										self.assertTrue(np.allclose(__lowercase      ,  __lowercase							)							)
										self.assertTrue(np.allclose(__lowercase      ,  __lowercase							)							)
										self.assertTrue(np.allclose(__lowercase      ,  __lowercase							)							)




"""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 				lowerCamelCase  (			unittest.TestCase				):






					'''simple docstring'''





					def    lowerCAmelCase_				(       self:							Any						)   ->	str:
											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=snake_case						,     )
											assert hasattr(self						,     """env"""						)






					def    lowerCAmelCase_				(       self:							int						,     snake_case:							Dict						)   ->	List[Any]:
											# configuration for running training on smdistributed Model Parallel
											snake_case_ :Tuple						=			{
											    """enabled""": True,
											    """processes_per_host""": 8,
											}
											snake_case_ :List[Any]						=			{
											    """enabled""": True,
											    """parameters""": {
											        """microbatches""": 4,
											        """placement_strategy""": """spread""",
											        """pipeline""": """interleaved""",
											        """optimize""": """speed""",
											        """partitions""": 4,
											        """ddp""": True,
											    },
											}

											snake_case_ :Tuple						=			{"""smdistributed""": {"""modelparallel""": smp_options}, """mpi""": mpi_options}

											snake_case_ :Any						=			"""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=snake_case						,     instance_type=self.instance_type						,     debugger_hook_config=snake_case						,     hyperparameters={
											        **self.env.hyperparameters,
											        """model_name_or_path""": self.model_name_or_path,
											        """max_steps""": 500,
											    }						,     metric_definitions=self.env.metric_definitions						,     distribution=snake_case						,     py_version="""py36"""						,     )






					def    lowerCAmelCase_				(       self:							Any						,     snake_case:							Tuple						)   ->	List[str]:
											TrainingJobAnalytics(snake_case						).export_csv(f"""{self.env.test_path}/{job_name}_metrics.csv"""						)






					@parameterized.expand([(1,)]						)
					def    lowerCAmelCase_				(       self:							Dict						,     snake_case:							Dict						)   ->	List[Any]:
											# create estimator
											snake_case_ :List[Any]						=			self.create_estimator(snake_case						)

											# run training
											estimator.fit()

											# result dataframe
											snake_case_ :Any						=			TrainingJobAnalytics(estimator.latest_training_job.name						).dataframe()

											# extract kpis
											snake_case_ :Tuple						=			list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""]						)
											snake_case_ :Dict						=			list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""]						)
											# get train time from SageMaker job, this includes starting, preprocessing, stopping
											snake_case_ :int						=			(
											    Session().describe_training_job(estimator.latest_training_job.name						).get("""TrainingTimeInSeconds"""						,     999_999						)
											)

											# 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}						,     snake_case						)
