


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






def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE="no"      ,      SCREAMING_SNAKE_CASE = default_json_config_file      ,      SCREAMING_SNAKE_CASE = False      )->						Any:




      """simple docstring"""

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






def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      )->						Optional[Any]:




      """simple docstring"""

      snake_case_ =   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  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      )->						str:




      """simple docstring"""

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



import unittest

from huggingface_hub import hf_hub_download

from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor
from transformers.pipelines import VideoClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_decord,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
)

from .test_pipelines_common import ANY







@is_pipeline_test
@require_torch_or_tf
@require_vision
@require_decord
class lowerCAmelCase_		(				unittest.TestCase ):

 '''simple docstring'''

 __snake_case				=						MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING



 def 		UpperCamelCase__  (			self	,   _UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase      ):
       snake_case_ =   hf_hub_download(
           repo_id='''nateraw/video-demo'''	,   filename='''archery.mp4'''	,   repo_type='''dataset'''      )
       snake_case_ =   VideoClassificationPipeline(model=_UpperCAmelCase	,   image_processor=_UpperCAmelCase	,   top_k=2      )
       snake_case_ =   [
           example_video_filepath,
           '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''',
       ]
       return video_classifier, examples



 def 		UpperCamelCase__  (			self	,   _UpperCAmelCase	,   _UpperCAmelCase      ):
       for example in examples:
             snake_case_ =   video_classifier(_UpperCAmelCase      )

             self.assertEqual(
                 _UpperCAmelCase	,   [
                     {'''score''': ANY(_UpperCAmelCase      ), '''label''': ANY(_UpperCAmelCase      )},
                     {'''score''': ANY(_UpperCAmelCase      ), '''label''': ANY(_UpperCAmelCase      )},
                 ]	,   )



 @require_torch
 def 		UpperCamelCase__  (			self      ):
       snake_case_ =   '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification'''
       snake_case_ =   VideoMAEFeatureExtractor(
           size={'''shortest_edge''': 10}	,   crop_size={'''height''': 10, '''width''': 10}      )
       snake_case_ =   pipeline(
           '''video-classification'''	,   model=_UpperCAmelCase	,   feature_extractor=_UpperCAmelCase	,   frame_sampling_rate=4      )

       snake_case_ =   hf_hub_download(repo_id='''nateraw/video-demo'''	,   filename='''archery.mp4'''	,   repo_type='''dataset'''      )
       snake_case_ =   video_classifier(_UpperCAmelCase	,   top_k=2      )
       self.assertEqual(
           nested_simplify(_UpperCAmelCase	,   decimals=4      )	,   [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}]	,   )

       snake_case_ =   video_classifier(
           [
               video_file_path,
               video_file_path,
           ]	,   top_k=2	,   )
       self.assertEqual(
           nested_simplify(_UpperCAmelCase	,   decimals=4      )	,   [
               [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}],
               [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}],
           ]	,   )





 @require_tf
 def 		UpperCamelCase__  (			self      ):
       pass