



'''simple docstring'''





import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test


class 				snake_case (unittest.TestCase   ):



       @parameterized.expand([(None,), ("foo.json",)]      )
       def 							_a      (				self     ,UpperCAmelCase_      )  ->							Optional[int]:
           lowercase__		       =						GenerationConfig(
               do_sample=__lowerCamelCase     ,temperature=0.7     ,length_penalty=1.0     ,bad_words_ids=[[1, 2, 3], [4, 5]]     ,)
           with tempfile.TemporaryDirectory() as tmp_dir:
               config.save_pretrained(__lowerCamelCase     ,config_name=__lowerCamelCase      )
               lowercase__		       =						GenerationConfig.from_pretrained(__lowerCamelCase     ,config_name=__lowerCamelCase      )

           # Checks parameters that were specified
           self.assertEqual(loaded_config.do_sample     ,__lowerCamelCase      )
           self.assertEqual(loaded_config.temperature     ,0.7      )
           self.assertEqual(loaded_config.length_penalty     ,1.0      )
           self.assertEqual(loaded_config.bad_words_ids     ,[[1, 2, 3], [4, 5]]      )

           # Checks parameters that were not specified (defaults)
           self.assertEqual(loaded_config.top_k     ,50      )
           self.assertEqual(loaded_config.max_length     ,20      )
           self.assertEqual(loaded_config.max_time     ,__lowerCamelCase      )



       def 							_a      (				self      )  ->							List[str]:
           lowercase__		       =						AutoConfig.from_pretrained("gpt2"      )
           lowercase__		       =						GenerationConfig.from_model_config(__lowerCamelCase      )
           lowercase__		       =						GenerationConfig()

           # The generation config has loaded a few non-default parameters from the model config
           self.assertNotEqual(__lowerCamelCase     ,__lowerCamelCase      )

           # One of those parameters is eos_token_id -- check if it matches
           self.assertNotEqual(generation_config_from_model.eos_token_id     ,default_generation_config.eos_token_id      )
           self.assertEqual(generation_config_from_model.eos_token_id     ,model_config.eos_token_id      )



       def 							_a      (				self      )  ->							int:
           lowercase__		       =						GenerationConfig()
           lowercase__		       =						{
               '''max_new_tokens''': 1_024,
               '''foo''': '''bar''',
           }
           lowercase__		       =						copy.deepcopy(__lowerCamelCase      )
           lowercase__		       =						generation_config.update(**__lowerCamelCase      )

           # update_kwargs was not modified (no side effects)
           self.assertEqual(__lowerCamelCase     ,__lowerCamelCase      )

           # update_kwargs was used to update the config on valid attributes
           self.assertEqual(generation_config.max_new_tokens     ,1_024      )

           # `.update()` returns a dictionary of unused kwargs
           self.assertEqual(__lowerCamelCase     ,{"foo": "bar"}      )



       def 							_a      (				self      )  ->							Union[str, Any]:
           lowercase__		       =						GenerationConfig()
           lowercase__		       =						'''bar'''

           with tempfile.TemporaryDirectory("test-generation-config"      ) as tmp_dir:
               generation_config.save_pretrained(__lowerCamelCase      )

               lowercase__		       =						GenerationConfig.from_pretrained(__lowerCamelCase      )
           # update_kwargs was used to update the config on valid attributes
           self.assertEqual(new_config.foo     ,"bar"      )

           lowercase__		       =						GenerationConfig.from_model_config(__lowerCamelCase      )
           assert not hasattr(__lowerCamelCase     ,"foo"      )  # no new kwargs should be initialized if from config







       def 							_a      (				self      )  ->							Optional[Any]:
           lowercase__		       =						GenerationConfig()
           self.assertEqual(default_config.temperature     ,1.0      )
           self.assertEqual(default_config.do_sample     ,__lowerCamelCase      )
           self.assertEqual(default_config.num_beams     ,1      )

           lowercase__		       =						GenerationConfig(
               do_sample=__lowerCamelCase     ,temperature=0.7     ,length_penalty=1.0     ,bad_words_ids=[[1, 2, 3], [4, 5]]     ,)
           self.assertEqual(config.temperature     ,0.7      )
           self.assertEqual(config.do_sample     ,__lowerCamelCase      )
           self.assertEqual(config.num_beams     ,1      )

           with tempfile.TemporaryDirectory() as tmp_dir:
               config.save_pretrained(__lowerCamelCase      )
               lowercase__		       =						GenerationConfig.from_pretrained(__lowerCamelCase     ,temperature=1.0      )

           self.assertEqual(loaded_config.temperature     ,1.0      )
           self.assertEqual(loaded_config.do_sample     ,__lowerCamelCase      )
           self.assertEqual(loaded_config.num_beams     ,1      )  # default value





