


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

import argparse
import os
import subprocess

from packaging.version import Version, parse

from accelerate.commands.config.config_args import default_config_file, load_config_from_file


lowerCamelCase : str						   =       '''Run commands across TPU VMs for initial setup before running `accelerate launch`.'''
def       snake_case_		(     lowerCAmelCase_       :						Optional[Any]=None      ):
							if subparsers is not None:
														__lowercase      :							Any				=     subparsers.add_parser("""tpu-config"""       ,       description=_description      )
							else:
														__lowercase      :							Dict				=     argparse.ArgumentParser("""Accelerate tpu-config command"""       ,       description=_description      )
							# Core arguments
							__lowercase      :							List[Any]				=     parser.add_argument_group(
							    """Config Arguments"""       ,       """Arguments that can be configured through `accelerate config`."""      )
							config_args.add_argument(
							    """--config_file"""       ,       type=lowerCAmelCase_       ,       default=lowerCAmelCase_       ,       help="""Path to the config file to use for accelerate."""       ,       )
							config_args.add_argument(
							    """--tpu_name"""       ,       default=lowerCAmelCase_       ,       help="""The name of the TPU to use. If not specified, will use the TPU specified in the config file."""       ,       )
							config_args.add_argument(
							    """--tpu_zone"""       ,       default=lowerCAmelCase_       ,       help="""The zone of the TPU to use. If not specified, will use the zone specified in the config file."""       ,       )
							__lowercase      :							int				=     parser.add_argument_group("""TPU Arguments"""       ,       """Arguments for options ran inside the TPU."""      )
							pod_args.add_argument(
							    """--use_alpha"""       ,       action="""store_true"""       ,       help="""Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`."""       ,       )
							pod_args.add_argument(
							    """--command_file"""       ,       default=lowerCAmelCase_       ,       help="""The path to the file containing the commands to run on the pod on startup."""       ,       )
							pod_args.add_argument(
							    """--command"""       ,       action="""append"""       ,       nargs="""+"""       ,       help="""A command to run on the pod. Can be passed multiple times."""       ,       )
							pod_args.add_argument(
							    """--install_accelerate"""       ,       action="""store_true"""       ,       help="""Whether to install accelerate on the pod. Defaults to False."""       ,       )
							pod_args.add_argument(
							    """--accelerate_version"""       ,       default="""latest"""       ,       help="""The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub."""       ,       )
							pod_args.add_argument(
							    """--debug"""       ,       action="""store_true"""       ,       help="""If set, will print the command that would be run instead of running it."""      )

							if subparsers is not None:
														parser.set_defaults(func=lowerCAmelCase_      )
							return parser
def       snake_case_		(     lowerCAmelCase_       :						Any      ):
							__lowercase      :							int				=     None

							# Get the default from the config file if it exists.
							if args.config_file is not None or os.path.isfile(lowerCAmelCase_      ):
														__lowercase      :							Any				=     load_config_from_file(args.config_file      )
														if not args.command_file and defaults.command_file is not None and not args.command:
																					__lowercase      :							int				=     defaults.command_file
														if not args.command and defaults.commands is not None:
																					__lowercase      :							Dict				=     defaults.commands
														if not args.tpu_name:
																					__lowercase      :							Optional[int]				=     defaults.tpu_name
														if not args.tpu_zone:
																					__lowercase      :							Union[str, Any]				=     defaults.tpu_zone
							if args.accelerate_version == "dev":
														__lowercase      :							List[Any]				=     """git+https://github.com/huggingface/accelerate.git"""
							elif args.accelerate_version == "latest":
														__lowercase      :							Dict				=     """accelerate -U"""
							elif isinstance(parse(args.accelerate_version      )       ,       lowerCAmelCase_      ):
														__lowercase      :							List[Any]				=     F"accelerate=={args.accelerate_version}"

							if not args.command_file and not args.command:
														raise ValueError("""You must specify either a command file or a command to run on the pod."""      )

							if args.command_file:
														with open(args.command_file       ,       """r"""      ) as f:
																					__lowercase      :							List[Any]				=     [f.read().splitlines()]

    # To turn list of lists into list of strings
							if isinstance(args.command[0]       ,       lowerCAmelCase_      ):
														__lowercase      :							Dict				=     [line for cmd in args.command for line in cmd]
							# Default to the shared folder and install accelerate
							__lowercase      :							Optional[Any]				=     ["""cd /usr/share"""]
							if args.install_accelerate:
														new_cmd += [F"pip install {args.accelerate_version}"]
							new_cmd += args.command
							__lowercase      :							Tuple				=     """; """.join(lowerCAmelCase_      )

							# Then send it to gcloud
							# Eventually try to use google-api-core to do this instead of subprocess
							__lowercase      :							Tuple				=     ["""gcloud"""]
							if args.use_alpha:
														cmd += ["alpha"]
							cmd += [
							    "compute",
							    "tpus",
							    "tpu-vm",
							    "ssh",
							    args.tpu_name,
							    "--zone",
							    args.tpu_zone,
							    "--command",
							    args.command,
							    "--worker",
							    "all",
							]
							if args.debug:
														print(F"Running {' '.join(lowerCAmelCase_      )}"      )
														return
							subprocess.run(lowerCAmelCase_      )
							print("""Successfully setup pod."""      )



