code: 
  
  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						=     get_logger(__name__)
  
  
  
  
  def 				a__	(	lowerCAmelCase						)  ->   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 			lowerCamelCase  (					_SCREAMING_SNAKE_CASE      ):
  
  
    '''simple docstring'''
  
  
  
  
  
  
  
    SCREAMING_SNAKE_CASE							=     False  # to tell pytest it's not a test class
  
  
  
    @staticmethod
    def    _a			(_lowerCamelCase  ):
  
  
          """simple docstring"""
  
          UpperCAmelCase__ :       List[str]						=						parser.add_parser("""test"""       ,					help="""Test dataset implementation."""  )
          test_parser.add_argument("""--name"""       ,					type=__A       ,					default=__A       ,					help="""Dataset processing name"""  )
          test_parser.add_argument(
              """--cache_dir"""       ,					type=__A       ,					default=__A       ,					help="""Cache directory where the datasets are stored."""       ,					)
          test_parser.add_argument(
              """--data_dir"""       ,					type=__A       ,					default=__A       ,					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=__A       ,					help="""Name of the dataset to download"""  )
          test_parser.set_defaults(func=_test_command_factory  )
  
  
  
    def __init__(self       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					_lowerCamelCase       ,					):
  
  
          """simple docstring"""
  
          UpperCAmelCase__ :       Dict						=						dataset
          UpperCAmelCase__ :       Optional[int]						=						name
          UpperCAmelCase__ :       int						=						cache_dir
          UpperCAmelCase__ :       Optional[int]						=						data_dir
          UpperCAmelCase__ :       List[Any]						=						all_configs
          UpperCAmelCase__ :       Any						=						save_infos
          UpperCAmelCase__ :       List[Any]						=						ignore_verifications
          UpperCAmelCase__ :       Tuple						=						force_redownload
          UpperCAmelCase__ :       List[str]						=						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:
                UpperCAmelCase__ :       str						=						True
  
  
  
  
    def    _a			(self  ):
  
  
          """simple docstring"""
  
          fl_logger().setLevel(__A  )
          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  )
          UpperCAmelCase__				,		UpperCAmelCase__ :       List[Any]						=						self._dataset, self._name
          UpperCAmelCase__ :       Optional[int]						=						dataset_module_factory(__A  )
          UpperCAmelCase__ :       Dict						=						import_main_class(module.module_path  )
          UpperCAmelCase__ :       Union[str, Any]						=						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=__A       ,					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})"""  )
                UpperCAmelCase__ :       Union[str, Any]						=						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=__A       ,					)
                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:
                      UpperCAmelCase__ :       List[str]						=						os.path.join(builder_cls.get_imported_module_dir()       ,					"""README.md"""  )
                      UpperCAmelCase__ :       List[Any]						=						Path(__A  ).name + """.py"""
                      UpperCAmelCase__ :       Optional[Any]						=						os.path.join(__A       ,					__A  )
                      if os.path.isfile(__A  ):
                            UpperCAmelCase__ :       Union[str, Any]						=						os.path.dirname(__A  )
                      elif os.path.isfile(__A  ):
                            UpperCAmelCase__ :       Any						=						path
                      elif os.path.isdir(__A  ):  # for local directories containing only data files
                            UpperCAmelCase__ :       Optional[int]						=						path
                      else:  # in case of a remote dataset
                            UpperCAmelCase__ :       int						=						None
                            print(F"""Dataset card saved at {dataset_readme_path}"""  )
  
                      # Move dataset_info back to the user
                      if dataset_dir is not None:
                            UpperCAmelCase__ :       str						=						os.path.join(__A       ,					"""README.md"""  )
                            copyfile(__A       ,					__A  )
                            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  )
                      UpperCAmelCase__ :       Tuple						=						os.path.join(self._cache_dir       ,					datasets.config.DOWNLOADED_DATASETS_DIR  )
                      if os.path.isdir(__A  ):
                            logger.warning(F"""Clearing cache at {download_dir}"""  )
                            rmtree(__A  )
  
          print("""Test successful."""  )
  
  
style_context: 
  
  """simple docstring"""
  import argparse
  import time
  
  import torch
  import transformers
  from measures_util import end_measure, log_measures, start_measure
  from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoTokenizer
  
  from accelerate.utils import compute_module_sizes
  
  
  _A						=     {
      """gpt-j-6b""": {"""is_causal""": True, """model""": """sgugger/sharded-gpt-j-6B""", """tokenizer""": """EleutherAI/gpt-j-6B"""},
      """gpt-neox""": {"""is_causal""": True, """model""": """EleutherAI/gpt-neox-20b"""},
      """opt""": {"""is_causal""": True, """model""": """facebook/opt-30b"""},
      """T0pp""": {"""is_causal""": False, """model""": """bigscience/T0pp""", """model_revision""": """sharded"""},
  }
  
  _A						=     [
      """Hello, my name is""",
      """Are unicorns real? Unicorns are""",
      """For the first time in several years,""",
      """My name is Julien and I am""",
      """The goal of life is""",
      """Whenever I'm sad, I like to""",
  ]
  
  
  
  
  def 				a__	(	)  ->   Optional[Any]:
        UpperCAmelCase__ :       int						=						argparse.ArgumentParser(description="""Run and time generations on a big model using Accelerate."""						)
        parser.add_argument("""model_name""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The name of the model to try."""						)
        parser.add_argument(
            """--tokenizer_name""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The name of the tokenizer (if different from the model."""						)
        parser.add_argument("""--is_causal""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""Whether or not the model is causal."""						)
        parser.add_argument(
            """--model_revision""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The revision to use for the model checkpoint."""						)
        parser.add_argument("""--torch_dtype""" ,  type=lowerCAmelCase ,  default=lowerCAmelCase ,  help="""The dtype for the model."""						)
        parser.add_argument("""--disk_offload""" ,  action="""store_true"""						)
  
        UpperCAmelCase__ :       Union[str, Any]						=						parser.parse_args()
  
        # Sanitize args
        if args.model_name in DEFAULT_MODELS:
              UpperCAmelCase__ :       Any						=						DEFAULT_MODELS[args.model_name]
              UpperCAmelCase__ :       Tuple						=						defaults["""model"""]
              if args.tokenizer_name is None:
                    UpperCAmelCase__ :       Optional[Any]						=						defaults.get("""tokenizer""" ,  args.model_name						)
              if args.is_causal is None:
                    UpperCAmelCase__ :       List[Any]						=						defaults["""is_causal"""]
              if args.model_revision is None:
                    UpperCAmelCase__ :       Optional[int]						=						defaults.get("""model_revision""" ,  """main"""						)
  
        if args.is_causal is None:
              raise ValueError("""Could not infer the default for `--is_causal`, pass either True or False for it."""						)
        if args.tokenizer_name is None:
              UpperCAmelCase__ :       str						=						args.model_name
        if args.model_revision is None:
              UpperCAmelCase__ :       List[str]						=						"""main"""
  
        return args
  
  
  
  
  def 				a__	(	)  ->   List[Any]:
        transformers.utils.logging.set_verbosity_error()
        UpperCAmelCase__ :       Optional[int]						=						parse_args()
  
        if args.torch_dtype is None:
              UpperCAmelCase__ :       List[str]						=						AutoConfig.from_pretrained(args.model_name						)
              UpperCAmelCase__ :       Optional[Any]						=						getattr(lowerCAmelCase ,  """torch_dtype""" ,  torch.floataa						)
        else:
              UpperCAmelCase__ :       Union[str, Any]						=						getattr(lowerCAmelCase ,  args.torch_dtype						)
        UpperCAmelCase__ :       List[Any]						=						AutoModelForCausalLM if args.is_causal else AutoModelForSeqaSeqLM
        UpperCAmelCase__ :       List[str]						=						{
            """torch_dtype""": torch_dtype,
            """revision""": args.model_revision,
        }
        if args.disk_offload:
              UpperCAmelCase__ :       List[str]						=						"""tmp_offload"""
              UpperCAmelCase__ :       int						=						True
  
        UpperCAmelCase__ :       Any						=						start_measure()
        UpperCAmelCase__ :       Optional[int]						=						model_cls.from_pretrained(args.model_name ,  device_map="""auto""" ,  **lowerCAmelCase						)
        UpperCAmelCase__ :       Any						=						end_measure(lowerCAmelCase						)
        log_measures(lowerCAmelCase ,  """Model loading"""						)
  
        UpperCAmelCase__ :       List[str]						=						compute_module_sizes(lowerCAmelCase						)
        UpperCAmelCase__ :       Dict						=						{v: 0 for v in model.hf_device_map.values()}
        for module, device in model.hf_device_map.items():
              device_size[device] += module_sizes[module]
        UpperCAmelCase__ :       Optional[Any]						=						"""\n""".join([F"""- {device}: {size // 2**20}MiB""" for device, size in device_size.items()]						)
        print(F"""\nTheoretical use:\n{message}"""						)
  
        UpperCAmelCase__ :       Tuple						=						AutoTokenizer.from_pretrained(args.tokenizer_name						)
  
        UpperCAmelCase__ :       List[str]						=						start_measure()
        UpperCAmelCase__ :       List[Any]						=						[]
        UpperCAmelCase__ :       Tuple						=						[]
        UpperCAmelCase__ :       Optional[Any]						=						[]
        for prompt in PROMPTS:
              UpperCAmelCase__ :       Any						=						tokenizer(lowerCAmelCase ,  return_tensors="""pt"""						).to(0						)
              UpperCAmelCase__ :       List[str]						=						inputs["""input_ids"""][0].tolist()
              UpperCAmelCase__ :       Dict						=						time.time()
              UpperCAmelCase__ :       List[str]						=						model.generate(inputs["""input_ids"""]						)
              UpperCAmelCase__ :       str						=						time.time()
              UpperCAmelCase__ :       str						=						outputs[0].tolist()
              UpperCAmelCase__ :       Optional[Any]						=						len(lowerCAmelCase						) if outputs[: len(lowerCAmelCase						)] != tokens else len(lowerCAmelCase						) - len(lowerCAmelCase						)
              UpperCAmelCase__ :       Tuple						=						after_generate - before_generate
  
              UpperCAmelCase__ :       Optional[Any]						=						tokenizer.decode(lowerCAmelCase ,  skip_special_tokens=lowerCAmelCase						)
              texts_outs.append(lowerCAmelCase						)
              generation_times.append(lowerCAmelCase						)
              gen_tokens.append(lowerCAmelCase						)
              print(F"""Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n"""						)
  
        UpperCAmelCase__ :       int						=						end_measure(lowerCAmelCase						)
        log_measures(lowerCAmelCase ,  """Model generation"""						)
  
        UpperCAmelCase__ :       Any						=						[gen / tok for gen, tok in zip(lowerCAmelCase ,  lowerCAmelCase						)]
        UpperCAmelCase__ :       List[Any]						=						sum(lowerCAmelCase						) / len(lowerCAmelCase						)
        print(F"""Average time of generation per token: {avg_gen:.2f}s"""						)
        print(F"""First generation (avg time per token): {generation_times_per_token[0]:.2f}s"""						)
        UpperCAmelCase__ :       Any						=						sum(generation_times_per_token[1:]						) / (len(lowerCAmelCase						) - 1)
        print(F"""Average time of generation per token (excluding the first): {avg_gen:.2f}s"""						)
  
  
  if __name__ == "__main__":
      main()
  
  