
"""simple docstring"""




import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile, rmtree
from typing import Generator

import datasets.config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.filelock import logger as fl_logger
from datasets.utils.info_utils import VerificationMode
from datasets.utils.logging import ERROR, get_logger


a		:					Optional[Any]    	=					get_logger(__name__)



def 						__magic_name__		(				UpperCamelCase    :		Optional[int]    )    ->	Optional[int]:
    return TestCommand(
        args.dataset       ,		args.name       ,		args.cache_dir       ,		args.data_dir       ,		args.all_configs       ,		args.save_info or args.save_infos       ,		args.ignore_verifications       ,		args.force_redownload       ,		args.clear_cache       ,		)







class 						lowercase(lowerCAmelCase_					):
     __snake_case:  Optional[Any]  				=    False  # to tell pytest it's not a test class



     @staticmethod
     def  lowercase__     (       __SCREAMING_SNAKE_CASE      )		->    List[Any]:







         """simple docstring"""



         a__    = parser.add_parser('test'    ,							help='Test dataset implementation.'      )
         test_parser.add_argument('--name'    ,							type=lowerCamelCase_    ,							default=lowerCamelCase_    ,							help='Dataset processing name'      )
         test_parser.add_argument(
             '--cache_dir'    ,							type=lowerCamelCase_    ,							default=lowerCamelCase_    ,							help='Cache directory where the datasets are stored.'    ,							)
         test_parser.add_argument(
             '--data_dir'    ,							type=lowerCamelCase_    ,							default=lowerCamelCase_    ,							help='Can be used to specify a manual directory to get the files from.'    ,							)
         test_parser.add_argument('--all_configs'    ,							action='store_true'    ,							help='Test all dataset configurations'      )
         test_parser.add_argument(
             '--save_info'    ,							action='store_true'    ,							help='Save the dataset infos in the dataset card (README.md)'      )
         test_parser.add_argument(
             '--ignore_verifications'    ,							action='store_true'    ,							help='Run the test without checksums and splits checks.'    ,							)
         test_parser.add_argument('--force_redownload'    ,							action='store_true'    ,							help='Force dataset redownload'      )
         test_parser.add_argument(
             '--clear_cache'    ,							action='store_true'    ,							help='Remove downloaded files and cached datasets after each config test'    ,							)
         # aliases
         test_parser.add_argument('--save_infos'    ,							action='store_true'    ,							help='alias to save_info'      )
         test_parser.add_argument('dataset'    ,							type=lowerCamelCase_    ,							help='Name of the dataset to download'      )
         test_parser.set_defaults(func=_test_command_factory      )



     def __init__(       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							)		->    Any:







         """simple docstring"""



         a__    = dataset
         a__    = name
         a__    = cache_dir
         a__    = data_dir
         a__    = all_configs
         a__    = save_infos
         a__    = ignore_verifications
         a__    = force_redownload
         a__    = clear_cache
         if clear_cache and not cache_dir:
             print(
                 'When --clear_cache is used, specifying a cache directory is mandatory.\n'
                 'The \'download\' folder of the cache directory and the dataset builder cache will be deleted after each configuration test.\n'
                 'Please provide a --cache_dir that will be used to test the dataset script.'      )
             exit(1      )
         if save_infos:
             a__    = True




     def  lowercase__     (       self      )		->    Optional[int]:







         """simple docstring"""



         fl_logger().setLevel(lowerCamelCase_      )
         if self._name is not None and self._all_configs:
             print('Both parameters `config` and `all_configs` can\'t be used at once.'      )
             exit(1      )
         a__  ,    a__    = self._dataset, self._name
         a__    = dataset_module_factory(lowerCamelCase_      )
         a__    = import_main_class(module.module_path      )
         a__    = len(builder_cls.BUILDER_CONFIGS      ) if self._all_configs and builder_cls.BUILDER_CONFIGS else 1

         def get_builders() -> Generator[DatasetBuilder, None, None]:
             if self._all_configs and builder_cls.BUILDER_CONFIGS:
                 for i, config in enumerate(builder_cls.BUILDER_CONFIGS      ):
                     if "config_name" in module.builder_kwargs:
                         yield builder_cls(
                             cache_dir=self._cache_dir    ,							data_dir=self._data_dir    ,							**module.builder_kwargs    ,							)
                     else:
                         yield builder_cls(
                             config_name=config.name    ,							cache_dir=self._cache_dir    ,							data_dir=self._data_dir    ,							**module.builder_kwargs    ,							)
             else:
                 if "config_name" in module.builder_kwargs:
                     yield builder_cls(cache_dir=self._cache_dir    ,							data_dir=self._data_dir    ,							**module.builder_kwargs      )
                 else:
                     yield builder_cls(
                         config_name=lowerCamelCase_    ,							cache_dir=self._cache_dir    ,							data_dir=self._data_dir    ,							**module.builder_kwargs    ,							)

         for j, builder in enumerate(get_builders()      ):
             print(f'Testing builder \'{builder.config.name}\' ({j + 1}/{n_builders})'      )
             a__    = os.path.exists(
                 os.path.join(builder.get_imported_module_dir()    ,							datasets.config.DATASETDICT_INFOS_FILENAME      )      )  # record checksums only if we need to update a (deprecated) dataset_infos.json
             builder.download_and_prepare(
                 download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
                 if not self._force_redownload
                 else DownloadMode.FORCE_REDOWNLOAD    ,							verification_mode=VerificationMode.NO_CHECKS
                 if self._ignore_verifications
                 else VerificationMode.ALL_CHECKS    ,							try_from_hf_gcs=lowerCamelCase_    ,							)
             builder.as_dataset()
             if self._save_infos:
                 builder._save_infos()

             # If save_infos=True, the dataset card (README.md) is created next to the loaded module file.
             # The dataset_infos are saved in the YAML part of the README.md

             # Let's move it to the original directory of the dataset script, to allow the user to
             # upload them on S3 at the same time afterwards.
             if self._save_infos:
                 a__    = os.path.join(builder_cls.get_imported_module_dir()    ,							'README.md'      )
                 a__    = Path(lowerCamelCase_      ).name + '.py'
                 a__    = os.path.join(lowerCamelCase_    ,							lowerCamelCase_      )
                 if os.path.isfile(lowerCamelCase_      ):
                     a__    = os.path.dirname(lowerCamelCase_      )
                 elif os.path.isfile(lowerCamelCase_      ):
                     a__    = path
                 elif os.path.isdir(lowerCamelCase_      ):  # for local directories containing only data files
                     a__    = path
                 else:  # in case of a remote dataset
                     a__    = None
                     print(f'Dataset card saved at {dataset_readme_path}'      )

                 # Move dataset_info back to the user
                 if dataset_dir is not None:
                     a__    = os.path.join(lowerCamelCase_    ,							'README.md'      )
                     copyfile(lowerCamelCase_    ,							lowerCamelCase_      )
                     print(f'Dataset card saved at {user_dataset_readme_path}'      )

            # If clear_cache=True, the download folder and the dataset builder cache directory are deleted
             if self._clear_cache:
                 if os.path.isdir(builder._cache_dir      ):
                     logger.warning(f'Clearing cache at {builder._cache_dir}'      )
                     rmtree(builder._cache_dir      )
                 a__    = os.path.join(self._cache_dir    ,							datasets.config.DOWNLOADED_DATASETS_DIR      )
                 if os.path.isdir(lowerCamelCase_      ):
                     logger.warning(f'Clearing cache at {download_dir}'      )
                     rmtree(lowerCamelCase_      )

         print('Test successful.'      )








