




'''simple docstring'''



import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import OPTConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
     import os

     # The slow tests are often failing with OOM error on GPU
     # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
     # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
     UpperCAmelCase_    :					Optional[Any]					      =						'''platform'''

     import jax
     import jax.numpy as jnp

     from transformers import FlaxOPTForCausalLM, FlaxOPTModel, GPTaTokenizer







def      _UpperCamelCase	(_lowerCamelCase							:       Optional[Any]				,		_lowerCamelCase							:       Tuple				,		_lowerCamelCase							:       Optional[Any]=None				,		_lowerCamelCase							:       Tuple=None		)->				List[Any]:




     '''simple docstring'''





     if attention_mask is None:
          __snake_case         =					np.where(input_ids != config.pad_token_id				,		1				,		0		)
     return {
         "input_ids": input_ids,
         "attention_mask": attention_mask,
     }





@require_flax
class       lowerCAmelCase				:


       def __init__(				self      ,					__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE=13      ,					__SCREAMING_SNAKE_CASE=7      ,					__SCREAMING_SNAKE_CASE=True      ,					__SCREAMING_SNAKE_CASE=False      ,					__SCREAMING_SNAKE_CASE=99      ,					__SCREAMING_SNAKE_CASE=16      ,					__SCREAMING_SNAKE_CASE=2      ,					__SCREAMING_SNAKE_CASE=4      ,					__SCREAMING_SNAKE_CASE=4      ,					__SCREAMING_SNAKE_CASE="gelu"      ,					__SCREAMING_SNAKE_CASE=0.1      ,					__SCREAMING_SNAKE_CASE=0.1      ,					__SCREAMING_SNAKE_CASE=20      ,					__SCREAMING_SNAKE_CASE=2      ,					__SCREAMING_SNAKE_CASE=1      ,					__SCREAMING_SNAKE_CASE=0      ,					__SCREAMING_SNAKE_CASE=16      ,					__SCREAMING_SNAKE_CASE=16      ,					__SCREAMING_SNAKE_CASE=0.02      ,					) ->					List[str]:



            '''simple docstring'''




            __snake_case         =					parent
            __snake_case         =					batch_size
            __snake_case         =					seq_length
            __snake_case         =					is_training
            __snake_case         =					use_labels
            __snake_case         =					vocab_size
            __snake_case         =					hidden_size
            __snake_case         =					num_hidden_layers
            __snake_case         =					num_attention_heads
            __snake_case         =					intermediate_size
            __snake_case         =					hidden_act
            __snake_case         =					hidden_dropout_prob
            __snake_case         =					attention_probs_dropout_prob
            __snake_case         =					max_position_embeddings
            __snake_case         =					eos_token_id
            __snake_case         =					pad_token_id
            __snake_case         =					bos_token_id
            __snake_case         =					embed_dim
            __snake_case         =					word_embed_proj_dim
            __snake_case         =					initializer_range
            __snake_case         =					False


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



            '''simple docstring'''




            __snake_case         =					np.clip(ids_tensor([self.batch_size, self.seq_length - 1]      ,					self.vocab_size					)      ,					3      ,					self.vocab_size					)
            __snake_case         =					np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)      ,					dtype=np.intaa					))      ,					-1					)

            __snake_case         =					OPTConfig(
                vocab_size=self.vocab_size      ,					hidden_size=self.hidden_size      ,					num_hidden_layers=self.num_hidden_layers      ,					num_attention_heads=self.num_attention_heads      ,					ffn_dim=self.intermediate_size      ,					dropout=self.hidden_dropout_prob      ,					attention_dropout=self.attention_probs_dropout_prob      ,					max_position_embeddings=self.max_position_embeddings      ,					eos_token_id=self.eos_token_id      ,					bos_token_id=self.bos_token_id      ,					pad_token_id=self.pad_token_id      ,					embed_dim=self.embed_dim      ,					is_encoder_decoder=__SCREAMING_SNAKE_CASE      ,					word_embed_proj_dim=self.word_embed_proj_dim      ,					initializer_range=self.initializer_range      ,					use_cache=__SCREAMING_SNAKE_CASE      ,					)
            __snake_case         =					prepare_opt_inputs_dict(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)
            return config, inputs_dict


       def  lowerCAmelCase (				self					) ->					Dict:



            '''simple docstring'''




            __snake_case   ,      __snake_case         =					self.prepare_config_and_inputs()
            return config, inputs_dict


       def  lowerCAmelCase (				self      ,					__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					) ->					Tuple:



            '''simple docstring'''




            __snake_case         =					20
            __snake_case         =					model_class_name(__SCREAMING_SNAKE_CASE					)

            __snake_case         =					inputs_dict['''input_ids''']
            __snake_case         =					inputs_dict['''attention_mask''']

            __snake_case         =					model.init_cache(input_ids.shape[0]      ,					__SCREAMING_SNAKE_CASE					)
            __snake_case         =					jnp.ones((input_ids.shape[0], max_length)      ,					dtype='''i4'''					)

            __snake_case         =					jnp.broadcast_to(
                jnp.arange(input_ids.shape[-1] - 1					)[None, :]      ,					(input_ids.shape[0], input_ids.shape[-1] - 1)      ,					)
            __snake_case         =					model(
                input_ids[:, :-1]      ,					attention_mask=__SCREAMING_SNAKE_CASE      ,					past_key_values=__SCREAMING_SNAKE_CASE      ,					position_ids=__SCREAMING_SNAKE_CASE      ,					)

            __snake_case         =					jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]      ,					dtype='''i4'''					)
            __snake_case         =					model(
                input_ids[:, -1:]      ,					attention_mask=__SCREAMING_SNAKE_CASE      ,					past_key_values=outputs_cache.past_key_values      ,					position_ids=__SCREAMING_SNAKE_CASE      ,					)

            __snake_case         =					model(__SCREAMING_SNAKE_CASE					)

            __snake_case         =					np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])					)					)
            self.parent.assertTrue(diff < 1E-3      ,					msg=F'''Max diff is {diff}'''					)




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



            '''simple docstring'''




            __snake_case         =					20
            __snake_case         =					model_class_name(__SCREAMING_SNAKE_CASE					)

            __snake_case   ,      __snake_case         =					(
                inputs_dict['''input_ids'''],
                inputs_dict['''attention_mask'''],
            )

            __snake_case         =					jnp.concatenate(
                [
                    attention_mask,
                    jnp.zeros((attention_mask.shape[0], max_length - attention_mask.shape[1])					),
                ]      ,					axis=-1      ,					)

            __snake_case         =					model.init_cache(input_ids.shape[0]      ,					__SCREAMING_SNAKE_CASE					)
            __snake_case         =					jnp.broadcast_to(
                jnp.arange(input_ids.shape[-1] - 1					)[None, :]      ,					(input_ids.shape[0], input_ids.shape[-1] - 1)      ,					)

            __snake_case         =					model(
                input_ids[:, :-1]      ,					attention_mask=__SCREAMING_SNAKE_CASE      ,					past_key_values=__SCREAMING_SNAKE_CASE      ,					position_ids=__SCREAMING_SNAKE_CASE      ,					)
            __snake_case         =					jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]      ,					dtype='''i4'''					)
            __snake_case         =					model(
                input_ids[:, -1:]      ,					past_key_values=outputs_cache.past_key_values      ,					attention_mask=__SCREAMING_SNAKE_CASE      ,					position_ids=__SCREAMING_SNAKE_CASE      ,					)

            __snake_case         =					model(__SCREAMING_SNAKE_CASE      ,					attention_mask=__SCREAMING_SNAKE_CASE					)

            __snake_case         =					np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])					)					)
            self.parent.assertTrue(diff < 1E-3      ,					msg=F'''Max diff is {diff}'''					)





