






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

import json
import os
import unittest

from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin



@require_tokenizers
class   snake_case_       (		__A  ,unittest.TestCase       ):
   __A	:		Union[str, Any]         =				LEDTokenizer
   __A	:		Union[str, Any]         =				LEDTokenizerFast
   __A	:		Optional[Any]         =				True






   def       __UpperCamelCase     (      self				:     List[str]  )					->						Union[str, Any]:
       super().setUp()
       lowercase__ :   List[str]    					=				[
           "l",
           "o",
           "w",
           "e",
           "r",
           "s",
           "t",
           "i",
           "d",
           "n",
           "\u0120",
           "\u0120l",
           "\u0120n",
           "\u0120lo",
           "\u0120low",
           "er",
           "\u0120lowest",
           "\u0120newer",
           "\u0120wider",
           "<unk>",
       ]
       lowercase__ :   Optional[int]    					=				dict(zip(lowercase_	,						range(len(lowercase_  )  )  )  )
       lowercase__ :   str    					=				["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
       lowercase__ :   Tuple    					=				{"unk_token": "<unk>"}

       lowercase__ :   Optional[Any]    					=				os.path.join(self.tmpdirname	,						VOCAB_FILES_NAMES["vocab_file"]  )
       lowercase__ :   Dict    					=				os.path.join(self.tmpdirname	,						VOCAB_FILES_NAMES["merges_file"]  )
       with open(self.vocab_file	,						"w"	,						encoding="utf-8"  ) as fp:
           fp.write(json.dumps(lowercase_  ) + "\n"  )
       with open(self.merges_file	,						"w"	,						encoding="utf-8"  ) as fp:
           fp.write("\n".join(lowercase_  )  )






   def       __UpperCamelCase     (      self				:     int	,						**lowercase_				:     str  )					->						List[Any]:
       kwargs.update(self.special_tokens_map  )
       return self.tokenizer_class.from_pretrained(self.tmpdirname	,						**lowercase_  )






   def       __UpperCamelCase     (      self				:     List[Any]	,						**lowercase_				:     Any  )					->						List[Any]:
       kwargs.update(self.special_tokens_map  )
       return self.rust_tokenizer_class.from_pretrained(self.tmpdirname	,						**lowercase_  )






   def       __UpperCamelCase     (      self				:     str	,						lowercase_				:     Any  )					->						Tuple:
       return "lower newer", "lower newer"






   @cached_property
   def       __UpperCamelCase     (      self				:     Tuple  )					->						Optional[Any]:
       return LEDTokenizer.from_pretrained("allenai/led-base-16384"  )






   @cached_property
   def       __UpperCamelCase     (      self				:     Tuple  )					->						int:
       return LEDTokenizerFast.from_pretrained("allenai/led-base-16384"  )






   @require_torch
   def       __UpperCamelCase     (      self				:     int  )					->						List[Any]:
       lowercase__ :   Union[str, Any]    					=				["A long paragraph for summarization.", "Another paragraph for summarization."]
       lowercase__ :   str    					=				[0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2]

       for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
           lowercase__ :   Dict    					=				tokenizer(lowercase_	,						max_length=len(lowercase_  )	,						padding=lowercase_	,						return_tensors="pt"  )
           self.assertIsInstance(lowercase_	,						lowercase_  )

           self.assertEqual((2, 9)	,						batch.input_ids.shape  )
           self.assertEqual((2, 9)	,						batch.attention_mask.shape  )
           lowercase__ :   Union[str, Any]    					=				batch.input_ids.tolist()[0]
           self.assertListEqual(lowercase_	,						lowercase_  )






   @require_torch
   def       __UpperCamelCase     (      self				:     List[str]  )					->						Tuple:
       lowercase__ :   Dict    					=				["A long paragraph for summarization.", "Another paragraph for summarization."]
       for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
           lowercase__ :   Optional[int]    					=				tokenizer(lowercase_	,						padding=lowercase_	,						return_tensors="pt"  )
           self.assertIn("input_ids"	,						lowercase_  )
           self.assertIn("attention_mask"	,						lowercase_  )
           self.assertNotIn("labels"	,						lowercase_  )
           self.assertNotIn("decoder_attention_mask"	,						lowercase_  )






   @require_torch
   def       __UpperCamelCase     (      self				:     Optional[Any]  )					->						Any:
       lowercase__ :   Dict    					=				[
           "Summary of the text.",
           "Another summary.",
       ]
       for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
           lowercase__ :   Dict    					=				tokenizer(text_target=lowercase_	,						max_length=32	,						padding="max_length"	,						return_tensors="pt"  )
           self.assertEqual(32	,						targets["input_ids"].shape[1]  )






   @require_torch
   def       __UpperCamelCase     (      self				:     Optional[int]  )					->						Tuple:
       for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
           lowercase__ :   int    					=				tokenizer(
               ["I am a small frog" * 10_24, "I am a small frog"]	,						padding=lowercase_	,						truncation=lowercase_	,						return_tensors="pt"  )
           self.assertIsInstance(lowercase_	,						lowercase_  )
           self.assertEqual(batch.input_ids.shape	,						(2, 51_22)  )






   @require_torch
   def       __UpperCamelCase     (      self				:     List[str]  )					->						Any:
       lowercase__ :   Union[str, Any]    					=				["A long paragraph for summarization."]
       lowercase__ :   List[Any]    					=				[
           "Summary of the text.",
       ]
       for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
           lowercase__ :   List[Any]    					=				tokenizer(lowercase_	,						return_tensors="pt"  )
           lowercase__ :   Dict    					=				tokenizer(text_target=lowercase_	,						return_tensors="pt"  )
           lowercase__ :   Optional[int]    					=				inputs["input_ids"]
           lowercase__ :   str    					=				targets["input_ids"]
           self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()  )
           self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()  )
           self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()  )
           self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()  )






   @require_torch
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						Dict:
       for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
           lowercase__ :   int    					=				["Summary of the text.", "Another summary."]
           lowercase__ :   List[str]    					=				[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]

           lowercase__ :   Tuple    					=				tokenizer(lowercase_	,						padding=lowercase_  )
           lowercase__ :   int    					=				[[0] * len(lowercase_  ) for x in encoded_output["input_ids"]]
           lowercase__ :   Any    					=				tokenizer.pad(lowercase_  )
           self.assertSequenceEqual(outputs["global_attention_mask"]	,						lowercase_  )






   def       __UpperCamelCase     (      self				:     int  )					->						Union[str, Any]:
       pass







   def       __UpperCamelCase     (      self				:     int  )					->						Optional[Any]:
       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
           with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''  ):
               lowercase__ :   List[Any]    					=				self.rust_tokenizer_class.from_pretrained(lowercase_	,						**lowercase_  )
               lowercase__ :   List[str]    					=				self.tokenizer_class.from_pretrained(lowercase_	,						**lowercase_  )
               lowercase__ :   List[Any]    					=				"A, <mask> AllenNLP sentence."
               lowercase__ :   Tuple    					=				tokenizer_r.encode_plus(lowercase_	,						add_special_tokens=lowercase_	,						return_token_type_ids=lowercase_  )
               lowercase__ :   List[str]    					=				tokenizer_p.encode_plus(lowercase_	,						add_special_tokens=lowercase_	,						return_token_type_ids=lowercase_  )
               self.assertEqual(sum(tokens_r["token_type_ids"]  )	,						sum(tokens_p["token_type_ids"]  )  )
               self.assertEqual(
                   sum(tokens_r["attention_mask"]  ) / len(tokens_r["attention_mask"]  )	,						sum(tokens_p["attention_mask"]  ) / len(tokens_p["attention_mask"]  )	,						)

               lowercase__ :   Any    					=				tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"]  )
               lowercase__ :   Optional[Any]    					=				tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"]  )
               self.assertSequenceEqual(tokens_p["input_ids"]	,						[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2]  )
               self.assertSequenceEqual(tokens_r["input_ids"]	,						[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2]  )

               self.assertSequenceEqual(
                   lowercase_	,						["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]  )
               self.assertSequenceEqual(
                   lowercase_	,						["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]  )