"""simple docstring"""




import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


a		:					Tuple    	=					namedtuple('ExampleNamedTuple', 'a b c')







class 						lowercase(unittest.TestCase					):



     def  lowercase__     (       self      )		->    Union[str, Any]:







         """simple docstring"""



         a__    = torch.randn(5    ,							2      )
         a__    = torch.device('cuda'      ) if torch.cuda.is_available() else torch.device('cpu'      )

         a__    = send_to_device(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta.cpu()    ,							__SCREAMING_SNAKE_CASE      )      )

         a__    = send_to_device((tensor, [tensor, tensor], 1)    ,							__SCREAMING_SNAKE_CASE      )
         self.assertIsInstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta[0].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertIsInstance(resulta[1]    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta[1][0].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertTrue(torch.equal(resulta[1][1].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertEqual(resulta[2]    ,							1      )

         a__    = send_to_device({'a': tensor, 'b': [tensor, tensor], 'c': 1}    ,							__SCREAMING_SNAKE_CASE      )
         self.assertIsInstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta['a'].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertIsInstance(resulta['b']    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta['b'][0].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertTrue(torch.equal(resulta['b'][1].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertEqual(resulta['c']    ,							1      )

         a__    = send_to_device(ExampleNamedTuple(a=__SCREAMING_SNAKE_CASE    ,							b=[tensor, tensor]    ,							c=1      )    ,							__SCREAMING_SNAKE_CASE      )
         self.assertIsInstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta.a.cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertIsInstance(resulta.b    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta.b[0].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertTrue(torch.equal(resulta.b[1].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertEqual(resulta.c    ,							1      )

         a__    = send_to_device(UserDict({'a': tensor, 'b': [tensor, tensor], 'c': 1}      )    ,							__SCREAMING_SNAKE_CASE      )
         self.assertIsInstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta['a'].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertIsInstance(resulta['b']    ,							__SCREAMING_SNAKE_CASE      )
         self.assertTrue(torch.equal(resulta['b'][0].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertTrue(torch.equal(resulta['b'][1].cpu()    ,							__SCREAMING_SNAKE_CASE      )      )
         self.assertEqual(resulta['c']    ,							1      )



     def  lowercase__     (       self      )		->    Dict:







         """simple docstring"""



         with self.assertRaises(__SCREAMING_SNAKE_CASE      ) as cm:
             a__    = recursively_apply(torch.tensor    ,							(torch.tensor(1      ), 1)    ,							error_on_other_type=__SCREAMING_SNAKE_CASE      )
         self.assertEqual(
             str(cm.exception      )    ,							'Unsupported types (<class \'int\'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed.'    ,							)



     def  lowercase__     (       self      )		->    Any:







         """simple docstring"""



         a__    = torch.tensor([1, 2, 3, 4, 5]      )
         self.assertEqual(listify(__SCREAMING_SNAKE_CASE      )    ,							[1, 2, 3, 4, 5]      )

         a__    = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]]      )
         self.assertEqual(listify(__SCREAMING_SNAKE_CASE      )    ,							[[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]]      )

         a__    = torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]], [[1_1, 1_2, 1_3, 1_4, 1_5], [1_6, 1_7, 1_8, 1_9, 2_0]]]      )
         self.assertEqual(
             listify(__SCREAMING_SNAKE_CASE      )    ,							[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]], [[1_1, 1_2, 1_3, 1_4, 1_5], [1_6, 1_7, 1_8, 1_9, 2_0]]]      )



     def  lowercase__     (       self      )		->    str:







         """simple docstring"""



         with patch_environment(aa=1    ,							BB=2      ):
             self.assertEqual(os.environ.get('AA'      )    ,							'1'      )
             self.assertEqual(os.environ.get('BB'      )    ,							'2'      )

         self.assertNotIn('AA'    ,							os.environ      )
         self.assertNotIn('BB'    ,							os.environ      )



     def  lowercase__     (       self      )		->    Tuple:







         """simple docstring"""



         a__    = RegressionModel()
         a__    = model.forward
         a__    = convert_outputs_to_fpaa(model.forward      )
         a__    = extract_model_from_parallel(__SCREAMING_SNAKE_CASE    ,							keep_fpaa_wrapper=__SCREAMING_SNAKE_CASE      )
         a__    = pickle.dumps(__SCREAMING_SNAKE_CASE      )



     @require_cuda
     def  lowercase__     (       self      )		->    Union[str, Any]:







         """simple docstring"""



         a__    = RegressionModel()
         a__    = model.forward
         a__    = torch.cuda.amp.autocast(dtype=torch.floataa      )(model.forward      )
         a__    = convert_outputs_to_fpaa(model.forward      )
         a__    = extract_model_from_parallel(__SCREAMING_SNAKE_CASE    ,							keep_fpaa_wrapper=__SCREAMING_SNAKE_CASE      )
         a__    = pickle.dumps(__SCREAMING_SNAKE_CASE      )



     @require_cuda
     @require_torch_min_version(version='2.0'      )
     def  lowercase__     (       self      )		->    Optional[int]:







         """simple docstring"""



         a__    = RegressionModel()
         a__    = model.forward
         a__    = torch.cuda.amp.autocast(dtype=torch.floataa      )(model.forward      )
         a__    = convert_outputs_to_fpaa(model.forward      )
         a__    = torch.compile(model.forward    ,							backend='inductor'      )
         a__    = torch.randn(4    ,							1_0      ).cuda()
         a__    = model(__SCREAMING_SNAKE_CASE      )



     def  lowercase__     (       self      )		->    str:







         """simple docstring"""



         a__    = RegressionModel()
         # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
         a__    = torch.nn.parallel.DataParallel(__SCREAMING_SNAKE_CASE      )
         a__    = extract_model_from_parallel(__SCREAMING_SNAKE_CASE      )

         self.assertEqual(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      )



     @require_torch_min_version(version='2.0'      )
     def  lowercase__     (       self      )		->    str:







         """simple docstring"""



         a__    = RegressionModel()
         a__    = torch.compile(__SCREAMING_SNAKE_CASE      )

         # could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
         a__    = torch.nn.parallel.DataParallel(__SCREAMING_SNAKE_CASE      )
         a__    = torch.compile(__SCREAMING_SNAKE_CASE      )
         a__    = extract_model_from_parallel(__SCREAMING_SNAKE_CASE      )

         self.assertEqual(compiled_model._orig_mod    ,							compiled_model_unwrapped._orig_mod      )




     def  lowercase__     (       self      )		->    Optional[Any]:







         """simple docstring"""



         self.assertEqual(find_device([1, 'a', torch.tensor([1, 2, 3]      )]      )    ,							torch.device('cpu'      )      )
         self.assertEqual(find_device({'a': 1, 'b': torch.tensor([1, 2, 3]      )}      )    ,							torch.device('cpu'      )      )
         self.assertIsNone(find_device([1, 'a']      )      )