def       snake_case_		(     ):
							__lowercase      :							Tuple				=     tpu_command_parser()
							__lowercase      :							Tuple				=     parser.parse_args()

							tpu_command_launcher(lowerCAmelCase_      )







import uuid
from typing import Any, Dict, List, Optional, Union

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


if is_tf_available():
	import tensorflow as tf

if is_torch_available():
	import torch


lowerCamelCase : List[Any]						   =       logging.get_logger(__name__)

class 		lowerCAmelCase     :

					'''simple docstring'''

					def __init__(  self				:	List[str]		,     __a				:	str = None		,     __a				:	uuid.UUID = None		,     __a				:	Any=None		,     __a				:	List[Any]=None							)			->  List[Any]:


												"""simple docstring"""

												if not conversation_id:
																			__lowercase      :							Any				=     uuid.uuida()
												if past_user_inputs is None:
																			__lowercase      :							Dict				=     []
												if generated_responses is None:
																			__lowercase      :							Dict				=     []

												__lowercase      :							uuid.UUID				=     conversation_id
												__lowercase      :							List[str]				=     past_user_inputs
												__lowercase      :							List[str]				=     generated_responses
												__lowercase      :							Optional[str]				=     text



					def __eq__(  self				:	Dict		,     __a				:	Dict							)			->  Any:


												"""simple docstring"""

												if not isinstance(__a		,     __a							):
																			return False
												if self.uuid == other.uuid:
																			return True
												return (
												    self.new_user_input == other.new_user_input
												    and self.past_user_inputs == other.past_user_inputs
												    and self.generated_responses == other.generated_responses
												)



					def       lowerCAmelCase				(  self				:	List[str]		,     __a				:	str		,     __a				:	bool = False							)			->  Dict:


												"""simple docstring"""

												if self.new_user_input:
																			if overwrite:
																										logger.warning(
																										    F"User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten "
																										    F"with: \"{text}\"."							)
																										__lowercase      :							Optional[int]				=     text
																			else:
																										logger.warning(
																										    F"User input added while unprocessed input was existing: \"{self.new_user_input}\" new input "
																										    F"ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input"							)
												else:
																			__lowercase      :							Dict				=     text



					def       lowerCAmelCase				(  self				:	int							)			->  Optional[Any]:


												"""simple docstring"""

												if self.new_user_input:
																			self.past_user_inputs.append(self.new_user_input							)
												__lowercase      :							Dict				=     None



					def       lowerCAmelCase				(  self				:	Optional[int]		,     __a				:	str							)			->  List[Any]:


												"""simple docstring"""

												self.generated_responses.append(__a							)



					def       lowerCAmelCase				(  self				:	Any							)			->  Optional[Any]:


												"""simple docstring"""

												for user_input, generated_response in zip(self.past_user_inputs		,     self.generated_responses							):
																			yield True, user_input
																			yield False, generated_response
												if self.new_user_input:
																			yield True, self.new_user_input



					def __repr__(  self				:	int							)			->  str:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     F"Conversation id: {self.uuid} \n"
												for is_user, text in self.iter_texts():
																			__lowercase      :							Optional[Any]				=     """user""" if is_user else """bot"""
																			output += F"{name} >> {text} \n"
												return output







@add_end_docstrings(
    __a      ,       r'''
        min_length_for_response (`int`, *optional*, defaults to 32):
            The minimum length (in number of tokens) for a response.
        minimum_tokens (`int`, *optional*, defaults to 10):
            The minimum length of tokens to leave for a response.
    '''      ,       )