@require_flax
class       lowerCAmelCase				(	__lowerCAmelCase			,				unittest.TestCase			,				__lowerCAmelCase):
       __lowercase					: str	    =     (FlaxOPTModel, FlaxOPTForCausalLM) if is_flax_available() else ()
       __lowercase					: Dict	    =     () if is_flax_available() else ()


       def  lowerCAmelCase (				self					) ->					Tuple:



            '''simple docstring'''




            __snake_case         =					FlaxOPTModelTester(self					)


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



            '''simple docstring'''




            __snake_case   ,      __snake_case         =					self.model_tester.prepare_config_and_inputs()
            for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)


       def  lowerCAmelCase (				self					) ->					List[str]:



            '''simple docstring'''




            __snake_case   ,      __snake_case         =					self.model_tester.prepare_config_and_inputs()
            for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward_with_attn_mask(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)




       @slow
       def  lowerCAmelCase (				self					) ->					str:



            '''simple docstring'''




            for model_class_name in self.all_model_classes:
                 __snake_case         =					model_class_name.from_pretrained('''facebook/opt-125m'''					)
                 __snake_case         =					np.ones((1, 1)					) * model.config.eos_token_id
                 __snake_case         =					model(__SCREAMING_SNAKE_CASE					)
                 self.assertIsNotNone(__SCREAMING_SNAKE_CASE					)





