



"""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


SCREAMING_SNAKE_CASE_				= """Create a default config file for Accelerate with only a few flags set."""



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__="no", SCREAMING_SNAKE_CASE__ = default_json_config_file, SCREAMING_SNAKE_CASE__ = False	)			->      Tuple:
		a_     :      Union[str, Any] 						=     Path(SCREAMING_SNAKE_CASE__	)
		path.parent.mkdir(parents=SCREAMING_SNAKE_CASE__, exist_ok=SCREAMING_SNAKE_CASE__	)
		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
		a_     :      Optional[int] 						=     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}"""	)
		a_     :      str 						=     {
		    "compute_environment": "LOCAL_MACHINE",
		    "mixed_precision": mixed_precision,
		}
		if torch.cuda.is_available():
				a_     :      int 						=     torch.cuda.device_count()
				a_     :      Optional[Any] 						=     num_gpus
				a_     :      int 						=     False
				if num_gpus > 1:
						a_     :      Any 						=     "MULTI_GPU"
				else:
						a_     :      int 						=     "NO"
		elif is_xpu_available() and use_xpu:
				a_     :      int 						=     torch.xpu.device_count()
				a_     :      str 						=     num_xpus
				a_     :      Tuple 						=     False
				if num_xpus > 1:
						a_     :      int 						=     "MULTI_XPU"
				else:
						a_     :      List[str] 						=     "NO"
		elif is_npu_available():
				a_     :      List[Any] 						=     torch.npu.device_count()
				a_     :      int 						=     num_npus
				a_     :      List[Any] 						=     False
				if num_npus > 1:
						a_     :      str 						=     "MULTI_NPU"
				else:
						a_     :      Union[str, Any] 						=     "NO"
		else:
				a_     :      Optional[Any] 						=     0
				a_     :      Optional[Any] 						=     True
				a_     :      Tuple 						=     1
				a_     :      Optional[int] 						=     "NO"
		a_     :      str 						=     ClusterConfig(**SCREAMING_SNAKE_CASE__	)
		config.to_json_file(SCREAMING_SNAKE_CASE__	)
		return path



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__	)			->      Optional[Any]:
		a_     :      Dict 						=     parser.add_parser("default", parents=SCREAMING_SNAKE_CASE__, help=SCREAMING_SNAKE_CASE__, formatter_class=SCREAMING_SNAKE_CASE__	)
		parser.add_argument(
		    "--config_file", default=SCREAMING_SNAKE_CASE__, 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=SCREAMING_SNAKE_CASE__, 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=SCREAMING_SNAKE_CASE__	)
		return parser



def        lowerCAmelCase_						(							SCREAMING_SNAKE_CASE__	)			->      Tuple:
		a_     :      Any 						=     write_basic_config(args.mixed_precision, args.save_location	)
		if config_file:
				print(F"""accelerate configuration saved at {config_file}"""	)




"""simple docstring"""
import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType




class 			snake_case_						(						a_				):
							__lowerCAmelCase    					=					["image_processor", "tokenizer"]
							__lowerCAmelCase    					=					"ViltImageProcessor"
							__lowerCAmelCase    					=					("BertTokenizer", "BertTokenizerFast")






							def __init__(   self			,     a_=None			,     a_=None			,     **a_      ):
									a_     :      int 						=     None
									if "feature_extractor" in kwargs:
											warnings.warn(
											    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
											    " instead."			,     a_			,     )
											a_     :      List[Any] 						=     kwargs.pop("feature_extractor"      )

									a_     :      List[str] 						=     image_processor if image_processor is not None else feature_extractor
									if image_processor is None:
											raise ValueError("You need to specify an `image_processor`."      )
									if tokenizer is None:
											raise ValueError("You need to specify a `tokenizer`."      )

									super().__init__(a_			,     a_      )
									a_     :      Dict 						=     self.image_processor






							def __call__(   self			,     a_			,     a_ = None			,     a_ = True			,     a_ = False			,     a_ = None			,     a_ = None			,     a_ = 0			,     a_ = None			,     a_ = None			,     a_ = None			,     a_ = False			,     a_ = False			,     a_ = False			,     a_ = False			,     a_ = True			,     a_ = None			,     **a_			,     ):
									a_     :      Union[str, Any] 						=     self.tokenizer(
									    text=a_			,     add_special_tokens=a_			,     padding=a_			,     truncation=a_			,     max_length=a_			,     stride=a_			,     pad_to_multiple_of=a_			,     return_token_type_ids=a_			,     return_attention_mask=a_			,     return_overflowing_tokens=a_			,     return_special_tokens_mask=a_			,     return_offsets_mapping=a_			,     return_length=a_			,     verbose=a_			,     return_tensors=a_			,     **a_			,     )
									# add pixel_values + pixel_mask
									a_     :      List[Any] 						=     self.image_processor(a_			,     return_tensors=a_      )
									encoding.update(a_      )

									return encoding






							def snake_case_  (   self			,     *a_			,     **a_      ):
									return self.tokenizer.batch_decode(*a_			,     **a_      )






							def snake_case_  (   self			,     *a_			,     **a_      ):
									return self.tokenizer.decode(*a_			,     **a_      )






							@property
							def snake_case_  (   self      ):
									a_     :      Union[str, Any] 						=     self.tokenizer.model_input_names
									a_     :      Dict 						=     self.image_processor.model_input_names
									return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names      )      )






							@property
							def snake_case_  (   self      ):
									warnings.warn(
									    "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."			,     a_			,     )
									return self.image_processor_class






							@property
							def snake_case_  (   self      ):
									warnings.warn(
									    "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."			,     a_			,     )
									return self.image_processor