






# 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_  :	List[Any] 				=					"""Run commands across TPU VMs for initial setup before running `accelerate launch`."""







def     A__   (  lowerCamelCase=None  )					->		Tuple:
				if subparsers is not None:
								UpperCamelCase_:							Optional[Any]		=  subparsers.add_parser("""tpu-config"""       ,      description=_description  )
				else:
								UpperCamelCase_:							Any		=  argparse.ArgumentParser("""Accelerate tpu-config command"""       ,      description=_description  )
				# Core arguments
				UpperCamelCase_:							List[str]		=  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."""       ,      )
				UpperCamelCase_:							List[Any]		=  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     A__   (  lowerCamelCase  )					->		Dict:
				UpperCamelCase_:							Dict		=  None

				# Get the default from the config file if it exists.
				if args.config_file is not None or os.path.isfile(lowerCamelCase  ):
								UpperCamelCase_:							Optional[int]		=  load_config_from_file(args.config_file  )
								if not args.command_file and defaults.command_file is not None and not args.command:
												UpperCamelCase_:							Union[str, Any]		=  defaults.command_file
								if not args.command and defaults.commands is not None:
												UpperCamelCase_:							List[Any]		=  defaults.commands
								if not args.tpu_name:
												UpperCamelCase_:							Optional[Any]		=  defaults.tpu_name
								if not args.tpu_zone:
												UpperCamelCase_:							int		=  defaults.tpu_zone
				if args.accelerate_version == "dev":
								UpperCamelCase_:							Dict		=  """git+https://github.com/huggingface/accelerate.git"""
				elif args.accelerate_version == "latest":
								UpperCamelCase_:							str		=  """accelerate -U"""
				elif isinstance(parse(args.accelerate_version  )       ,      lowerCamelCase  ):
								UpperCamelCase_:							Tuple		=  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:
												UpperCamelCase_:							int		=  [f.read().splitlines()]

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

				# Then send it to gcloud
				# Eventually try to use google-api-core to do this instead of subprocess
				UpperCamelCase_:							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     A__   (  )					->		Tuple:
				UpperCamelCase_:							List[str]		=  tpu_command_parser()
				UpperCamelCase_:							Optional[Any]		=  parser.parse_args()

				tpu_command_launcher(lowerCamelCase  )








from datasets.utils.patching import _PatchedModuleObj, patch_submodule

from . import _test_patching







def     A__   (  )					->		Union[str, Any]:
				import os as original_os
				from os import path as original_path
				from os import rename as original_rename
				from os.path import dirname as original_dirname
				from os.path import join as original_join

				assert _test_patching.os is original_os
				assert _test_patching.path is original_path
				assert _test_patching.join is original_join

				assert _test_patching.renamed_os is original_os
				assert _test_patching.renamed_path is original_path
				assert _test_patching.renamed_join is original_join

				UpperCamelCase_:							Optional[int]		=  """__test_patch_submodule_mock__"""
				with patch_submodule(_test_patching       ,      """os.path.join"""       ,      lowerCamelCase  ):
								# Every way to access os.path.join must be patched, and the rest must stay untouched

								# check os.path.join
								assert isinstance(_test_patching.os       ,      _PatchedModuleObj  )
								assert isinstance(_test_patching.os.path       ,      _PatchedModuleObj  )
								assert _test_patching.os.path.join is mock

								# check path.join
								assert isinstance(_test_patching.path       ,      _PatchedModuleObj  )
								assert _test_patching.path.join is mock

								# check join
								assert _test_patching.join is mock

								# check that the other attributes are untouched
								assert _test_patching.os.rename is original_rename
								assert _test_patching.path.dirname is original_dirname
								assert _test_patching.os.path.dirname is original_dirname

								# Even renamed modules or objects must be patched

								# check renamed_os.path.join
								assert isinstance(_test_patching.renamed_os       ,      _PatchedModuleObj  )
								assert isinstance(_test_patching.renamed_os.path       ,      _PatchedModuleObj  )
								assert _test_patching.renamed_os.path.join is mock

								# check renamed_path.join
								assert isinstance(_test_patching.renamed_path       ,      _PatchedModuleObj  )
								assert _test_patching.renamed_path.join is mock

								# check renamed_join
								assert _test_patching.renamed_join is mock

								# check that the other attributes are untouched
								assert _test_patching.renamed_os.rename is original_rename
								assert _test_patching.renamed_path.dirname is original_dirname
								assert _test_patching.renamed_os.path.dirname is original_dirname

				# check that everthing is back to normal when the patch is over

				assert _test_patching.os is original_os
				assert _test_patching.path is original_path
				assert _test_patching.join is original_join

				assert _test_patching.renamed_os is original_os
				assert _test_patching.renamed_path is original_path
				assert _test_patching.renamed_join is original_join