@require_sentencepiece
@require_flax
class       lowerCAmelCase				(	unittest.TestCase):


       @slow
       def  lowerCAmelCase (				self					) ->					str:



            '''simple docstring'''




            __snake_case         =					FlaxOPTModel.from_pretrained('''facebook/opt-350m'''					)
            __snake_case         =					jnp.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]					)
            __snake_case         =					model(input_ids=__SCREAMING_SNAKE_CASE					).last_hidden_state
            __snake_case         =					(1, 11, 512)
            self.assertEqual(output.shape      ,					__SCREAMING_SNAKE_CASE					)
            __snake_case         =					jnp.array(
                [[-0.2_867, -1.9_256, -0.3_062], [-1.2_711, -0.1_337, -0.1_897], [0.4_109, 0.1_187, -1.3_142]]					)
            self.assertTrue(jnp.allclose(output[:, :3, :3]      ,					__SCREAMING_SNAKE_CASE      ,					atol=4E-2					)					)





@require_flax
@slow
class       lowerCAmelCase				(	unittest.TestCase):


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



            '''simple docstring'''




            super().setUp()
            __snake_case         =					'''facebook/opt-350m'''




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



            '''simple docstring'''




            __snake_case         =					FlaxOPTForCausalLM.from_pretrained(self.path_model					)
            __snake_case         =					GPTaTokenizer.from_pretrained(self.path_model					)

            __snake_case         =					[
                '''Today is a beautiful day and I want to''',
                '''In the city of''',
                '''Paris is the capital of France and''',
                '''Computers and mobile phones have taken''',
            ]
            # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
            __snake_case         =					tokenizer(__SCREAMING_SNAKE_CASE      ,					return_tensors='''jax'''      ,					padding=__SCREAMING_SNAKE_CASE      ,					add_special_tokens=__SCREAMING_SNAKE_CASE					)
            __snake_case         =					model(inputs.input_ids      ,					attention_mask=inputs.attention_mask					)[0].mean(axis=-1					)
            __snake_case         =					jnp.array(
                [
                    [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670],
                    [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822],
                    [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703],
                    [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477],
                ]					)
            self.assertTrue(jnp.allclose(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE      ,					atol=4E-2					)					)

            __snake_case         =					jax.jit(__SCREAMING_SNAKE_CASE					)
            __snake_case         =					model(inputs.input_ids      ,					attention_mask=inputs.attention_mask					)[0].mean(axis=-1					)
            self.assertTrue(jnp.allclose(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE      ,					atol=4E-2					)					)





