






# 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.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


__lowerCamelCase	:		Union[str, Any]										=   """Create a default config file for Accelerate with only a few flags set."""







def 			A__							(      _a  :					int="no"		,  _a  :					str = default_json_config_file		,  _a  :					bool = False	):





 '''simple docstring'''







 snake_case__  :    List[str]							       =Path(_a	)
 path.parent.mkdir(parents=_a		,  exist_ok=_a	)
 if path.exists():
  print(
      f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`."	)
  return False
 snake_case__  :    List[Any]							       =mixed_precision.lower()
 if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
  raise ValueError(
      f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}"	)
 snake_case__  :    Tuple							       ={
     """compute_environment""": """LOCAL_MACHINE""",
     """mixed_precision""": mixed_precision,
 }
 if torch.cuda.is_available():
  snake_case__  :    str							       =torch.cuda.device_count()
  snake_case__  :    Any							       =num_gpus
  snake_case__  :    str							       =False
  if num_gpus > 1:
   snake_case__  :    Optional[int]							       ="""MULTI_GPU"""
  else:
   snake_case__  :    List[Any]							       ="""NO"""
 elif is_xpu_available() and use_xpu:
  snake_case__  :    Any							       =torch.xpu.device_count()
  snake_case__  :    Optional[Any]							       =num_xpus
  snake_case__  :    str							       =False
  if num_xpus > 1:
   snake_case__  :    List[str]							       ="""MULTI_XPU"""
  else:
   snake_case__  :    int							       ="""NO"""
 elif is_npu_available():
  snake_case__  :    List[str]							       =torch.npu.device_count()
  snake_case__  :    Dict							       =num_npus
  snake_case__  :    Optional[int]							       =False
  if num_npus > 1:
   snake_case__  :    Any							       ="""MULTI_NPU"""
  else:
   snake_case__  :    Tuple							       ="""NO"""
 else:
  snake_case__  :    str							       =0
  snake_case__  :    int							       =True
  snake_case__  :    int							       =1
  snake_case__  :    str							       ="""NO"""
 snake_case__  :    Union[str, Any]							       =ClusterConfig(**_a	)
 config.to_json_file(_a	)
 return path







def 			A__							(      _a  :					Optional[int]		,  _a  :					str	):





 '''simple docstring'''







 snake_case__  :    Optional[int]							       =parser.add_parser("""default"""		,  parents=_a		,  help=_a		,  formatter_class=_a	)
 parser.add_argument(
     """--config_file"""		,  default=_a		,  help=(
         """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
         """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
         """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
         """with 'huggingface'."""
     )		,  dest="""save_location"""		,  )

 parser.add_argument(
     """--mixed_precision"""		,  choices=["""no""", """fp16""", """bf16"""]		,  type=_a		,  help="""Whether or not to use mixed precision training. """
     """Choose between FP16 and BF16 (bfloat16) training. """
     """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""		,  default="""no"""		,  )
 parser.set_defaults(func=_a	)
 return parser







def 			A__							(      _a  :					List[str]	):





 '''simple docstring'''







 snake_case__  :    Optional[Any]							       =write_basic_config(args.mixed_precision		,  args.save_location	)
 if config_file:
  print(f"accelerate configuration saved at {config_file}"	)













from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__lowerCamelCase	:		Tuple										=   logging.get_logger(__name__)







class  _lowercase   (   _A						):
      _a							:						Optional[int]										=							['pixel_values']
      def __init__(     self				,			a = True				,			a = 3_2				,			a=PILImageResampling.BILINEAR				,			a = True				,			**a				,			):
       snake_case__  :    Any							       =do_resize
       snake_case__  :    Optional[int]							       =do_rescale
       snake_case__  :    Optional[Any]							       =size_divisor
       snake_case__  :    Optional[int]							       =resample
       super().__init__(**a   )
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a = None				,			**a   ):
       snake_case__       ,   snake_case__  :    List[str]							       =get_image_size(a   )
       # Rounds the height and width down to the closest multiple of size_divisor
       snake_case__  :    str							       =height // size_divisor * size_divisor
       snake_case__  :    List[str]							       =width // size_divisor * size_divisor
       snake_case__  :    int							       =resize(a				,			(new_h, new_w)				,			resample=a				,			data_format=a				,			**a   )
       return image
      def 						lowercase__					(     self				,			a				,			a				,			a = None				,			**a   ):
       return rescale(image=a				,			scale=a				,			data_format=a				,			**a   )



      def 						lowercase__					(     self				,			a				,			a = None				,			a = None				,			a=None				,			a = None				,			a = None				,			a = ChannelDimension.FIRST				,			**a				,			):
       snake_case__  :    Optional[Any]							       =do_resize if do_resize is not None else self.do_resize
       snake_case__  :    str							       =do_rescale if do_rescale is not None else self.do_rescale
       snake_case__  :    List[Any]							       =size_divisor if size_divisor is not None else self.size_divisor
       snake_case__  :    Optional[int]							       =resample if resample is not None else self.resample

       if do_resize and size_divisor is None:
        raise ValueError("""size_divisor is required for resizing"""   )

       snake_case__  :    Optional[int]							       =make_list_of_images(a   )

       if not valid_images(a   ):
        raise ValueError("""Invalid image(s)"""   )

       # All transformations expect numpy arrays.
       snake_case__  :    str							       =[to_numpy_array(a   ) for img in images]

       if do_resize:
        snake_case__  :    str							       =[self.resize(a				,			size_divisor=a				,			resample=a   ) for image in images]

       if do_rescale:
        snake_case__  :    Union[str, Any]							       =[self.rescale(a				,			scale=1 / 2_5_5   ) for image in images]

       snake_case__  :    int							       =[to_channel_dimension_format(a				,			a   ) for image in images]

       snake_case__  :    Tuple							       ={"""pixel_values""": images}
       return BatchFeature(data=a				,			tensor_type=a   )





