


'''simple docstring'''



import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
__UpperCAmelCase      :List[str]			    =       {"LayoutLMv2Config", "LayoutLMv3Config"}



@is_pipeline_test
class      a    (		unittest.TestCase	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			List[Any]							       =       MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
     SCREAMING_SNAKE_CASE	:			Union[str, Any]							       =       TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

     if model_mapping is not None:
          SCREAMING_SNAKE_CASE	:			Any							       =       {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
     if tf_model_mapping is not None:
          SCREAMING_SNAKE_CASE	:			Any							       =       {
              config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
          }

     @require_torch
     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Optional[Any]:
          __UpperCAmelCase     :			List[str]  							=      pipeline(
              task='''text-classification'''							,			model='''hf-internal-testing/tiny-random-distilbert'''							,			framework='''pt'''      )

          __UpperCAmelCase     :			Dict  							=      text_classifier('''This is great !'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

          __UpperCAmelCase     :			Optional[int]  							=      text_classifier('''This is great !'''							,			top_k=2      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]      )

          __UpperCAmelCase     :			Optional[Any]  							=      text_classifier(['''This is great !''', '''This is bad''']							,			top_k=2      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[
                  [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
                  [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
              ]							,			)

          __UpperCAmelCase     :			int  							=      text_classifier('''This is great !'''							,			top_k=1      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

          # Legacy behavior
          __UpperCAmelCase     :			Optional[int]  							=      text_classifier('''This is great !'''							,			return_all_scores=snake_case      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

          __UpperCAmelCase     :			int  							=      text_classifier('''This is great !'''							,			return_all_scores=snake_case      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[[{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]]      )

          __UpperCAmelCase     :			Tuple  							=      text_classifier(['''This is great !''', '''Something else''']							,			return_all_scores=snake_case      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[
                  [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
                  [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
              ]							,			)

          __UpperCAmelCase     :			Optional[int]  							=      text_classifier(['''This is great !''', '''Something else''']							,			return_all_scores=snake_case      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[
                  {'''label''': '''LABEL_0''', '''score''': 0.504},
                  {'''label''': '''LABEL_0''', '''score''': 0.504},
              ]							,			)

     @require_torch
     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Union[str, Any]:
          import torch

          __UpperCAmelCase     :			Optional[Any]  							=      pipeline(
              task='''text-classification'''							,			model='''hf-internal-testing/tiny-random-distilbert'''							,			framework='''pt'''							,			device=torch.device('''cpu'''      )							,			)

          __UpperCAmelCase     :			Any  							=      text_classifier('''This is great !'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

     @require_tf
     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Tuple:
          __UpperCAmelCase     :			List[Any]  							=      pipeline(
              task='''text-classification'''							,			model='''hf-internal-testing/tiny-random-distilbert'''							,			framework='''tf'''      )

          __UpperCAmelCase     :			str  							=      text_classifier('''This is great !'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

     @slow
     @require_torch
     def 			lowerCamelCase__			(    self					:		str      )						->							Optional[Any]:
          __UpperCAmelCase     :			Tuple  							=      pipeline('''text-classification'''      )

          __UpperCAmelCase     :			List[Any]  							=      text_classifier('''This is great !'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''POSITIVE''', '''score''': 1.0}]      )
          __UpperCAmelCase     :			Tuple  							=      text_classifier('''This is bad !'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''NEGATIVE''', '''score''': 1.0}]      )
          __UpperCAmelCase     :			Union[str, Any]  							=      text_classifier('''Birds are a type of animal'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''POSITIVE''', '''score''': 0.988}]      )

     @slow
     @require_tf
     def 			lowerCamelCase__			(    self					:		Tuple      )						->							str:
          __UpperCAmelCase     :			Optional[Any]  							=      pipeline('''text-classification'''							,			framework='''tf'''      )

          __UpperCAmelCase     :			Any  							=      text_classifier('''This is great !'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''POSITIVE''', '''score''': 1.0}]      )
          __UpperCAmelCase     :			Dict  							=      text_classifier('''This is bad !'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''NEGATIVE''', '''score''': 1.0}]      )
          __UpperCAmelCase     :			Union[str, Any]  							=      text_classifier('''Birds are a type of animal'''      )
          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': '''POSITIVE''', '''score''': 0.988}]      )

     def 			lowerCamelCase__			(    self					:		List[Any]							,			snake_case					:		str							,			snake_case					:		Any							,			snake_case					:		Any      )						->							Union[str, Any]:
          __UpperCAmelCase     :			str  							=      TextClassificationPipeline(model=snake_case							,			tokenizer=snake_case      )
          return text_classifier, ["HuggingFace is in", "This is another test"]






     def 			lowerCamelCase__			(    self					:		int							,			snake_case					:		List[str]							,			snake_case					:		Any      )						->							List[str]:
          __UpperCAmelCase     :			Optional[Any]  							=      text_classifier.model
          # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
          __UpperCAmelCase     :			Tuple  							=      '''HuggingFace is in'''
          __UpperCAmelCase     :			Union[str, Any]  							=      text_classifier(snake_case      )

          self.assertEqual(nested_simplify(snake_case      )							,			[{'''label''': ANY(snake_case      ), '''score''': ANY(snake_case      )}]      )
          self.assertTrue(outputs[0]['''label'''] in model.config.idalabel.values()      )

          __UpperCAmelCase     :			Tuple  							=      ['''HuggingFace is in ''', '''Paris is in France''']
          __UpperCAmelCase     :			int  							=      text_classifier(snake_case      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[{'''label''': ANY(snake_case      ), '''score''': ANY(snake_case      )}, {'''label''': ANY(snake_case      ), '''score''': ANY(snake_case      )}]							,			)
          self.assertTrue(outputs[0]['''label'''] in model.config.idalabel.values()      )
          self.assertTrue(outputs[1]['''label'''] in model.config.idalabel.values()      )

          # Forcing to get all results with `top_k=None`
          # This is NOT the legacy format
          __UpperCAmelCase     :			List[str]  							=      text_classifier(snake_case							,			top_k=snake_case      )
          __UpperCAmelCase     :			str  							=      len(model.config.idalabel.values()      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[[{'''label''': ANY(snake_case      ), '''score''': ANY(snake_case      )}] * N, [{'''label''': ANY(snake_case      ), '''score''': ANY(snake_case      )}] * N]							,			)

          __UpperCAmelCase     :			Optional[int]  							=      {'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
          __UpperCAmelCase     :			Union[str, Any]  							=      text_classifier(snake_case      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			{'''label''': ANY(snake_case      ), '''score''': ANY(snake_case      )}							,			)
          self.assertTrue(outputs['''label'''] in model.config.idalabel.values()      )

          # This might be used a text pair, but tokenizer + pipe interaction
          # makes it hard to understand that it's not using the pair properly
          # https://github.com/huggingface/transformers/issues/17305
          # We disabled this usage instead as it was outputting wrong outputs.
          __UpperCAmelCase     :			Any  							=      [['''HuggingFace is in ''', '''Paris is in France''']]
          with self.assertRaises(snake_case      ):
               text_classifier(snake_case      )

          # This used to be valid for doing text pairs
          # We're keeping it working because of backward compatibility
          __UpperCAmelCase     :			str  							=      text_classifier([[['''HuggingFace is in ''', '''Paris is in France''']]]      )
          self.assertEqual(
              nested_simplify(snake_case      )							,			[{'''label''': ANY(snake_case      ), '''score''': ANY(snake_case      )}]							,			)
          self.assertTrue(outputs[0]['''label'''] in model.config.idalabel.values()      )



'''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


