






# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_UpperCAmelCase					:						Union[str, Any]         =     os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
_UpperCAmelCase					:						List[str]         =     os.path.join(hf_cache_home, 'accelerate')
_UpperCAmelCase					:						Dict         =     os.path.join(cache_dir, 'default_config.yaml')
_UpperCAmelCase					:						Dict         =     os.path.join(cache_dir, 'default_config.yaml')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
   _UpperCAmelCase					:						Dict         =     default_yaml_config_file
else:
   _UpperCAmelCase					:						Optional[int]         =     default_json_config_file






def  UpperCAmelCase__						(    lowerCamelCase	:			List[Any]    ):
   if config_file is not None:
      if not os.path.isfile(lowerCamelCase    ):
         raise FileNotFoundError(
             f'''The passed configuration file `{config_file}` does not exist. '''
             """Please pass an existing file to `accelerate launch`, or use the the default one """
             """created through `accelerate config` and run `accelerate launch` """
             """without the `--config_file` argument."""    )
   else:
      lowerCamelCase									=default_config_file
   with open(lowerCamelCase			,"""r"""			,encoding="""utf-8"""    ) as f:
      if config_file.endswith(""".json"""    ):
         if (
             json.load(lowerCamelCase    ).get("""compute_environment"""			,ComputeEnvironment.LOCAL_MACHINE    )
             == ComputeEnvironment.LOCAL_MACHINE
         ):
            lowerCamelCase									=ClusterConfig
         else:
            lowerCamelCase									=SageMakerConfig
         return config_class.from_json_file(json_file=lowerCamelCase    )
      else:
         if (
             yaml.safe_load(lowerCamelCase    ).get("""compute_environment"""			,ComputeEnvironment.LOCAL_MACHINE    )
             == ComputeEnvironment.LOCAL_MACHINE
         ):
            lowerCamelCase									=ClusterConfig
         else:
            lowerCamelCase									=SageMakerConfig
         return config_class.from_yaml_file(yaml_file=lowerCamelCase    )


@dataclass
class 		lowerCAmelCase_				:
     __lowerCamelCase       :    ComputeEnvironment
     __lowerCamelCase       :    Union[DistributedType, SageMakerDistributedType]
     __lowerCamelCase       :    str
     __lowerCamelCase       :    bool





     def 						lowerCamelCase							(	self  )		->				Any:
        lowerCamelCase									=self.__dict__
        # For serialization, it's best to convert Enums to strings (or their underlying value type).
        for key, value in result.items():
           if isinstance(_UpperCAmelCase							, _UpperCAmelCase  ):
              lowerCamelCase									=value.value
           if isinstance(_UpperCAmelCase							, _UpperCAmelCase  ) and not bool(_UpperCAmelCase  ):
              lowerCamelCase									=None
        lowerCamelCase									={k: v for k, v in result.items() if v is not None}
        return result





     @classmethod
     def 						lowerCamelCase							(	cls							, _UpperCAmelCase=None  )		->				Optional[int]:
        lowerCamelCase									=default_json_config_file if json_file is None else json_file
        with open(_UpperCAmelCase							, """r"""							, encoding="""utf-8"""  ) as f:
           lowerCamelCase									=json.load(_UpperCAmelCase  )
        if "compute_environment" not in config_dict:
           lowerCamelCase									=ComputeEnvironment.LOCAL_MACHINE
        if "mixed_precision" not in config_dict:
           lowerCamelCase									="""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
        if "fp16" in config_dict:  # Convert the config to the new format.
           del config_dict["fp16"]
        if "dynamo_backend" in config_dict:  # Convert the config to the new format.
           lowerCamelCase									=config_dict.pop("""dynamo_backend"""  )
           lowerCamelCase									={} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
        if "use_cpu" not in config_dict:
           lowerCamelCase									=False
        return cls(**_UpperCAmelCase  )





     def 						lowerCamelCase							(	self							, _UpperCAmelCase  )		->				Optional[Any]:
        with open(_UpperCAmelCase							, """w"""							, encoding="""utf-8"""  ) as f:
           lowerCamelCase									=json.dumps(self.to_dict()							, indent=2							, sort_keys=_UpperCAmelCase  ) + """\n"""
           f.write(_UpperCAmelCase  )





     @classmethod
     def 						lowerCamelCase							(	cls							, _UpperCAmelCase=None  )		->				str:
        lowerCamelCase									=default_yaml_config_file if yaml_file is None else yaml_file
        with open(_UpperCAmelCase							, """r"""							, encoding="""utf-8"""  ) as f:
           lowerCamelCase									=yaml.safe_load(_UpperCAmelCase  )
        if "compute_environment" not in config_dict:
           lowerCamelCase									=ComputeEnvironment.LOCAL_MACHINE

        if "mixed_precision" not in config_dict:
           lowerCamelCase									="""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
        if isinstance(config_dict["""mixed_precision"""]							, _UpperCAmelCase  ) and not config_dict["mixed_precision"]:
           lowerCamelCase									="""no"""
        if "fp16" in config_dict:  # Convert the config to the new format.
           del config_dict["fp16"]
        if "dynamo_backend" in config_dict:  # Convert the config to the new format.
           lowerCamelCase									=config_dict.pop("""dynamo_backend"""  )
           lowerCamelCase									={} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
        if "use_cpu" not in config_dict:
           lowerCamelCase									=False
        return cls(**_UpperCAmelCase  )





     def 						lowerCamelCase							(	self							, _UpperCAmelCase  )		->				Any:
        with open(_UpperCAmelCase							, """w"""							, encoding="""utf-8"""  ) as f:
           yaml.safe_dump(self.to_dict()							, _UpperCAmelCase  )





     def 						lowerCamelCase							(	self  )		->				Dict:
        if isinstance(self.compute_environment							, _UpperCAmelCase  ):
           lowerCamelCase									=ComputeEnvironment(self.compute_environment  )
        if isinstance(self.distributed_type							, _UpperCAmelCase  ):
           if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
              lowerCamelCase									=SageMakerDistributedType(self.distributed_type  )
           else:
              lowerCamelCase									=DistributedType(self.distributed_type  )
        if self.dynamo_config is None:
           lowerCamelCase									={}




