"""simple docstring"""


# 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


__UpperCamelCase									=			'''Create a default config file for Accelerate with only a few flags set.'''







def 					UpperCAmelCase    (		UpperCAmelCase="no"						,					UpperCAmelCase = default_json_config_file						,					UpperCAmelCase = False					)				->      int:
     snake_case_					       =					Path(UpperCAmelCase					)
     path.parent.mkdir(parents=UpperCAmelCase						,					exist_ok=UpperCAmelCase					)
     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_					       =					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_					       =					{
         'compute_environment': 'LOCAL_MACHINE',
         'mixed_precision': mixed_precision,
     }
     if torch.cuda.is_available():
          snake_case_					       =					torch.cuda.device_count()
          snake_case_					       =					num_gpus
          snake_case_					       =					False
          if num_gpus > 1:
               snake_case_					       =					'MULTI_GPU'
          else:
               snake_case_					       =					'NO'
     elif is_xpu_available() and use_xpu:
          snake_case_					       =					torch.xpu.device_count()
          snake_case_					       =					num_xpus
          snake_case_					       =					False
          if num_xpus > 1:
               snake_case_					       =					'MULTI_XPU'
          else:
               snake_case_					       =					'NO'
     elif is_npu_available():
          snake_case_					       =					torch.npu.device_count()
          snake_case_					       =					num_npus
          snake_case_					       =					False
          if num_npus > 1:
               snake_case_					       =					'MULTI_NPU'
          else:
               snake_case_					       =					'NO'
     else:
          snake_case_					       =					0
          snake_case_					       =					True
          snake_case_					       =					1
          snake_case_					       =					'NO'
     snake_case_					       =					ClusterConfig(**UpperCAmelCase					)
     config.to_json_file(UpperCAmelCase					)
     return path







def 					UpperCAmelCase    (		UpperCAmelCase						,					UpperCAmelCase					)				->      Tuple:
     snake_case_					       =					parser.add_parser('default'						,					parents=UpperCAmelCase						,					help=UpperCAmelCase						,					formatter_class=UpperCAmelCase					)
     parser.add_argument(
         '--config_file'						,					default=UpperCAmelCase						,					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=UpperCAmelCase						,					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=UpperCAmelCase					)
     return parser







def 					UpperCAmelCase    (		UpperCAmelCase					)				->      Tuple:
     snake_case_					       =					write_basic_config(args.mixed_precision						,					args.save_location					)
     if config_file:
          print(f'accelerate configuration saved at {config_file}'					)





from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_tf_available():
 import tensorflow as tf

 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
 from ..tf_utils import stable_softmax

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

SCREAMING_SNAKE_CASE       :      List[str]												= logging.get_logger(__name__)






@add_end_docstrings(_a   )
class _lowerCamelCase(						_a   ):
       def __init__(					self,      *lowerCamelCase,      **lowerCamelCase)       ->   int:




           """simple docstring"""

           super().__init__(*lowerCamelCase,      **lowerCamelCase)
           requires_backends(self,      'vision')
           self.check_model_type(
               TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
               if self.framework == 'tf'
               else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING)
       def 			UpperCamelCase     (					self,      lowerCamelCase=None)       ->   int:




           """simple docstring"""

           _lowercase       :							Dict      		=		{}
           if top_k is not None:
               _lowercase       :							List[str]      		=		top_k
           return {}, {}, postprocess_params
       def __call__(					self,      lowerCamelCase,      **lowerCamelCase)       ->   Tuple:




           """simple docstring"""

           return super().__call__(lowerCamelCase,      **lowerCamelCase)
       def 			UpperCamelCase     (					self,      lowerCamelCase)       ->   str:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		load_image(lowerCamelCase)
           _lowercase       :							List[str]      		=		self.image_processor(images=lowerCamelCase,      return_tensors=self.framework)
           return model_inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase)       ->   List[str]:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		self.model(**lowerCamelCase)
           return model_outputs




       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase=5)       ->   Dict:




           """simple docstring"""

           if top_k > self.model.config.num_labels:
               _lowercase       :							List[Any]      		=		self.model.config.num_labels

           if self.framework == "pt":
               _lowercase       :							int      		=		model_outputs.logits.softmax(-1)[0]
               _lowercase		,				_lowercase       :							Union[str, Any]      		=		probs.topk(lowerCamelCase)
           elif self.framework == "tf":
               _lowercase       :							int      		=		stable_softmax(model_outputs.logits,      axis=-1)[0]
               _lowercase       :							List[Any]      		=		tf.math.top_k(lowerCamelCase,      k=lowerCamelCase)
               _lowercase		,				_lowercase       :							Any      		=		topk.values.numpy(), topk.indices.numpy()
           else:
               raise ValueError(F'''Unsupported framework: {self.framework}''')

           _lowercase       :							str      		=		scores.tolist()
           _lowercase       :							str      		=		ids.tolist()
           return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase,      lowerCamelCase)]