__UpperCAmelCase      :Tuple			    =       "Create a default config file for Accelerate with only a few flags set."




def      _a     (						_lowercase :     List[Any]="no"      , _lowercase :     str = default_json_config_file      , _lowercase :     bool = False  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Dict  							=      Path(_lowercase  )
     path.parent.mkdir(parents=_lowercase      , exist_ok=_lowercase  )
     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     :			List[str]  							=      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     :			int  							=      {
         '''compute_environment''': '''LOCAL_MACHINE''',
         '''mixed_precision''': mixed_precision,
     }
     if torch.cuda.is_available():
          __UpperCAmelCase     :			Optional[Any]  							=      torch.cuda.device_count()
          __UpperCAmelCase     :			List[str]  							=      num_gpus
          __UpperCAmelCase     :			int  							=      False
          if num_gpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_GPU'''
          else:
               __UpperCAmelCase     :			int  							=      '''NO'''
     elif is_xpu_available() and use_xpu:
          __UpperCAmelCase     :			List[Any]  							=      torch.xpu.device_count()
          __UpperCAmelCase     :			List[Any]  							=      num_xpus
          __UpperCAmelCase     :			Optional[int]  							=      False
          if num_xpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_XPU'''
          else:
               __UpperCAmelCase     :			Optional[Any]  							=      '''NO'''
     elif is_npu_available():
          __UpperCAmelCase     :			Dict  							=      torch.npu.device_count()
          __UpperCAmelCase     :			Any  							=      num_npus
          __UpperCAmelCase     :			Any  							=      False
          if num_npus > 1:
               __UpperCAmelCase     :			Dict  							=      '''MULTI_NPU'''
          else:
               __UpperCAmelCase     :			Optional[int]  							=      '''NO'''
     else:
          __UpperCAmelCase     :			List[str]  							=      0
          __UpperCAmelCase     :			Dict  							=      True
          __UpperCAmelCase     :			Dict  							=      1
          __UpperCAmelCase     :			Tuple  							=      '''NO'''
     __UpperCAmelCase     :			List[Any]  							=      ClusterConfig(**_lowercase  )
     config.to_json_file(_lowercase  )
     return path




def      _a     (						_lowercase :     Union[str, Any]      , _lowercase :     str  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Optional[int]  							=      parser.add_parser('''default'''      , parents=_lowercase      , help=_lowercase      , formatter_class=_lowercase  )
     parser.add_argument(
         '''--config_file'''      , default=_lowercase      , 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=_lowercase      , 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=_lowercase  )
     return parser




def      _a     (						_lowercase :     List[Any]  ):





     '''simple docstring'''






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