



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


lowercase_      :				List[Any]   					=    '''Create a default config file for Accelerate with only a few flags set.'''







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







def      SCREAMING_SNAKE_CASE				(				lowercase_    :      str ,  lowercase_    :      Optional[Any]						):
						lowercase        =							parser.add_parser("""default""" ,  parents=lowercase_ ,  help=lowercase_ ,  formatter_class=lowercase_						)
						parser.add_argument(
						    """--config_file""" ,  default=lowercase_ ,  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=lowercase_ ,  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=lowercase_						)
						return parser







def      SCREAMING_SNAKE_CASE				(				lowercase_    :      int						):
						lowercase        =							write_basic_config(args.mixed_precision ,  args.save_location						)
						if config_file:
												print(F"""accelerate configuration saved at {config_file}"""						)







'''simple docstring'''


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():
						from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
						import torch

						from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

lowercase_      :				Union[str, Any]   					=    logging.get_logger(__name__)




@add_end_docstrings(_UpperCAmelCase			)
class      __UpperCamelCase       (_UpperCAmelCase			):







	def __init__(    self ,				*_lowerCAmelCase ,				**_lowerCAmelCase						)    ->    Dict:
							'''simple docstring'''






							super().__init__(*_lowerCAmelCase ,				**_lowerCAmelCase						)
							requires_backends(self ,				"""vision"""						)
							self.check_model_type(
							    TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING						)







	def   _a   (    self ,				_lowerCAmelCase=None ,				_lowerCAmelCase=None ,				_lowerCAmelCase=None						)    ->    str:
							'''simple docstring'''






							lowercase        =							{}
							lowercase        =							{}

							if prompt is not None:
													lowercase        =							prompt

							if generate_kwargs is not None:
													lowercase        =							generate_kwargs
							if max_new_tokens is not None:
													if "generate_kwargs" not in forward_kwargs:
																			lowercase        =							{}
													if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
																			raise ValueError(
																			    """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,"""
																			    """ please use only one"""						)
													lowercase        =							max_new_tokens
							return preprocess_params, forward_kwargs, {}







	def __call__(    self ,				_lowerCAmelCase ,				**_lowerCAmelCase						)    ->    Any:
							'''simple docstring'''






							return super().__call__(_lowerCAmelCase ,				**_lowerCAmelCase						)







	def   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase=None						)    ->    List[str]:
							'''simple docstring'''






							lowercase        =							load_image(_lowerCAmelCase						)

							if prompt is not None:
													if not isinstance(_lowerCAmelCase ,				_lowerCAmelCase						):
																			raise ValueError(
																			    F"""Received an invalid text input, got - {type(_lowerCAmelCase						)} - but expected a single string. """
																			    """Note also that one single text can be provided for conditional image to text generation."""						)

													lowercase        =							self.model.config.model_type

													if model_type == "git":
																			lowercase        =							self.image_processor(images=_lowerCAmelCase ,				return_tensors=self.framework						)
																			lowercase        =							self.tokenizer(text=_lowerCAmelCase ,				add_special_tokens=_lowerCAmelCase						).input_ids
																			lowercase        =							[self.tokenizer.cls_token_id] + input_ids
																			lowercase        =							torch.tensor(_lowerCAmelCase						).unsqueeze(0						)
																			model_inputs.update({"""input_ids""": input_ids}						)

													elif model_type == "pix2struct":
																			lowercase        =							self.image_processor(images=_lowerCAmelCase ,				header_text=_lowerCAmelCase ,				return_tensors=self.framework						)

													elif model_type != "vision-encoder-decoder":
																			# vision-encoder-decoder does not support conditional generation
																			lowercase        =							self.image_processor(images=_lowerCAmelCase ,				return_tensors=self.framework						)
																			lowercase        =							self.tokenizer(_lowerCAmelCase ,				return_tensors=self.framework						)
																			model_inputs.update(_lowerCAmelCase						)

													else:
																			raise ValueError(F"""Model type {model_type} does not support conditional text generation"""						)

							else:
													lowercase        =							self.image_processor(images=_lowerCAmelCase ,				return_tensors=self.framework						)

							if self.model.config.model_type == "git" and prompt is None:
													lowercase        =							None

							return model_inputs







	def   _a   (    self ,				_lowerCAmelCase ,				_lowerCAmelCase=None						)    ->    Union[str, Any]:
							'''simple docstring'''






							if (
							    "input_ids" in model_inputs
							    and isinstance(model_inputs["""input_ids"""] ,				_lowerCAmelCase						)
							    and all(x is None for x in model_inputs["""input_ids"""]						)
							):
													lowercase        =							None

							if generate_kwargs is None:
													lowercase        =							{}
							# FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
							#  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
							#  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
							#  in the `_prepare_model_inputs` method.
							lowercase        =							model_inputs.pop(self.model.main_input_name						)
							lowercase        =							self.model.generate(_lowerCAmelCase ,				**_lowerCAmelCase ,				**_lowerCAmelCase						)
							return model_outputs







	def   _a   (    self ,				_lowerCAmelCase						)    ->    List[str]:
							'''simple docstring'''






							lowercase        =							[]
							for output_ids in model_outputs:
													lowercase        =							{
													    """generated_text""": self.tokenizer.decode(
													        _lowerCAmelCase ,				skip_special_tokens=_lowerCAmelCase ,				)
													}
													records.append(_lowerCAmelCase						)
							return records