class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					def __init__(  self				:	Any		,     *__a				:	int		,     **__a				:	str							)			->  Union[str, Any]:


												"""simple docstring"""

												super().__init__(*__a		,     **__a							)
												if self.tokenizer.pad_token_id is None:
																			__lowercase      :							List[Any]				=     self.tokenizer.eos_token



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	int=None		,     __a				:	Tuple=None		,     __a				:	Any=None		,     **__a				:	List[str]							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							List[str]				=     {}
												__lowercase      :							Tuple				=     {}
												__lowercase      :							List[str]				=     {}

												if min_length_for_response is not None:
																			__lowercase      :							Dict				=     min_length_for_response
												if minimum_tokens is not None:
																			__lowercase      :							Union[str, Any]				=     minimum_tokens

												if "max_length" in generate_kwargs:
																			__lowercase      :							Union[str, Any]				=     generate_kwargs["""max_length"""]
																			# self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
												if clean_up_tokenization_spaces is not None:
																			__lowercase      :							Union[str, Any]				=     clean_up_tokenization_spaces

												if generate_kwargs:
																			forward_params.update(__a							)
												return preprocess_params, forward_params, postprocess_params



					def __call__(  self				:	Optional[int]		,     __a				:	Union[Conversation, List[Conversation]]		,     __a				:	Dict=0		,     **__a				:	List[Any]							)			->  Tuple:


												"""simple docstring"""

												__lowercase      :							List[Any]				=     super().__call__(__a		,     num_workers=__a		,     **__a							)
												if isinstance(__a		,     __a							) and len(__a							) == 1:
																			return outputs[0]
												return outputs



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	Conversation		,     __a				:	Tuple=32							)			->  Dict[str, Any]:


												"""simple docstring"""

												if not isinstance(__a		,     __a							):
																			raise ValueError("""ConversationalPipeline, expects Conversation as inputs"""							)
												if conversation.new_user_input is None:
																			raise ValueError(
																			    F"Conversation with UUID {type(conversation.uuid							)} does not contain new user input to process. "
																			    """Add user inputs with the conversation's `add_user_input` method"""							)
												if hasattr(self.tokenizer		,     """_build_conversation_input_ids"""							):
																			__lowercase      :							List[Any]				=     self.tokenizer._build_conversation_input_ids(__a							)
												else:
																			# If the tokenizer cannot handle conversations, we default to only the old version
																			__lowercase      :							Tuple				=     self._legacy_parse_and_tokenize(__a							)

												if self.framework == "pt":
																			__lowercase      :							List[Any]				=     torch.LongTensor([input_ids]							)
												elif self.framework == "tf":
																			__lowercase      :							List[str]				=     tf.constant([input_ids]							)
												return {"input_ids": input_ids, "conversation": conversation}



					def       lowerCAmelCase				(  self				:	Any		,     __a				:	Dict		,     __a				:	Any=10		,     **__a				:	Dict							)			->  Optional[Any]:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     generate_kwargs.get("""max_length"""		,     self.model.config.max_length							)

												__lowercase      :							List[Any]				=     model_inputs["""input_ids"""].shape[1]
												if max_length - minimum_tokens < n:
																			logger.warning(F"Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})"							)
																			__lowercase      :							Any				=     max_length - minimum_tokens
																			__lowercase      :							int				=     model_inputs["""input_ids"""][:, -trim:]
																			if "attention_mask" in model_inputs:
																										__lowercase      :							Dict				=     model_inputs["""attention_mask"""][:, -trim:]
												__lowercase      :							Union[str, Any]				=     model_inputs.pop("""conversation"""							)
												__lowercase      :							Tuple				=     max_length
												__lowercase      :							int				=     self.model.generate(**__a		,     **__a							)
												if self.model.config.is_encoder_decoder:
																			__lowercase      :							Optional[int]				=     1
												else:
																			__lowercase      :							str				=     n
												return {"output_ids": output_ids[:, start_position:], "conversation": conversation}



					def       lowerCAmelCase				(  self				:	int		,     __a				:	Tuple		,     __a				:	List[Any]=True							)			->  List[str]:


												"""simple docstring"""

												__lowercase      :							int				=     model_outputs["""output_ids"""]
												__lowercase      :							Union[str, Any]				=     self.tokenizer.decode(
												    output_ids[0]		,     skip_special_tokens=__a		,     clean_up_tokenization_spaces=__a		,     )
												__lowercase      :							List[str]				=     model_outputs["""conversation"""]
												conversation.mark_processed()
												conversation.append_response(__a							)
												return conversation



					def       lowerCAmelCase				(  self				:	int		,     __a				:	Conversation							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     self.tokenizer.eos_token_id
												__lowercase      :							Optional[Any]				=     []
												for is_user, text in conversation.iter_texts():
																			if eos_token_id is not None:
																										input_ids.extend(self.tokenizer.encode(__a		,     add_special_tokens=__a							) + [eos_token_id]							)
																			else:
																										input_ids.extend(self.tokenizer.encode(__a		,     add_special_tokens=__a							)							)

												if len(__a							) > self.tokenizer.model_max_length:
																			__lowercase      :							List[Any]				=     input_ids[-self.tokenizer.model_max_length :]
												return input_ids