@dataclass
class 		lowerCAmelCase_				(  UpperCamelCase ):
     __lowerCamelCase       :    int
     __lowerCamelCase       :    int 	=     0
     __lowerCamelCase       :    int 	=     1
     __lowerCamelCase       :    Optional[str] 	=     None
     __lowerCamelCase       :    Optional[str] 	=     None
     __lowerCamelCase       :    Optional[int] 	=     None
     __lowerCamelCase       :    Optional[str] 	=     "static"
     __lowerCamelCase       :    Optional[bool] 	=     False
     __lowerCamelCase       :    str 	=     "main"

     # args for deepspeed_plugin
     __lowerCamelCase       :    dict 	=     None
     # args for fsdp
     __lowerCamelCase       :    dict 	=     None
     # args for megatron_lm
     __lowerCamelCase       :    dict 	=     None
     # args for ipex
     __lowerCamelCase       :    dict 	=     None
     # args for TPU
     __lowerCamelCase       :    bool 	=     False

     # args for TPU pods
     __lowerCamelCase       :    str 	=     None
     __lowerCamelCase       :    str 	=     None
     __lowerCamelCase       :    bool 	=     False
     __lowerCamelCase       :    bool 	=     False
     __lowerCamelCase       :    str 	=     None
     __lowerCamelCase       :    List[str] 	=     None
     __lowerCamelCase       :    List[str] 	=     None
     __lowerCamelCase       :    List[str] 	=     None

     # args for dynamo
     __lowerCamelCase       :    dict 	=     None





     def 						lowerCamelCase							(	self  )		->				Tuple:
        if self.deepspeed_config is None:
           lowerCamelCase									={}
        if self.fsdp_config is None:
           lowerCamelCase									={}
        if self.megatron_lm_config is None:
           lowerCamelCase									={}
        if self.ipex_config is None:
           lowerCamelCase									={}
        return super().__post_init__()




@dataclass
class 		lowerCAmelCase_				(  UpperCamelCase ):
     __lowerCamelCase       :    str
     __lowerCamelCase       :    str
     __lowerCamelCase       :    Optional[str] 	=     None
     __lowerCamelCase       :    Optional[str] 	=     None
     __lowerCamelCase       :    str 	=     "us-east-1"
     __lowerCamelCase       :    int 	=     1
     __lowerCamelCase       :    str 	=     "all"
     __lowerCamelCase       :    str 	=     f'''accelerate-sagemaker-{num_machines}'''
     __lowerCamelCase       :    str 	=     SAGEMAKER_PYTORCH_VERSION
     __lowerCamelCase       :    str 	=     SAGEMAKER_TRANSFORMERS_VERSION
     __lowerCamelCase       :    str 	=     SAGEMAKER_PYTHON_VERSION
     __lowerCamelCase       :    str 	=     None
     __lowerCamelCase       :    str 	=     None
     __lowerCamelCase       :    dict 	=     None
     __lowerCamelCase       :    dict 	=     None







import unittest

import numpy as np

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

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import BlipImageProcessor