@is_staging_test
class 				snake_case (unittest.TestCase   ):



       @classmethod
       def 							_a      (				cls      )  ->							int:
           lowercase__		       =						TOKEN
           HfFolder.save_token(__lowerCamelCase      )



       @classmethod
       def 							_a      (				cls      )  ->							List[str]:






           try:
               delete_repo(token=cls._token     ,repo_id="test-generation-config"      )
           except HTTPError:
               pass

           try:
               delete_repo(token=cls._token     ,repo_id="valid_org/test-generation-config-org"      )
           except HTTPError:
               pass



       def 							_a      (				self      )  ->							str:
           lowercase__		       =						GenerationConfig(
               do_sample=__lowerCamelCase     ,temperature=0.7     ,length_penalty=1.0     ,)
           config.push_to_hub("test-generation-config"     ,use_auth_token=self._token      )

           lowercase__		       =						GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''      )
           for k, v in config.to_dict().items():
               if k != "transformers_version":
                   self.assertEqual(__lowerCamelCase     ,getattr(__lowerCamelCase     ,__lowerCamelCase      )      )

        # Reset repo
           delete_repo(token=self._token     ,repo_id="test-generation-config"      )

           # Push to hub via save_pretrained
           with tempfile.TemporaryDirectory() as tmp_dir:
               config.save_pretrained(
                   __lowerCamelCase     ,repo_id="test-generation-config"     ,push_to_hub=__lowerCamelCase     ,use_auth_token=self._token      )

           lowercase__		       =						GenerationConfig.from_pretrained(F'''{USER}/test-generation-config'''      )
           for k, v in config.to_dict().items():
               if k != "transformers_version":
                   self.assertEqual(__lowerCamelCase     ,getattr(__lowerCamelCase     ,__lowerCamelCase      )      )







       def 							_a      (				self      )  ->							Dict:
           lowercase__		       =						GenerationConfig(
               do_sample=__lowerCamelCase     ,temperature=0.7     ,length_penalty=1.0     ,)
           config.push_to_hub("valid_org/test-generation-config-org"     ,use_auth_token=self._token      )

           lowercase__		       =						GenerationConfig.from_pretrained("valid_org/test-generation-config-org"      )
           for k, v in config.to_dict().items():
               if k != "transformers_version":
                   self.assertEqual(__lowerCamelCase     ,getattr(__lowerCamelCase     ,__lowerCamelCase      )      )

        # Reset repo
           delete_repo(token=self._token     ,repo_id="valid_org/test-generation-config-org"      )

           # Push to hub via save_pretrained
           with tempfile.TemporaryDirectory() as tmp_dir:
               config.save_pretrained(
                   __lowerCamelCase     ,repo_id="valid_org/test-generation-config-org"     ,push_to_hub=__lowerCamelCase     ,use_auth_token=self._token      )

           lowercase__		       =						GenerationConfig.from_pretrained("valid_org/test-generation-config-org"      )
           for k, v in config.to_dict().items():
               if k != "transformers_version":
                   self.assertEqual(__lowerCamelCase     ,getattr(__lowerCamelCase     ,__lowerCamelCase      )      )









'''simple docstring'''





# Copyright 2022 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.

import argparse
import os
import platform

import numpy as np
import psutil
import torch

from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file

from ..utils import is_npu_available, is_xpu_available




def        lowerCamelCase  (				_snake_case  :						str=None       ):





    '''simple docstring'''


    if subparsers is not None:
        lowercase__		       =						subparsers.add_parser("env"       )
    else:
        lowercase__		       =						argparse.ArgumentParser("Accelerate env command"       )

    parser.add_argument(
        "--config_file"     ,default=_snake_case     ,help="The config file to use for the default values in the launching script."       )

    if subparsers is not None:
        parser.set_defaults(func=_snake_case       )
    return parser




def        lowerCamelCase  (				_snake_case  :						Tuple       ):





    '''simple docstring'''


    lowercase__		       =						torch.__version__
    lowercase__		       =						torch.cuda.is_available()
    lowercase__		       =						is_xpu_available()
    lowercase__		       =						is_npu_available()

    lowercase__		       =						"Not found"
    # Get the default from the config file.
    if args.config_file is not None or os.path.isfile(_snake_case       ):
        lowercase__		       =						load_config_from_file(args.config_file       ).to_dict()

    lowercase__		       =						{
        "`Accelerate` version": version,
        "Platform": platform.platform(),
        "Python version": platform.python_version(),
        "Numpy version": np.__version__,
        "PyTorch version (GPU?)": f'''{pt_version} ({pt_cuda_available})''',
        "PyTorch XPU available": str(_snake_case       ),
        "PyTorch NPU available": str(_snake_case       ),
        "System RAM": f'''{psutil.virtual_memory().total / 1_024 ** 3:.2f} GB''',
    }
    if pt_cuda_available:
        lowercase__		       =						torch.cuda.get_device_name()

    print("\nCopy-and-paste the text below in your GitHub issue\n"       )
    print("\n".join([f'''- {prop}: {val}''' for prop, val in info.items()]       )       )

    print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:"       )
    lowercase__		       =						(
        "\n".join([f'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]       )
        if isinstance(_snake_case     ,_snake_case       )
        else f'''\t{accelerate_config}'''
    )
    print(_snake_case       )

    lowercase__		       =						accelerate_config

    return info




def        lowerCamelCase  (				):





    '''simple docstring'''


    lowercase__		       =						env_command_parser()
    lowercase__		       =						parser.parse_args()
    env_command(_snake_case       )
    return 0


if __name__ == "__main__":
 raise SystemExit(main())




