


import json
import os
import unittest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin


@require_tokenizers
class 	_a							(      UpperCamelCase__					,     unittest.TestCase      ):
	_lowercase     :      Union[str, Any]  				=			CLIPTokenizer
	_lowercase     :      int  				=			CLIPTokenizerFast
	_lowercase     :      Any  				=			True
	_lowercase     :      List[Any]  				=			{}
	_lowercase     :      Union[str, Any]  				=			False

	def 				lowerCamelCase_			(							self:     str							)      ->       List[Any]:





			"""simple docstring"""







			super().setUp()

			# fmt: off
			lowercase__						=				['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>''']
			# fmt: on
			lowercase__						=				dict(zip(UpperCamelCase_   ,						range(len(UpperCamelCase_							)							)							)							)
			lowercase__						=				['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''']
			lowercase__						=				{'''unk_token''': '''<unk>'''}

			lowercase__						=				os.path.join(self.tmpdirname   ,						VOCAB_FILES_NAMES['''vocab_file''']							)
			lowercase__						=				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(UpperCamelCase_							) + '''\n'''							)
			with open(self.merges_file   ,						'''w'''   ,						encoding='''utf-8'''							) as fp:
					fp.write('''\n'''.join(UpperCamelCase_							)							)

	def 				lowerCamelCase_			(							self:     Union[str, Any]   ,						**UpperCamelCase_:     int							)      ->       Dict:





			"""simple docstring"""







			kwargs.update(self.special_tokens_map							)
			return CLIPTokenizer.from_pretrained(self.tmpdirname   ,						**UpperCamelCase_							)

	def 				lowerCamelCase_			(							self:     Dict   ,						**UpperCamelCase_:     Tuple							)      ->       List[Any]:





			"""simple docstring"""







			kwargs.update(self.special_tokens_map							)
			return CLIPTokenizerFast.from_pretrained(self.tmpdirname   ,						**UpperCamelCase_							)

	def 				lowerCamelCase_			(							self:     Any   ,						UpperCamelCase_:     int							)      ->       Dict:





			"""simple docstring"""







			lowercase__						=				'''lower newer'''
			lowercase__						=				'''lower newer'''
			return input_text, output_text

	def 				lowerCamelCase_			(							self:     Tuple							)      ->       List[Any]:





			"""simple docstring"""







			lowercase__						=				CLIPTokenizer(self.vocab_file   ,						self.merges_file   ,						**self.special_tokens_map							)
			lowercase__						=				'''lower newer'''
			lowercase__						=				['''lo''', '''w''', '''er</w>''', '''n''', '''e''', '''w''', '''er</w>''']
			lowercase__						=				tokenizer.tokenize(UpperCamelCase_							)
			self.assertListEqual(UpperCamelCase_   ,						UpperCamelCase_							)

			lowercase__						=				tokens + [tokenizer.unk_token]
			lowercase__						=				[10, 2, 16, 9, 3, 2, 16, 20]
			self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_							)   ,						UpperCamelCase_							)

	@require_ftfy
	def 				lowerCamelCase_			(							self:     Dict							)      ->       Any:





			"""simple docstring"""







			for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
					with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})'							):
							lowercase__						=				self.tokenizer_class.from_pretrained(UpperCamelCase_   ,						**UpperCamelCase_							)
							lowercase__						=				self.rust_tokenizer_class.from_pretrained(UpperCamelCase_   ,						**UpperCamelCase_							)

							lowercase__						=				'''A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.'''
							lowercase__						=				tokenizer_s.tokenize(UpperCamelCase_							)
							lowercase__						=				tokenizer_r.tokenize(UpperCamelCase_							)

							self.assertListEqual(UpperCamelCase_   ,						UpperCamelCase_							)

							# Test that the tokenization is identical on an example containing a character (Latin Small Letter A
							# with Tilde) encoded in 2 different ways
							lowercase__						=				'''xa\u0303y''' + ''' ''' + '''x\xe3y'''
							lowercase__						=				tokenizer_s.tokenize(UpperCamelCase_							)
							lowercase__						=				tokenizer_r.tokenize(UpperCamelCase_							)

							self.assertListEqual(UpperCamelCase_   ,						UpperCamelCase_							)

							# Test that the tokenization is identical on unicode of space type
							lowercase__						=				[
							    '''\u0009''',  # (horizontal tab, '\t')
							    '''\u000B''',  # (vertical tab)
							    '''\u000C''',  # (form feed)
							    '''\u0020''',  # (space, ' ')
							    '''\u200E''',  # (left-to-right mark):w
							    '''\u200F''',  # (right-to-left mark)
							]
							for unicode_seq in spaces_unicodes:
									lowercase__						=				tokenizer_s.tokenize(UpperCamelCase_							)
									lowercase__						=				tokenizer_r.tokenize(UpperCamelCase_							)

									self.assertListEqual(UpperCamelCase_   ,						UpperCamelCase_							)

							# Test that the tokenization is identical on unicode of line break type
							lowercase__						=				[
							    '''\u000A''',  # (line feed, '\n')
							    '''\r\n''',  # (carriage return and line feed, '\r\n')
							    '''\u000D''',  # (carriage return, '\r')
							    '''\r''',  # (carriage return, '\r')
							    '''\u000D''',  # (carriage return, '\r')
							    '''\u2028''',  # (line separator)
							    '''\u2029''',  # (paragraph separator)
							    # "\u0085", # (next line)
							]

							# The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms
							# it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a
							# space (and thus into an empty list).

							for unicode_seq in line_break_unicodes:
									lowercase__						=				tokenizer_s.tokenize(UpperCamelCase_							)
									lowercase__						=				tokenizer_r.tokenize(UpperCamelCase_							)

									self.assertListEqual(UpperCamelCase_   ,						UpperCamelCase_							)

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





			"""simple docstring"""







			for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
					with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})'							):
							lowercase__						=				'''hello'''  # `hello` is a token in the vocabulary of `pretrained_name`
							lowercase__						=				f'{text_of_1_token} {text_of_1_token}'

							lowercase__						=				self.rust_tokenizer_class.from_pretrained(
							    UpperCamelCase_   ,						use_fast=UpperCamelCase_   ,						)
							lowercase__						=				tokenizer_r(UpperCamelCase_   ,						return_offsets_mapping=UpperCamelCase_   ,						add_special_tokens=UpperCamelCase_							)
							self.assertEqual(encoding.offset_mapping[0]   ,						(0, len(UpperCamelCase_							))							)
							self.assertEqual(
							    encoding.offset_mapping[1]   ,						(len(UpperCamelCase_							) + 1, len(UpperCamelCase_							) + 1 + len(UpperCamelCase_							))   ,						)

							lowercase__						=				f' {text}'

							lowercase__						=				self.rust_tokenizer_class.from_pretrained(
							    UpperCamelCase_   ,						use_fast=UpperCamelCase_   ,						)
							lowercase__						=				tokenizer_r(UpperCamelCase_   ,						return_offsets_mapping=UpperCamelCase_   ,						add_special_tokens=UpperCamelCase_							)
							self.assertEqual(encoding.offset_mapping[0]   ,						(1, 1 + len(UpperCamelCase_							))							)
							self.assertEqual(
							    encoding.offset_mapping[1]   ,						(1 + len(UpperCamelCase_							) + 1, 1 + len(UpperCamelCase_							) + 1 + len(UpperCamelCase_							))   ,						)

	def 				lowerCamelCase_			(							self:     Tuple							)      ->       Dict:





			"""simple docstring"""







			with self.assertRaises(UpperCamelCase_							) as context:
					self.rust_tokenizer_class.from_pretrained('''robot-test/old-clip-tokenizer'''							)

			self.assertTrue(
			    context.exception.args[0].startswith(
			        '''The `backend_tokenizer` provided does not match the expected format.'''							)							)

	@require_ftfy
	def 				lowerCamelCase_			(							self:     str							)      ->       int:





			"""simple docstring"""







			super().test_tokenization_python_rust_equals()


	def 				lowerCamelCase_			(							self:     Tuple							)      ->       str:





			"""simple docstring"""







			pass






# 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


lowerCAmelCase	=							'Create a default config file for Accelerate with only a few flags set.'
def       _a			(				SCREAMING_SNAKE_CASE="no"						,    SCREAMING_SNAKE_CASE = default_json_config_file						,    SCREAMING_SNAKE_CASE = False					):


		"""simple docstring"""




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


		"""simple docstring"""




		lowercase__						=				parser.add_parser('''default'''						,    parents=SCREAMING_SNAKE_CASE						,    help=SCREAMING_SNAKE_CASE						,    formatter_class=SCREAMING_SNAKE_CASE					)
		parser.add_argument(
		    '''--config_file'''						,    default=SCREAMING_SNAKE_CASE						,    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=SCREAMING_SNAKE_CASE						,    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=SCREAMING_SNAKE_CASE					)
		return parser
def       _a			(				SCREAMING_SNAKE_CASE					):


		"""simple docstring"""




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