class 		lowerCAmelCase_				(  unittest.TestCase ):





     def __init__(	self							, _UpperCAmelCase							, _UpperCAmelCase=7							, _UpperCAmelCase=3							, _UpperCAmelCase=18							, _UpperCAmelCase=30							, _UpperCAmelCase=400							, _UpperCAmelCase=True							, _UpperCAmelCase=None							, _UpperCAmelCase=True							, _UpperCAmelCase=False							, _UpperCAmelCase=[0.48145466, 0.4578275, 0.40821073]							, _UpperCAmelCase=[0.26862954, 0.26130258, 0.27577711]							, _UpperCAmelCase=True							, )		->				List[str]:
        lowerCamelCase									=size if size is not None else {"""height""": 20, """width""": 20}
        lowerCamelCase									=parent
        lowerCamelCase									=batch_size
        lowerCamelCase									=num_channels
        lowerCamelCase									=image_size
        lowerCamelCase									=min_resolution
        lowerCamelCase									=max_resolution
        lowerCamelCase									=do_resize
        lowerCamelCase									=size
        lowerCamelCase									=do_normalize
        lowerCamelCase									=image_mean
        lowerCamelCase									=image_std
        lowerCamelCase									=do_pad
        lowerCamelCase									=do_convert_rgb





     def 						lowerCamelCase							(	self  )		->				str:
        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_convert_rgb": self.do_convert_rgb,
            "do_pad": self.do_pad,
        }





     def 						lowerCamelCase							(	self							, _UpperCAmelCase=False							, _UpperCAmelCase=False							, _UpperCAmelCase=False  )		->				Optional[int]:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
           lowerCamelCase									=[]
           for i in range(self.batch_size  ):
              image_inputs.append(
                  np.random.randint(
                      255							, size=(self.num_channels, self.max_resolution, self.max_resolution)							, dtype=np.uinta  )  )
        else:
           lowerCamelCase									=[]
           for i in range(self.batch_size  ):
              lowerCamelCase				,       lowerCamelCase									=np.random.choice(np.arange(self.min_resolution							, self.max_resolution  )							, 2  )
              image_inputs.append(np.random.randint(255							, size=(self.num_channels, width, height)							, dtype=np.uinta  )  )

        if not numpify and not torchify:
           # PIL expects the channel dimension as last dimension
           lowerCamelCase									=[Image.fromarray(np.moveaxis(_UpperCAmelCase							, 0							, -1  )  ) for x in image_inputs]

        if torchify:
           lowerCamelCase									=[torch.from_numpy(_UpperCAmelCase  ) for x in image_inputs]

        return image_inputs




@require_torch
@require_vision
class 		lowerCAmelCase_				(  UpperCamelCase				,     unittest.TestCase ):
     __lowerCamelCase       :    str 	=     BlipImageProcessor if is_vision_available() else None





     def 						lowerCamelCase							(	self  )		->				Dict:
        lowerCamelCase									=BlipImageProcessingTester(self  )





     @property
     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        return self.image_processor_tester.prepare_image_processor_dict()





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_resize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """size"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_normalize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_mean"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_std"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_convert_rgb"""  )  )





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        pass





     def 						lowerCamelCase							(	self  )		->				int:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PIL images
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, Image.Image  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )





     def 						lowerCamelCase							(	self  )		->				Union[str, Any]:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random numpy tensors
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase							, numpify=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, np.ndarray  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )





     def 						lowerCamelCase							(	self  )		->				Optional[Any]:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PyTorch tensors
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase							, torchify=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, torch.Tensor  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )




@require_torch
@require_vision
class 		lowerCAmelCase_				(  UpperCamelCase				,     unittest.TestCase ):
     __lowerCamelCase       :    Any 	=     BlipImageProcessor if is_vision_available() else None





     def 						lowerCamelCase							(	self  )		->				Optional[int]:
        lowerCamelCase									=BlipImageProcessingTester(self							, num_channels=4  )
        lowerCamelCase									=3





     @property
     def 						lowerCamelCase							(	self  )		->				Any:
        return self.image_processor_tester.prepare_image_processor_dict()





     def 						lowerCamelCase							(	self  )		->				List[str]:
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_resize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """size"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_normalize"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_mean"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """image_std"""  )  )
        self.assertTrue(hasattr(_UpperCAmelCase							, """do_convert_rgb"""  )  )





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





     def 						lowerCamelCase							(	self  )		->				List[Any]:
        # Initialize image_processor
        lowerCamelCase									=self.image_processing_class(**self.image_processor_dict  )
        # create random PIL images
        lowerCamelCase									=self.image_processor_tester.prepare_inputs(equal_resolution=_UpperCAmelCase  )
        for image in image_inputs:
           self.assertIsInstance(_UpperCAmelCase							, Image.Image  )

        # Test not batched input
        lowerCamelCase									=image_processor(image_inputs[0]							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                1,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )

        # Test batched
        lowerCamelCase									=image_processor(_UpperCAmelCase							, return_tensors="""pt"""  ).pixel_values
        self.assertEqual(
            encoded_images.shape							, (
                self.image_processor_tester.batch_size,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )							, )