'''simple docstring'''




import json
import os
import shutil
import tempfile
import unittest

import numpy as np

from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
						from PIL import Image

						from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor






@require_tokenizers
@require_vision
class 							a__(   unittest.TestCase      ):


			'''simple docstring'''






			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    tempfile.mkdtemp()

					# fmt: off
					lowerCAmelCase     =    ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest"""]
					# fmt: on
					lowerCAmelCase     =    os.path.join(self.tmpdirname			,       VOCAB_FILES_NAMES["""vocab_file"""])
					with open(self.vocab_file			,       """w"""			,       encoding="""utf-8""") as vocab_writer:
							vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]))

					lowerCAmelCase     =    {
					    """do_resize""": True,
					    """size""": {"""height""": 18, """width""": 18},
					    """do_normalize""": True,
					    """image_mean""": [0.5, 0.5, 0.5],
					    """image_std""": [0.5, 0.5, 0.5],
					}
					lowerCAmelCase     =    os.path.join(self.tmpdirname			,       __lowerCAmelCase)
					with open(self.image_processor_file			,       """w"""			,       encoding="""utf-8""") as fp:
							json.dump(__lowerCAmelCase			,       __lowerCAmelCase)



			def 				a_			(  self			,       **__lowerCAmelCase):




					"""simple docstring"""


					return BertTokenizer.from_pretrained(self.tmpdirname			,       **__lowerCAmelCase)



			def 				a_			(  self			,       **__lowerCAmelCase):




					"""simple docstring"""


					return ViTImageProcessor.from_pretrained(self.tmpdirname			,       **__lowerCAmelCase)



			def 				a_			(  self):




					"""simple docstring"""


					shutil.rmtree(self.tmpdirname)



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    [np.random.randint(255			,       size=(3, 30, 400)			,       dtype=np.uinta)]

					lowerCAmelCase     =    [Image.fromarray(np.moveaxis(__lowerCAmelCase			,       0			,       -1)) for x in image_inputs]

					return image_inputs



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.get_tokenizer()
					lowerCAmelCase     =    self.get_image_processor()

					lowerCAmelCase     =    VisionTextDualEncoderProcessor(tokenizer=__lowerCAmelCase			,       image_processor=__lowerCAmelCase)

					processor.save_pretrained(self.tmpdirname)
					lowerCAmelCase     =    VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname)

					self.assertEqual(processor.tokenizer.get_vocab()			,       tokenizer.get_vocab())
					self.assertIsInstance(processor.tokenizer			,       (BertTokenizer, BertTokenizerFast))

					self.assertEqual(processor.image_processor.to_json_string()			,       image_processor.to_json_string())
					self.assertIsInstance(processor.image_processor			,       __lowerCAmelCase)



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    VisionTextDualEncoderProcessor(
					    tokenizer=self.get_tokenizer()			,       image_processor=self.get_image_processor())
					processor.save_pretrained(self.tmpdirname)

					lowerCAmelCase     =    self.get_tokenizer(bos_token="""(BOS)"""			,       eos_token="""(EOS)""")
					lowerCAmelCase     =    self.get_image_processor(do_normalize=__lowerCAmelCase			,       padding_value=1.0)

					lowerCAmelCase     =    VisionTextDualEncoderProcessor.from_pretrained(
					    self.tmpdirname			,       bos_token="""(BOS)"""			,       eos_token="""(EOS)"""			,       do_normalize=__lowerCAmelCase			,       padding_value=1.0)

					self.assertEqual(processor.tokenizer.get_vocab()			,       tokenizer_add_kwargs.get_vocab())
					self.assertIsInstance(processor.tokenizer			,       (BertTokenizer, BertTokenizerFast))

					self.assertEqual(processor.image_processor.to_json_string()			,       image_processor_add_kwargs.to_json_string())
					self.assertIsInstance(processor.image_processor			,       __lowerCAmelCase)



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.get_image_processor()
					lowerCAmelCase     =    self.get_tokenizer()

					lowerCAmelCase     =    VisionTextDualEncoderProcessor(tokenizer=__lowerCAmelCase			,       image_processor=__lowerCAmelCase)

					lowerCAmelCase     =    self.prepare_image_inputs()

					lowerCAmelCase     =    image_processor(__lowerCAmelCase			,       return_tensors="""np""")
					lowerCAmelCase     =    processor(images=__lowerCAmelCase			,       return_tensors="""np""")

					for key in input_feat_extract.keys():
							self.assertAlmostEqual(input_feat_extract[key].sum()			,       input_processor[key].sum()			,       delta=1E-2)



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.get_image_processor()
					lowerCAmelCase     =    self.get_tokenizer()

					lowerCAmelCase     =    VisionTextDualEncoderProcessor(tokenizer=__lowerCAmelCase			,       image_processor=__lowerCAmelCase)

					lowerCAmelCase     =    """lower newer"""

					lowerCAmelCase     =    processor(text=__lowerCAmelCase)

					lowerCAmelCase     =    tokenizer(__lowerCAmelCase)

					for key in encoded_tok.keys():
							self.assertListEqual(encoded_tok[key]			,       encoded_processor[key])



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.get_image_processor()
					lowerCAmelCase     =    self.get_tokenizer()

					lowerCAmelCase     =    VisionTextDualEncoderProcessor(tokenizer=__lowerCAmelCase			,       image_processor=__lowerCAmelCase)

					lowerCAmelCase     =    """lower newer"""
					lowerCAmelCase     =    self.prepare_image_inputs()

					lowerCAmelCase     =    processor(text=__lowerCAmelCase			,       images=__lowerCAmelCase)

					self.assertListEqual(list(inputs.keys())			,       ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""])

					# test if it raises when no input is passed
					with self.assertRaises(__lowerCAmelCase):
							processor()



			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.get_image_processor()
					lowerCAmelCase     =    self.get_tokenizer()

					lowerCAmelCase     =    VisionTextDualEncoderProcessor(tokenizer=__lowerCAmelCase			,       image_processor=__lowerCAmelCase)

					lowerCAmelCase     =    [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

					lowerCAmelCase     =    processor.batch_decode(__lowerCAmelCase)
					lowerCAmelCase     =    tokenizer.batch_decode(__lowerCAmelCase)

					self.assertListEqual(__lowerCAmelCase			,       __lowerCAmelCase)







			def 				a_			(  self):




					"""simple docstring"""


					lowerCAmelCase     =    self.get_image_processor()
					lowerCAmelCase     =    self.get_tokenizer()

					lowerCAmelCase     =    VisionTextDualEncoderProcessor(tokenizer=__lowerCAmelCase			,       image_processor=__lowerCAmelCase)

					lowerCAmelCase     =    """lower newer"""
					lowerCAmelCase     =    self.prepare_image_inputs()

					lowerCAmelCase     =    processor(text=__lowerCAmelCase			,       images=__lowerCAmelCase)

					self.assertListEqual(list(inputs.keys())			,       processor.model_input_names)





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






def 							snake_case__				(     _A:   Dict="no" ,  _A:   str = default_json_config_file ,  _A:   bool = False					)       ->      List[str]:

		'''simple docstring'''


		lowerCAmelCase     =    Path(_A					)
		path.parent.mkdir(parents=_A ,  exist_ok=_A					)
		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
		lowerCAmelCase     =    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}"					)
		lowerCAmelCase     =    {
		    """compute_environment""": """LOCAL_MACHINE""",
		    """mixed_precision""": mixed_precision,
		}
		if torch.cuda.is_available():
				lowerCAmelCase     =    torch.cuda.device_count()
				lowerCAmelCase     =    num_gpus
				lowerCAmelCase     =    False
				if num_gpus > 1:
						lowerCAmelCase     =    """MULTI_GPU"""
				else:
						lowerCAmelCase     =    """NO"""
		elif is_xpu_available() and use_xpu:
				lowerCAmelCase     =    torch.xpu.device_count()
				lowerCAmelCase     =    num_xpus
				lowerCAmelCase     =    False
				if num_xpus > 1:
						lowerCAmelCase     =    """MULTI_XPU"""
				else:
						lowerCAmelCase     =    """NO"""
		elif is_npu_available():
				lowerCAmelCase     =    torch.npu.device_count()
				lowerCAmelCase     =    num_npus
				lowerCAmelCase     =    False
				if num_npus > 1:
						lowerCAmelCase     =    """MULTI_NPU"""
				else:
						lowerCAmelCase     =    """NO"""
		else:
				lowerCAmelCase     =    0
				lowerCAmelCase     =    True
				lowerCAmelCase     =    1
				lowerCAmelCase     =    """NO"""
		lowerCAmelCase     =    ClusterConfig(**_A					)
		config.to_json_file(_A					)
		return path






def 							snake_case__				(     _A:   str ,  _A:   Any					)       ->      Optional[Any]:

		'''simple docstring'''


		lowerCAmelCase     =    parser.add_parser("""default""" ,  parents=_A ,  help=_A ,  formatter_class=_A					)
		parser.add_argument(
		    """--config_file""" ,  default=_A ,  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=_A ,  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=_A					)
		return parser






def 							snake_case__				(     _A:   Optional[int]					)       ->      Optional[int]:

		'''simple docstring'''


		lowerCAmelCase     =    write_basic_config(args.mixed_precision ,  args.save_location					)
		if config_file:
				print(f"accelerate configuration saved at {config_file}"					)