def     A__   (  )					->		Union[str, Any]:
				assert _test_patching.open is open

				UpperCamelCase_:							List[Any]		=  """__test_patch_submodule_builtin_mock__"""
				# _test_patching has "open" in its globals
				assert _test_patching.open is open
				with patch_submodule(_test_patching       ,      """open"""       ,      lowerCamelCase  ):
								assert _test_patching.open is mock

				# check that everthing is back to normal when the patch is over

				assert _test_patching.open is open







def     A__   (  )					->		Optional[Any]:
				# pandas.read_csv is not present in _test_patching
				UpperCamelCase_:							Optional[Any]		=  """__test_patch_submodule_missing_mock__"""
				with patch_submodule(_test_patching       ,      """pandas.read_csv"""       ,      lowerCamelCase  ):
								pass







def     A__   (  )					->		Any:
				# builtin should always be mocked even if they're not in the globals
				# in case they're loaded at one point
				UpperCamelCase_:							List[Any]		=  """__test_patch_submodule_missing_builtin_mock__"""
				# _test_patching doesn't have "len" in its globals
				assert getattr(_test_patching       ,      """len"""       ,      lowerCamelCase  ) is None
				with patch_submodule(_test_patching       ,      """len"""       ,      lowerCamelCase  ):
								assert _test_patching.len is mock
				assert _test_patching.len is len







def     A__   (  )					->		Any:
				UpperCamelCase_:							Dict		=  """__test_patch_submodule_start_and_stop_mock__"""
				UpperCamelCase_:							List[str]		=  patch_submodule(_test_patching       ,      """open"""       ,      lowerCamelCase  )
				assert _test_patching.open is open
				patch.start()
				assert _test_patching.open is mock
				patch.stop()
				assert _test_patching.open is open







def     A__   (  )					->		List[str]:
				from os import rename as original_rename
				from os.path import dirname as original_dirname
				from os.path import join as original_join

				UpperCamelCase_:							Optional[Any]		=  """__test_patch_submodule_successive_join__"""
				UpperCamelCase_:							Any		=  """__test_patch_submodule_successive_dirname__"""
				UpperCamelCase_:							Dict		=  """__test_patch_submodule_successive_rename__"""
				assert _test_patching.os.path.join is original_join
				assert _test_patching.os.path.dirname is original_dirname
				assert _test_patching.os.rename is original_rename

				with patch_submodule(_test_patching       ,      """os.path.join"""       ,      lowerCamelCase  ):
								with patch_submodule(_test_patching       ,      """os.rename"""       ,      lowerCamelCase  ):
												with patch_submodule(_test_patching       ,      """os.path.dirname"""       ,      lowerCamelCase  ):
																assert _test_patching.os.path.join is mock_join
																assert _test_patching.os.path.dirname is mock_dirname
																assert _test_patching.os.rename is mock_rename

    # try another order
				with patch_submodule(_test_patching       ,      """os.rename"""       ,      lowerCamelCase  ):
								with patch_submodule(_test_patching       ,      """os.path.join"""       ,      lowerCamelCase  ):
												with patch_submodule(_test_patching       ,      """os.path.dirname"""       ,      lowerCamelCase  ):
																assert _test_patching.os.path.join is mock_join
																assert _test_patching.os.path.dirname is mock_dirname
																assert _test_patching.os.rename is mock_rename

				assert _test_patching.os.path.join is original_join
				assert _test_patching.os.path.dirname is original_dirname
				assert _test_patching.os.rename is original_rename







def     A__   (  )					->		Union[str, Any]:
				UpperCamelCase_:							Dict		=  """__test_patch_submodule_doesnt_exist_mock__"""
				with patch_submodule(_test_patching       ,      """__module_that_doesn_exist__.__attribute_that_doesn_exist__"""       ,      lowerCamelCase  ):
								pass
				with patch_submodule(_test_patching       ,      """os.__attribute_that_doesn_exist__"""       ,      lowerCamelCase  ):
								pass