@require_flax
@slow
class       lowerCAmelCase				(	unittest.TestCase):


       @property
       def  lowerCAmelCase (				self					) ->					Optional[int]:



            '''simple docstring'''




            return [
                "Today is a beautiful day and I want",
                "In the city of",
                "Paris is the capital of France and",
                "Computers and mobile phones have taken",
            ]


       def  lowerCAmelCase (				self					) ->					Any:



            '''simple docstring'''




            __snake_case         =					'''facebook/opt-125m'''

            __snake_case         =					[
                '''Today is a beautiful day and I want to''',
                '''In the city of New York, the city''',
                '''Paris is the capital of France and the capital''',
                '''Computers and mobile phones have taken over the''',
            ]

            __snake_case         =					[]

            __snake_case         =					FlaxOPTForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE					)
            __snake_case         =					GPTaTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE					)

            for prompt in self.prompts:
                 __snake_case         =					tokenizer(__SCREAMING_SNAKE_CASE      ,					return_tensors='''jax'''					).input_ids

                 __snake_case         =					model.generate(__SCREAMING_SNAKE_CASE      ,					max_length=10					)
                 __snake_case         =					generated_ids[0]

                 __snake_case         =					tokenizer.batch_decode(__SCREAMING_SNAKE_CASE      ,					skip_special_tokens=__SCREAMING_SNAKE_CASE					)
                 predicted_outputs += generated_string

            self.assertListEqual(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)


       def  lowerCAmelCase (				self					) ->					List[str]:



            '''simple docstring'''




            __snake_case         =					'''facebook/opt-350m'''

            __snake_case         =					[
                '''Today is a beautiful day and I want to''',
                '''In the city of San Francisco, the city''',
                '''Paris is the capital of France and the capital''',
                '''Computers and mobile phones have taken over the''',
            ]

            __snake_case         =					[]
            __snake_case         =					FlaxOPTForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE					)
            __snake_case         =					GPTaTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE					)

            for prompt in self.prompts:
                 __snake_case         =					tokenizer(__SCREAMING_SNAKE_CASE      ,					return_tensors='''jax'''					).input_ids

                 __snake_case         =					model.generate(__SCREAMING_SNAKE_CASE      ,					max_length=10					)
                 __snake_case         =					generated_ids[0]

                 __snake_case         =					tokenizer.batch_decode(__SCREAMING_SNAKE_CASE      ,					skip_special_tokens=__SCREAMING_SNAKE_CASE					)
                 predicted_outputs += generated_string

            self.assertListEqual(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)


       def  lowerCAmelCase (				self					) ->					List[str]:



            '''simple docstring'''




            __snake_case         =					'''facebook/opt-125m'''
            __snake_case         =					[
                '''Today is a beautiful day and I want to thank''',
                '''In the city of Rome Canaver Canaver Canaver Canaver''',
            ]
            __snake_case         =					FlaxOPTForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE					)
            __snake_case         =					GPTaTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE					)
            __snake_case         =					tokenizer(
                [
                    '''Today is a beautiful day and I want to''',
                    '''In the city of''',
                ]      ,					return_tensors='''jax'''      ,					padding=__SCREAMING_SNAKE_CASE      ,					)

            __snake_case         =					jax.jit(model.generate					)

            __snake_case         =					jit_generate(inputs['''input_ids''']      ,					attention_mask=inputs['''attention_mask''']					).sequences

            __snake_case         =					tokenizer.batch_decode(__SCREAMING_SNAKE_CASE      ,					skip_special_tokens=__SCREAMING_SNAKE_CASE					)

            self.assertIsNotNone(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)




       def  lowerCAmelCase (				self					) ->					Any:



            '''simple docstring'''




            __snake_case         =					'''facebook/opt-350m'''

            __snake_case         =					GPTaTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE					)
            __snake_case         =					FlaxOPTForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE					)

            __snake_case         =					'''left'''

            # use different length sentences to test batching
            __snake_case         =					[
                '''Hello, my dog is a little''',
                '''Today, I''',
            ]

            __snake_case         =					tokenizer(__SCREAMING_SNAKE_CASE      ,					return_tensors='''jax'''      ,					padding=__SCREAMING_SNAKE_CASE					)
            __snake_case         =					inputs['''input_ids''']

            __snake_case         =					model.generate(input_ids=__SCREAMING_SNAKE_CASE      ,					attention_mask=inputs['''attention_mask''']      ,					trace=__SCREAMING_SNAKE_CASE					)

            __snake_case         =					tokenizer(sentences[0]      ,					return_tensors='''jax'''					).input_ids
            __snake_case         =					model.generate(input_ids=__SCREAMING_SNAKE_CASE					)

            __snake_case         =					inputs_non_padded.shape[-1] - inputs['''attention_mask'''][-1].sum()
            __snake_case         =					tokenizer(sentences[1]      ,					return_tensors='''jax'''					).input_ids
            __snake_case         =					model.generate(input_ids=__SCREAMING_SNAKE_CASE      ,					max_length=model.config.max_length - num_paddings					)

            __snake_case         =					tokenizer.batch_decode(outputs[0]      ,					skip_special_tokens=__SCREAMING_SNAKE_CASE					)
            __snake_case         =					tokenizer.decode(output_non_padded[0][0]      ,					skip_special_tokens=__SCREAMING_SNAKE_CASE					)
            __snake_case         =					tokenizer.decode(output_padded[0][0]      ,					skip_special_tokens=__SCREAMING_SNAKE_CASE					)

            __snake_case         =					[
                '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''',
                '''Today, I was in the middle of a conversation with a friend about the''',
            ]
            self.assertListEqual(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)
            self.assertListEqual(__SCREAMING_SNAKE_CASE      ,					[non_padded_sentence, padded_sentence]					)












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


