
# 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  )








import json
import os
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import ImageGPTImageProcessor

class     _UpperCamelCase			(   unittest.TestCase					):






			'''simple docstring'''

			def __init__(    self	:    Optional[int]  ,		snake_case_	:    Dict  ,		snake_case_	:    Tuple=7  ,		snake_case_	:    Optional[Any]=3  ,		snake_case_	:    Dict=18  ,		snake_case_	:    Dict=30  ,		snake_case_	:    Union[str, Any]=400  ,		snake_case_	:    List[Any]=True  ,		snake_case_	:    Any=None  ,		snake_case_	:    List[str]=True  ,		):
							UpperCamelCase_:							Dict		=  size if size is not None else {"""height""": 18, """width""": 18}
							UpperCamelCase_:							Union[str, Any]		=  parent
							UpperCamelCase_:							Tuple		=  batch_size
							UpperCamelCase_:							List[str]		=  num_channels
							UpperCamelCase_:							Optional[int]		=  image_size
							UpperCamelCase_:							Dict		=  min_resolution
							UpperCamelCase_:							Optional[int]		=  max_resolution
							UpperCamelCase_:							str		=  do_resize
							UpperCamelCase_:							Tuple		=  size
							UpperCamelCase_:							Dict		=  do_normalize




			def  lowerCAmelCase__		(    self	:    str ):
							return {
							    # here we create 2 clusters for the sake of simplicity
							    "clusters": np.asarray(
							        [
							            [0.8866_4436_3403_3203, 0.6618_8293_6954_4983, 0.3891_7464_0178_6804],
							            [-0.6042_5591_4688_1104, -0.0_2295_0088_6052_8469, 0.5423_7973_6900_3296],
							        ] ),
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "do_normalize": self.do_normalize,
							}




@require_torch
@require_vision
class     _UpperCamelCase			(   _A       ,    unittest.TestCase					):






			'''simple docstring'''

			__UpperCamelCase :  Optional[int]    =	ImageGPTImageProcessor if is_vision_available() else None

			def  lowerCAmelCase__		(    self	:    List[str] ):
							UpperCamelCase_:							Any		=  ImageGPTImageProcessingTester(self )

			@property
			def  lowerCAmelCase__		(    self	:    Optional[int] ):
							return self.image_processor_tester.prepare_image_processor_dict()

			def  lowerCAmelCase__		(    self	:    Optional[int] ):
							UpperCamelCase_:							List[Any]		=  self.image_processing_class(**self.image_processor_dict )
							self.assertTrue(hasattr(snake_case_  ,		"""clusters""" ) )
							self.assertTrue(hasattr(snake_case_  ,		"""do_resize""" ) )
							self.assertTrue(hasattr(snake_case_  ,		"""size""" ) )
							self.assertTrue(hasattr(snake_case_  ,		"""do_normalize""" ) )

			def  lowerCAmelCase__		(    self	:    int ):
							UpperCamelCase_:							List[Any]		=  self.image_processing_class.from_dict(self.image_processor_dict )
							self.assertEqual(image_processor.size  ,		{"""height""": 18, """width""": 18} )

							UpperCamelCase_:							Tuple		=  self.image_processing_class.from_dict(self.image_processor_dict  ,		size=42 )
							self.assertEqual(image_processor.size  ,		{"""height""": 42, """width""": 42} )

			def  lowerCAmelCase__		(    self	:    Optional[Any] ):
							UpperCamelCase_:							int		=  self.image_processing_class(**self.image_processor_dict )
							UpperCamelCase_:							Optional[int]		=  json.loads(image_processor.to_json_string() )
							for key, value in self.image_processor_dict.items():
											if key == "clusters":
															self.assertTrue(np.array_equal(snake_case_  ,		obj[key] ) )
											else:
															self.assertEqual(obj[key]  ,		snake_case_ )

			def  lowerCAmelCase__		(    self	:    List[Any] ):
							UpperCamelCase_:							Dict		=  self.image_processing_class(**self.image_processor_dict )

							with tempfile.TemporaryDirectory() as tmpdirname:
											UpperCamelCase_:							int		=  os.path.join(snake_case_  ,		"""image_processor.json""" )
											image_processor_first.to_json_file(snake_case_ )
											UpperCamelCase_:							Any		=  self.image_processing_class.from_json_file(snake_case_ ).to_dict()

							UpperCamelCase_:							str		=  image_processor_first.to_dict()
							for key, value in image_processor_first.items():
											if key == "clusters":
															self.assertTrue(np.array_equal(snake_case_  ,		image_processor_second[key] ) )
											else:
															self.assertEqual(image_processor_first[key]  ,		snake_case_ )

			def  lowerCAmelCase__		(    self	:    Union[str, Any] ):
							UpperCamelCase_:							Optional[Any]		=  self.image_processing_class(**self.image_processor_dict )

							with tempfile.TemporaryDirectory() as tmpdirname:
											image_processor_first.save_pretrained(snake_case_ )
											UpperCamelCase_:							Optional[int]		=  self.image_processing_class.from_pretrained(snake_case_ ).to_dict()

							UpperCamelCase_:							Union[str, Any]		=  image_processor_first.to_dict()
							for key, value in image_processor_first.items():
											if key == "clusters":
															self.assertTrue(np.array_equal(snake_case_  ,		image_processor_second[key] ) )
											else:
															self.assertEqual(image_processor_first[key]  ,		snake_case_ )




			@unittest.skip("""ImageGPT requires clusters at initialization""" )
			def  lowerCAmelCase__		(    self	:    List[Any] ):
							pass







def     A__   (  )					->		Optional[int]:
				UpperCamelCase_:							Optional[int]		=  load_dataset("""hf-internal-testing/fixtures_image_utils"""       ,      split="""test"""  )

				UpperCamelCase_:							Tuple		=  Image.open(dataset[4]["""file"""]  )
				UpperCamelCase_:							Union[str, Any]		=  Image.open(dataset[5]["""file"""]  )

				UpperCamelCase_:							List[str]		=  [imagea, imagea]

				return images





@require_vision
@require_torch
class     _UpperCamelCase			(   unittest.TestCase					):






			'''simple docstring'''

			@slow
			def  lowerCAmelCase__		(    self	:    List[str] ):
							UpperCamelCase_:							List[Any]		=  ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" )

							UpperCamelCase_:							List[str]		=  prepare_images()

							# test non-batched
							UpperCamelCase_:							List[str]		=  image_processing(images[0]  ,		return_tensors="""pt""" )

							self.assertIsInstance(encoding.input_ids  ,		torch.LongTensor )
							self.assertEqual(encoding.input_ids.shape  ,		(1, 1024) )

							UpperCamelCase_:							Union[str, Any]		=  [306, 191, 191]
							self.assertEqual(encoding.input_ids[0, :3].tolist()  ,		snake_case_ )

							# test batched
							UpperCamelCase_:							Optional[int]		=  image_processing(snake_case_  ,		return_tensors="""pt""" )

							self.assertIsInstance(encoding.input_ids  ,		torch.LongTensor )
							self.assertEqual(encoding.input_ids.shape  ,		(2, 1024) )

							UpperCamelCase_:							str		=  [303, 13, 13]
							self.assertEqual(encoding.input_ids[1, -3:].tolist()  ,		snake_case_ )






