






# 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_ :						Any      =      '''Create a default config file for Accelerate with only a few flags set.'''

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[int]="no"	,			__magic_name__					:  str = default_json_config_file	,			__magic_name__					:  bool = False					)		->			str:






	"""simple docstring"""



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

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Tuple					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	parser.add_parser("""default"""	,			parents=__magic_name__	,			help=__magic_name__	,			formatter_class=__magic_name__					)
	parser.add_argument(
	    """--config_file"""	,			default=__magic_name__	,			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=__magic_name__	,			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=__magic_name__					)
	return parser

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			List[str]:






	"""simple docstring"""



	UpperCamelCase     :Optional[Any]          =	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 Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
    import tensorflow as tf

    from ..tf_utils import stable_softmax


if is_torch_available():
    import torch


SCREAMING_SNAKE_CASE_:     Optional[int]  =logging.get_logger(__name__)




@add_end_docstrings(
    UpperCamelCase__		,	r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """		,	)
class        __A      ( UpperCamelCase__	):



    def 					_lowercase						(self    :    str   ,			__a    :    GenericTensor ):
         if self.framework == "tf":
              UpperCAmelCase_           =   tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
         elif self.framework == "pt":
              UpperCAmelCase_           =   torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,			as_tuple=__a )
         else:
              raise ValueError("Unsupported framework" )
         return masked_index



    def 					_lowercase						(self    :    Tuple   ,			__a    :    GenericTensor ):
         UpperCAmelCase_           =   self.get_masked_index(__a )
         UpperCAmelCase_           =   np.prod(masked_index.shape )
         if numel < 1:
              raise PipelineException(
                  "fill-mask"   ,			self.model.base_model_prefix   ,			f"""No mask_token ({self.tokenizer.mask_token}) found on the input"""   ,			)



    def 					_lowercase						(self    :    List[Any]   ,			__a    :    GenericTensor ):
         if isinstance(__a   ,			__a ):
              for model_input in model_inputs:
                   self._ensure_exactly_one_mask_token(model_input["input_ids"][0] )
         else:
              for input_ids in model_inputs["input_ids"]:
                   self._ensure_exactly_one_mask_token(__a )



    def 					_lowercase						(self    :    Tuple   ,			__a    :    Dict   ,			__a    :    List[str]=None   ,			**__a    :    Any ):
         if return_tensors is None:
              UpperCAmelCase_           =   self.framework
         UpperCAmelCase_           =   self.tokenizer(__a   ,			return_tensors=__a )
         self.ensure_exactly_one_mask_token(__a )
         return model_inputs



    def 					_lowercase						(self    :    str   ,			__a    :    Optional[int] ):
         UpperCAmelCase_           =   self.model(**__a )
         UpperCAmelCase_           =   model_inputs["input_ids"]
         return model_outputs



    def 					_lowercase						(self    :    List[str]   ,			__a    :    Tuple   ,			__a    :    int=5   ,			__a    :    Dict=None ):
         # Cap top_k if there are targets
         if target_ids is not None and target_ids.shape[0] < top_k:
              UpperCAmelCase_           =   target_ids.shape[0]
         UpperCAmelCase_           =   model_outputs["input_ids"][0]
         UpperCAmelCase_           =   model_outputs["logits"]

         if self.framework == "tf":
              UpperCAmelCase_           =   tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]

              UpperCAmelCase_           =   outputs.numpy()

              UpperCAmelCase_           =   outputs[0, masked_index, :]
              UpperCAmelCase_           =   stable_softmax(__a   ,			axis=-1 )
              if target_ids is not None:
                   UpperCAmelCase_           =   tf.gather_nd(tf.squeeze(__a   ,			0 )   ,			target_ids.reshape(-1   ,			1 ) )
                   UpperCAmelCase_           =   tf.expand_dims(__a   ,			0 )

              UpperCAmelCase_           =   tf.math.top_k(__a   ,			k=__a )
              UpperCAmelCase_    , UpperCAmelCase_           =   topk.values.numpy(), topk.indices.numpy()
         else:
              UpperCAmelCase_           =   torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,			as_tuple=__a ).squeeze(-1 )
              # Fill mask pipeline supports only one ${mask_token} per sample

              UpperCAmelCase_           =   outputs[0, masked_index, :]
              UpperCAmelCase_           =   logits.softmax(dim=-1 )
              if target_ids is not None:
                   UpperCAmelCase_           =   probs[..., target_ids]

              UpperCAmelCase_    , UpperCAmelCase_           =   probs.topk(__a )

         UpperCAmelCase_           =   []
         UpperCAmelCase_           =   values.shape[0] == 1
         for i, (_values, _predictions) in enumerate(zip(values.tolist()   ,			predictions.tolist() ) ):
              UpperCAmelCase_           =   []
              for v, p in zip(_values   ,			_predictions ):
                   # Copy is important since we're going to modify this array in place
                   UpperCAmelCase_           =   input_ids.numpy().copy()
                   if target_ids is not None:
                        UpperCAmelCase_           =   target_ids[p].tolist()

                   UpperCAmelCase_           =   p
                   # Filter padding out:
                   UpperCAmelCase_           =   tokens[np.where(tokens != self.tokenizer.pad_token_id )]
                   # Originally we skip special tokens to give readable output.
                   # For multi masks though, the other [MASK] would be removed otherwise
                   # making the output look odd, so we add them back
                   UpperCAmelCase_           =   self.tokenizer.decode(__a   ,			skip_special_tokens=__a )
                   UpperCAmelCase_           =   {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence}
                   row.append(__a )
              result.append(__a )
         if single_mask:
              return result[0]
         return result



    def 					_lowercase						(self    :    Dict   ,			__a    :    List[Any]   ,			__a    :    List[str]=None ):
         if isinstance(__a   ,			__a ):
              UpperCAmelCase_           =   [targets]
         try:
              UpperCAmelCase_           =   self.tokenizer.get_vocab()
         except Exception:
              UpperCAmelCase_           =   {}
         UpperCAmelCase_           =   []
         for target in targets:
              UpperCAmelCase_           =   vocab.get(__a   ,			__a )
              if id_ is None:
                   UpperCAmelCase_           =   self.tokenizer(
                       __a   ,			add_special_tokens=__a   ,			return_attention_mask=__a   ,			return_token_type_ids=__a   ,			max_length=1   ,			truncation=__a   ,			)["input_ids"]
                   if len(__a ) == 0:
                        logger.warning(
                            f"""The specified target token `{target}` does not exist in the model vocabulary. """
                            "We cannot replace it with anything meaningful, ignoring it" )
                        continue
                   UpperCAmelCase_           =   input_ids[0]
                   # XXX: If users encounter this pass
                   # it becomes pretty slow, so let's make sure
                   # The warning enables them to fix the input to
                   # get faster performance.
                   logger.warning(
                       f"""The specified target token `{target}` does not exist in the model vocabulary. """
                       f"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" )
              target_ids.append(id_ )
         UpperCAmelCase_           =   list(set(__a ) )
         if len(__a ) == 0:
              raise ValueError("At least one target must be provided when passed." )
         UpperCAmelCase_           =   np.array(__a )
         return target_ids



    def 					_lowercase						(self    :    Tuple   ,			__a    :    Dict=None   ,			__a    :    List[str]=None ):
         UpperCAmelCase_           =   {}

         if targets is not None:
              UpperCAmelCase_           =   self.get_target_ids(__a   ,			__a )
              UpperCAmelCase_           =   target_ids

         if top_k is not None:
              UpperCAmelCase_           =   top_k

         if self.tokenizer.mask_token_id is None:
              raise PipelineException(
                  "fill-mask"   ,			self.model.base_model_prefix   ,			"The tokenizer does not define a `mask_token`." )
         return {}, {}, postprocess_params






    def __call__(self    :    Union[str, Any]   ,			__a    :    str   ,			*__a    :    Any   ,			**__a    :    Tuple ):
         UpperCAmelCase_           =   super().__call__(__a   ,			**__a )
         if isinstance(__a   ,			__a ) and len(__a ) == 1:
              return outputs[0]
         return outputs