UpperCAmelCase_    :					Optional[Any]					      =						get_logger(__name__)







def      _UpperCamelCase	(_lowerCamelCase							:       Dict		)->				Tuple:




     '''simple docstring'''





     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       lowerCAmelCase				(	__lowerCAmelCase):
       __lowercase					: int	    =     False  # to tell pytest it's not a test class


       @staticmethod
       def  lowerCAmelCase (				__SCREAMING_SNAKE_CASE					) ->					Optional[int]:



            '''simple docstring'''




            __snake_case         =					parser.add_parser('''test'''      ,					help='''Test dataset implementation.'''					)
            test_parser.add_argument('''--name'''      ,					type=__SCREAMING_SNAKE_CASE      ,					default=__SCREAMING_SNAKE_CASE      ,					help='''Dataset processing name'''					)
            test_parser.add_argument(
                '''--cache_dir'''      ,					type=__SCREAMING_SNAKE_CASE      ,					default=__SCREAMING_SNAKE_CASE      ,					help='''Cache directory where the datasets are stored.'''      ,					)
            test_parser.add_argument(
                '''--data_dir'''      ,					type=__SCREAMING_SNAKE_CASE      ,					default=__SCREAMING_SNAKE_CASE      ,					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=__SCREAMING_SNAKE_CASE      ,					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'''




            __snake_case         =					dataset
            __snake_case         =					name
            __snake_case         =					cache_dir
            __snake_case         =					data_dir
            __snake_case         =					all_configs
            __snake_case         =					save_infos
            __snake_case         =					ignore_verifications
            __snake_case         =					force_redownload
            __snake_case         =					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:
                 __snake_case         =					True




       def  lowerCAmelCase (				self					) ->					Dict:



            '''simple docstring'''




            fl_logger().setLevel(__SCREAMING_SNAKE_CASE					)
            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					)
            __snake_case   ,      __snake_case         =					self._dataset, self._name
            __snake_case         =					dataset_module_factory(__SCREAMING_SNAKE_CASE					)
            __snake_case         =					import_main_class(module.module_path					)
            __snake_case         =					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=__SCREAMING_SNAKE_CASE      ,					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})'''					)
                 __snake_case         =					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=__SCREAMING_SNAKE_CASE      ,					)
                 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:
                      __snake_case         =					os.path.join(builder_cls.get_imported_module_dir()      ,					'''README.md'''					)
                      __snake_case         =					Path(__SCREAMING_SNAKE_CASE					).name + '''.py'''
                      __snake_case         =					os.path.join(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)
                      if os.path.isfile(__SCREAMING_SNAKE_CASE					):
                           __snake_case         =					os.path.dirname(__SCREAMING_SNAKE_CASE					)
                      elif os.path.isfile(__SCREAMING_SNAKE_CASE					):
                           __snake_case         =					path
                      elif os.path.isdir(__SCREAMING_SNAKE_CASE					):  # for local directories containing only data files
                           __snake_case         =					path
                      else:  # in case of a remote dataset
                           __snake_case         =					None
                           print(F'''Dataset card saved at {dataset_readme_path}'''					)

                      # Move dataset_info back to the user
                      if dataset_dir is not None:
                           __snake_case         =					os.path.join(__SCREAMING_SNAKE_CASE      ,					'''README.md'''					)
                           copyfile(__SCREAMING_SNAKE_CASE      ,					__SCREAMING_SNAKE_CASE					)
                           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					)
                      __snake_case         =					os.path.join(self._cache_dir      ,					datasets.config.DOWNLOADED_DATASETS_DIR					)
                      if os.path.isdir(__SCREAMING_SNAKE_CASE					):
                           logger.warning(F'''Clearing cache at {download_dir}'''					)
                           rmtree(__SCREAMING_SNAKE_CASE					)

            print('''Test successful.'''					)






