



import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import DetaImageProcessor







class 							_a							(					unittest.TestCase ):

			def __init__(self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_=7,					SCREAMING_SNAKE_CASE_=3,					SCREAMING_SNAKE_CASE_=30,					SCREAMING_SNAKE_CASE_=400,					SCREAMING_SNAKE_CASE_=True,					SCREAMING_SNAKE_CASE_=None,					SCREAMING_SNAKE_CASE_=True,					SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5],					SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5],					SCREAMING_SNAKE_CASE_=True,					SCREAMING_SNAKE_CASE_=1 / 255,					SCREAMING_SNAKE_CASE_=True,					)    ->					Any:
						UpperCAmelCase_:						List[Any]					=			size if size is not None else {"shortest_edge": 18, "longest_edge": 1333}
						UpperCAmelCase_:						Dict					=			parent
						UpperCAmelCase_:						Optional[int]					=			batch_size
						UpperCAmelCase_:						str					=			num_channels
						UpperCAmelCase_:						Optional[Any]					=			min_resolution
						UpperCAmelCase_:						List[Any]					=			max_resolution
						UpperCAmelCase_:						int					=			do_resize
						UpperCAmelCase_:						Union[str, Any]					=			size
						UpperCAmelCase_:						Union[str, Any]					=			do_normalize
						UpperCAmelCase_:						int					=			image_mean
						UpperCAmelCase_:						Optional[int]					=			image_std
						UpperCAmelCase_:						List[Any]					=			do_rescale
						UpperCAmelCase_:						Optional[Any]					=			rescale_factor
						UpperCAmelCase_:						Any					=			do_pad

			def 			__snake_case    (self )    ->					Any:
						return {
						    "do_resize": self.do_resize,
						    "size": self.size,
						    "do_normalize": self.do_normalize,
						    "image_mean": self.image_mean,
						    "image_std": self.image_std,
						    "do_rescale": self.do_rescale,
						    "rescale_factor": self.rescale_factor,
						    "do_pad": self.do_pad,
						}

			def 			__snake_case    (self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_=False )    ->					List[Any]:



						if not batched:
									UpperCAmelCase_:						Tuple					=			image_inputs[0]
									if isinstance(__lowerCamelCase,					Image.Image ):
												UpperCAmelCase_:						Tuple					=			image.size
									else:
												UpperCAmelCase_:						List[str]					=			image.shape[1], image.shape[2]
									if w < h:
												UpperCAmelCase_:						List[Any]					=			int(self.size["""shortest_edge"""] * h / w )
												UpperCAmelCase_:						Optional[Any]					=			self.size["shortest_edge"]
									elif w > h:
												UpperCAmelCase_:						List[Any]					=			self.size["shortest_edge"]
												UpperCAmelCase_:						List[str]					=			int(self.size["""shortest_edge"""] * w / h )
									else:
												UpperCAmelCase_:						Optional[int]					=			self.size["shortest_edge"]
												UpperCAmelCase_:						Union[str, Any]					=			self.size["shortest_edge"]

						else:
									UpperCAmelCase_:						Dict					=			[]
									for image in image_inputs:
												UpperCAmelCase_:						Union[str, Any]					=			self.get_expected_values([image] )
												expected_values.append((expected_height, expected_width) )
									UpperCAmelCase_:						str					=			max(__lowerCamelCase,					key=lambda SCREAMING_SNAKE_CASE_ : item[0] )[0]
									UpperCAmelCase_:						Optional[Any]					=			max(__lowerCamelCase,					key=lambda SCREAMING_SNAKE_CASE_ : item[1] )[1]

						return expected_height, expected_width







@require_torch
@require_vision
class 							_a							(					lowercase__      ,						unittest.TestCase ):
			A							=     DetaImageProcessor if is_vision_available() else None

			def 			__snake_case    (self )    ->					Union[str, Any]:
						UpperCAmelCase_:						str					=			DetaImageProcessingTester(self )

			@property
			def 			__snake_case    (self )    ->					str:
						return self.image_processor_tester.prepare_image_processor_dict()

			def 			__snake_case    (self )    ->					Dict:
						UpperCAmelCase_:						int					=			self.image_processing_class(**self.image_processor_dict )
						self.assertTrue(hasattr(__lowerCamelCase,					"""image_mean""" ) )
						self.assertTrue(hasattr(__lowerCamelCase,					"""image_std""" ) )
						self.assertTrue(hasattr(__lowerCamelCase,					"""do_normalize""" ) )
						self.assertTrue(hasattr(__lowerCamelCase,					"""do_resize""" ) )
						self.assertTrue(hasattr(__lowerCamelCase,					"""do_rescale""" ) )
						self.assertTrue(hasattr(__lowerCamelCase,					"""do_pad""" ) )
						self.assertTrue(hasattr(__lowerCamelCase,					"""size""" ) )

			def 			__snake_case    (self )    ->					Dict:
						UpperCAmelCase_:						Any					=			self.image_processing_class.from_dict(self.image_processor_dict )
						self.assertEqual(image_processor.size,					{"""shortest_edge""": 18, """longest_edge""": 1333} )
						self.assertEqual(image_processor.do_pad,					__lowerCamelCase )

			def 			__snake_case    (self )    ->					List[Any]:
						pass

			def 			__snake_case    (self )    ->					List[Any]:
						UpperCAmelCase_:						Optional[int]					=			self.image_processing_class(**self.image_processor_dict )
						# create random PIL images
						UpperCAmelCase_:						List[str]					=			prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowerCamelCase )
						for image in image_inputs:
									self.assertIsInstance(__lowerCamelCase,					Image.Image )

						# Test not batched input
						UpperCAmelCase_:						Optional[int]					=			image_processing(image_inputs[0],					return_tensors="""pt""" ).pixel_values

						UpperCAmelCase_:						Optional[Any]					=			self.image_processor_tester.get_expected_values(__lowerCamelCase )

						self.assertEqual(
						    encoded_images.shape,					(1, self.image_processor_tester.num_channels, expected_height, expected_width),					)

						# Test batched
						UpperCAmelCase_:						List[str]					=			self.image_processor_tester.get_expected_values(__lowerCamelCase,					batched=__lowerCamelCase )

						UpperCAmelCase_:						List[Any]					=			image_processing(__lowerCamelCase,					return_tensors="""pt""" ).pixel_values
						self.assertEqual(
						    encoded_images.shape,					(
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        expected_height,
						        expected_width,
						    ),					)

			def 			__snake_case    (self )    ->					Union[str, Any]:
						UpperCAmelCase_:						Optional[int]					=			self.image_processing_class(**self.image_processor_dict )
						# create random numpy tensors
						UpperCAmelCase_:						Optional[int]					=			prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowerCamelCase,					numpify=__lowerCamelCase )
						for image in image_inputs:
									self.assertIsInstance(__lowerCamelCase,					np.ndarray )

						# Test not batched input
						UpperCAmelCase_:						Any					=			image_processing(image_inputs[0],					return_tensors="""pt""" ).pixel_values

						UpperCAmelCase_:						Any					=			self.image_processor_tester.get_expected_values(__lowerCamelCase )

						self.assertEqual(
						    encoded_images.shape,					(1, self.image_processor_tester.num_channels, expected_height, expected_width),					)

						# Test batched
						UpperCAmelCase_:						Optional[Any]					=			image_processing(__lowerCamelCase,					return_tensors="""pt""" ).pixel_values

						UpperCAmelCase_:						Union[str, Any]					=			self.image_processor_tester.get_expected_values(__lowerCamelCase,					batched=__lowerCamelCase )

						self.assertEqual(
						    encoded_images.shape,					(
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        expected_height,
						        expected_width,
						    ),					)

			def 			__snake_case    (self )    ->					Any:
						UpperCAmelCase_:						Union[str, Any]					=			self.image_processing_class(**self.image_processor_dict )
						# create random PyTorch tensors
						UpperCAmelCase_:						Dict					=			prepare_image_inputs(self.image_processor_tester,					equal_resolution=__lowerCamelCase,					torchify=__lowerCamelCase )
						for image in image_inputs:
									self.assertIsInstance(__lowerCamelCase,					torch.Tensor )

						# Test not batched input
						UpperCAmelCase_:						Dict					=			image_processing(image_inputs[0],					return_tensors="""pt""" ).pixel_values

						UpperCAmelCase_:						Any					=			self.image_processor_tester.get_expected_values(__lowerCamelCase )

						self.assertEqual(
						    encoded_images.shape,					(1, self.image_processor_tester.num_channels, expected_height, expected_width),					)

						# Test batched
						UpperCAmelCase_:						Union[str, Any]					=			image_processing(__lowerCamelCase,					return_tensors="""pt""" ).pixel_values

						UpperCAmelCase_:						Dict					=			self.image_processor_tester.get_expected_values(__lowerCamelCase,					batched=__lowerCamelCase )

						self.assertEqual(
						    encoded_images.shape,					(
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        expected_height,
						        expected_width,
						    ),					)

			@slow
			def 			__snake_case    (self )    ->					Optional[Any]:
						UpperCAmelCase_:						int					=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
						with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""",					"""r""" ) as f:
									UpperCAmelCase_:						Dict					=			json.loads(f.read() )

						UpperCAmelCase_:						Any					=			{"image_id": 39769, "annotations": target}

						# encode them
						UpperCAmelCase_:						Union[str, Any]					=			DetaImageProcessor()
						UpperCAmelCase_:						List[str]					=			image_processing(images=__lowerCamelCase,					annotations=__lowerCamelCase,					return_tensors="""pt""" )

						# verify pixel values
						UpperCAmelCase_:						List[str]					=			torch.Size([1, 3, 800, 1066] )
						self.assertEqual(encoding["""pixel_values"""].shape,					__lowerCamelCase )

						UpperCAmelCase_:						Union[str, Any]					=			torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
						self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3],					__lowerCamelCase,					atol=1E-4 ) )

						# verify area
						UpperCAmelCase_:						Tuple					=			torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""],					__lowerCamelCase ) )
						# verify boxes
						UpperCAmelCase_:						Union[str, Any]					=			torch.Size([6, 4] )
						self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape,					__lowerCamelCase )
						UpperCAmelCase_:						List[Any]					=			torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0],					__lowerCamelCase,					atol=1E-3 ) )
						# verify image_id
						UpperCAmelCase_:						Optional[Any]					=			torch.tensor([39769] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""],					__lowerCamelCase ) )
						# verify is_crowd
						UpperCAmelCase_:						Dict					=			torch.tensor([0, 0, 0, 0, 0, 0] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""],					__lowerCamelCase ) )
						# verify class_labels
						UpperCAmelCase_:						int					=			torch.tensor([75, 75, 63, 65, 17, 17] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""],					__lowerCamelCase ) )
						# verify orig_size
						UpperCAmelCase_:						int					=			torch.tensor([480, 640] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""],					__lowerCamelCase ) )
						# verify size
						UpperCAmelCase_:						Optional[int]					=			torch.tensor([800, 1066] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""],					__lowerCamelCase ) )

			@slow
			def 			__snake_case    (self )    ->					Optional[int]:
						UpperCAmelCase_:						Union[str, Any]					=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
						with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""",					"""r""" ) as f:
									UpperCAmelCase_:						Tuple					=			json.loads(f.read() )

						UpperCAmelCase_:						List[str]					=			{"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}

						UpperCAmelCase_:						Union[str, Any]					=			pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" )

						# encode them
						UpperCAmelCase_:						Tuple					=			DetaImageProcessor(format="""coco_panoptic""" )
						UpperCAmelCase_:						Dict					=			image_processing(images=__lowerCamelCase,					annotations=__lowerCamelCase,					masks_path=__lowerCamelCase,					return_tensors="""pt""" )

						# verify pixel values
						UpperCAmelCase_:						List[Any]					=			torch.Size([1, 3, 800, 1066] )
						self.assertEqual(encoding["""pixel_values"""].shape,					__lowerCamelCase )

						UpperCAmelCase_:						Dict					=			torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
						self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3],					__lowerCamelCase,					atol=1E-4 ) )

						# verify area
						UpperCAmelCase_:						List[Any]					=			torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""],					__lowerCamelCase ) )
						# verify boxes
						UpperCAmelCase_:						Any					=			torch.Size([6, 4] )
						self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape,					__lowerCamelCase )
						UpperCAmelCase_:						int					=			torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0],					__lowerCamelCase,					atol=1E-3 ) )
						# verify image_id
						UpperCAmelCase_:						Optional[int]					=			torch.tensor([39769] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""],					__lowerCamelCase ) )
						# verify is_crowd
						UpperCAmelCase_:						Dict					=			torch.tensor([0, 0, 0, 0, 0, 0] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""],					__lowerCamelCase ) )
						# verify class_labels
						UpperCAmelCase_:						Tuple					=			torch.tensor([17, 17, 63, 75, 75, 93] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""],					__lowerCamelCase ) )
						# verify masks
						UpperCAmelCase_:						Union[str, Any]					=			822873
						self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item(),					__lowerCamelCase )
						# verify orig_size
						UpperCAmelCase_:						Optional[Any]					=			torch.tensor([480, 640] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""],					__lowerCamelCase ) )
						# verify size
						UpperCAmelCase_:						Union[str, Any]					=			torch.tensor([800, 1066] )
						self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""],					__lowerCamelCase ) )










from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
    from .deepspeed import (
        DeepSpeedEngineWrapper,
        DeepSpeedOptimizerWrapper,
        DeepSpeedSchedulerWrapper,
        DummyOptim,
        DummyScheduler,
        HfDeepSpeedConfig,
    )

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers


