
"""simple docstring"""

import argparse
import gc
import os
import threading

import evaluate
import psutil
import torch
from datasets import load_dataset
from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig
from torch.utils.data import DataLoader
from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    get_linear_schedule_with_warmup,
    set_seed,
)

from accelerate import Accelerator, DistributedType, FullyShardedDataParallelPlugin


########################################################################
# This is a fully working simple example to use Accelerate
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#   - FSDP
#
# This example also demonstrates the checkpointing and sharding capabilities
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


SCREAMING_SNAKE_CASE_			    =  16
SCREAMING_SNAKE_CASE_			    =  32




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






    """simple docstring"""




    return int(x / 2**20       )
class    _UpperCAmelCase							:




      def __enter__(							self							)  ->    List[Any]:
          gc.collect()
          torch.cuda.empty_cache()
          torch.cuda.reset_max_memory_allocated()  # reset the peak gauge to zero
          UpperCAmelCase  	=    torch.cuda.memory_allocated()
          UpperCAmelCase  	=    psutil.Process()

          UpperCAmelCase  	=    self.cpu_mem_used()
          UpperCAmelCase  	=    True
          UpperCAmelCase  	=    threading.Thread(target=self.peak_monitor_func							)
          UpperCAmelCase  	=    True
          peak_monitor_thread.start()
          return self




      def 			a_					(							self							)  ->    Dict:
          return self.process.memory_info().rss




      def 			a_					(							self							)  ->    str:
          UpperCAmelCase  	=    -1

          while True:
              UpperCAmelCase  	=    max(self.cpu_mem_used()      ,				self.cpu_peak							)

              # can't sleep or will not catch the peak right (this comment is here on purpose)
              # time.sleep(0.001) # 1msec

              if not self.peak_monitoring:
                  break




      def __exit__(							self      ,				*lowercase_							)  ->    Any:
          UpperCAmelCase  	=    False

          gc.collect()
          torch.cuda.empty_cache()
          UpperCAmelCase  	=    torch.cuda.memory_allocated()
          UpperCAmelCase  	=    torch.cuda.max_memory_allocated()
          UpperCAmelCase  	=    bamb(self.end - self.begin							)
          UpperCAmelCase  	=    bamb(self.peak - self.begin							)

          UpperCAmelCase  	=    self.cpu_mem_used()
          UpperCAmelCase  	=    bamb(self.cpu_end - self.cpu_begin							)
          UpperCAmelCase  	=    bamb(self.cpu_peak - self.cpu_begin							)
          # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")


# For testing only
if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1":
   from accelerate.test_utils.training import mocked_dataloaders

   SCREAMING_SNAKE_CASE_			    =  mocked_dataloaders  # noqa: F811




def 			lowercase__  (    lowerCAmelCase :    Union[str, Any]       , lowerCAmelCase :    int       )       ->					Optional[Any]:






    """simple docstring"""




    if os.environ.get('TESTING_MOCKED_DATALOADERS'       , lowerCAmelCase       ) == "1":
        UpperCAmelCase  	=    2

    # New Code #
    # Pass the advanced FSDP settings not part of the accelerate config by creating fsdp_plugin
    UpperCAmelCase  	=    FullyShardedDataParallelPlugin(
        state_dict_config=FullStateDictConfig(offload_to_cpu=lowerCAmelCase       , ranka_only=lowerCAmelCase       )       , optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=lowerCAmelCase       , ranka_only=lowerCAmelCase       )       , )

    # Initialize accelerator
    if args.with_tracking:
        UpperCAmelCase  	=    Accelerator(
            cpu=args.cpu       , mixed_precision=args.mixed_precision       , log_with='wandb'       , project_dir=args.logging_dir       , fsdp_plugin=lowerCAmelCase       , )
    else:
        UpperCAmelCase  	=    Accelerator(fsdp_plugin=lowerCAmelCase       )
    accelerator.print(accelerator.distributed_type       )

    if hasattr(args.checkpointing_steps       , 'isdigit'       ):
        if args.checkpointing_steps == "epoch":
            UpperCAmelCase  	=    args.checkpointing_steps
        elif args.checkpointing_steps.isdigit():
            UpperCAmelCase  	=    int(args.checkpointing_steps       )
        else:
            raise ValueError(
                F"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."       )
    else:
        UpperCAmelCase  	=    None
    # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
    UpperCAmelCase  	=    config['lr']
    UpperCAmelCase  	=    int(config['num_epochs']       )
    UpperCAmelCase  	=    int(config['seed']       )
    UpperCAmelCase  	=    int(config['batch_size']       )

    # We need to initialize the trackers we use, and also store our configuration
    if args.with_tracking:
        UpperCAmelCase  	=    vars(lowerCAmelCase       )
        accelerator.init_trackers('fsdp_glue_no_trainer'       , lowerCAmelCase       )

    UpperCAmelCase  	=    AutoTokenizer.from_pretrained(args.model_name_or_path       )
    UpperCAmelCase  	=    load_dataset('glue'       , 'mrpc'       )
    UpperCAmelCase  	=    evaluate.load('glue'       , 'mrpc'       )

    def tokenize_function(lowerCAmelCase :    List[str]       ):
        # max_length=None => use the model max length (it's actually the default)
        UpperCAmelCase  	=    tokenizer(examples['sentence1']       , examples['sentence2']       , truncation=lowerCAmelCase       , max_length=lowerCAmelCase       )
        return outputs

    # Apply the method we just defined to all the examples in all the splits of the dataset
    # starting with the main process first:
    with accelerator.main_process_first():
        UpperCAmelCase  	=    datasets.map(
            lowerCAmelCase       , batched=lowerCAmelCase       , remove_columns=['idx', 'sentence1', 'sentence2']       , )

    # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
    # transformers library
    UpperCAmelCase  	=    tokenized_datasets.rename_column('label'       , 'labels'       )

    # If the batch size is too big we use gradient accumulation
    UpperCAmelCase  	=    1
    if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
        UpperCAmelCase  	=    batch_size // MAX_GPU_BATCH_SIZE
        UpperCAmelCase  	=    MAX_GPU_BATCH_SIZE

    def collate_fn(lowerCAmelCase :    Optional[int]       ):
        # On TPU it's best to pad everything to the same length or training will be very slow.
        UpperCAmelCase  	=    128 if accelerator.distributed_type == DistributedType.TPU else None
        # When using mixed precision we want round multiples of 8/16
        if accelerator.mixed_precision == "fp8":
            UpperCAmelCase  	=    16
        elif accelerator.mixed_precision != "no":
            UpperCAmelCase  	=    8
        else:
            UpperCAmelCase  	=    None

        return tokenizer.pad(
            lowerCAmelCase       , padding='longest'       , max_length=lowerCAmelCase       , pad_to_multiple_of=lowerCAmelCase       , return_tensors='pt'       , )

    # Instantiate dataloaders.
    UpperCAmelCase  	=    DataLoader(
        tokenized_datasets['train']       , shuffle=lowerCAmelCase       , collate_fn=lowerCAmelCase       , batch_size=lowerCAmelCase       )
    UpperCAmelCase  	=    DataLoader(
        tokenized_datasets['validation']       , shuffle=lowerCAmelCase       , collate_fn=lowerCAmelCase       , batch_size=lowerCAmelCase       )

    set_seed(lowerCAmelCase       )

    # Instantiate the model (we build the model here so that the seed also control new weights initialization)
    UpperCAmelCase  	=    AutoModelForSequenceClassification.from_pretrained(
        args.model_name_or_path       , return_dict=lowerCAmelCase       , low_cpu_mem_usage=lowerCAmelCase       )

    # New Code #
    # For FSDP feature, it is highly recommended and efficient to prepare the model before creating optimizer
    UpperCAmelCase  	=    accelerator.prepare(lowerCAmelCase       )
    accelerator.print(lowerCAmelCase       )

    # Instantiate optimizer
    # New Code #
    # For FSDP feature, at present it doesn't support multiple parameter groups,
    # so we need to create a single parameter group for the whole model
    UpperCAmelCase  	=    torch.optim.AdamW(params=model.parameters()       , lr=lowerCAmelCase       , weight_decay=2E-4       )

    # Instantiate scheduler
    UpperCAmelCase  	=    get_linear_schedule_with_warmup(
        optimizer=lowerCAmelCase       , num_warmup_steps=10       , num_training_steps=(len(lowerCAmelCase       ) * num_epochs) // gradient_accumulation_steps       , )

    # New Code #
    # For FSDP feature, prepare everything except the model as we have already prepared the model
    # before creating the optimizer
    # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
    # prepare method.
    UpperCAmelCase	,							UpperCAmelCase	,							UpperCAmelCase	,							UpperCAmelCase  	=    accelerator.prepare(
        lowerCAmelCase       , lowerCAmelCase       , lowerCAmelCase       , lowerCAmelCase       )

    UpperCAmelCase  	=    0

    # Potentially load in the weights and states from a previous save
    if args.resume_from_checkpoint:
        if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
            accelerator.print(F"Resumed from checkpoint: {args.resume_from_checkpoint}"       )
            accelerator.load_state(args.resume_from_checkpoint       )
            UpperCAmelCase  	=    os.path.basename(args.resume_from_checkpoint       )
        else:
            # Get the most recent checkpoint
            UpperCAmelCase  	=    [f.name for f in os.scandir(os.getcwd()       ) if f.is_dir()]
            dirs.sort(key=os.path.getctime       )
            UpperCAmelCase  	=    dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
        # Extract `epoch_{i}` or `step_{i}`
        UpperCAmelCase  	=    os.path.splitext(lowerCAmelCase       )[0]

        if "epoch" in training_difference:
            num_epochs -= int(training_difference.replace('epoch_'       , ''       )       )
            UpperCAmelCase  	=    None
        else:
            UpperCAmelCase  	=    int(training_difference.replace('step_'       , ''       )       )
            num_epochs -= resume_step // len(lowerCAmelCase       )
            # If resuming by step, we also need to know exactly how far into the DataLoader we went
            UpperCAmelCase  	=    (num_epochs * len(lowerCAmelCase       )) - resume_step

    # Now we train the model
    for epoch in range(lowerCAmelCase       ):
        # New Code #
        # context manager to track the peak memory usage during the training epoch
        with TorchTracemalloc() as tracemalloc:
            model.train()
            if args.with_tracking:
                UpperCAmelCase  	=    0
            for step, batch in enumerate(lowerCAmelCase       ):
                # We need to skip steps until we reach the resumed step
                if args.resume_from_checkpoint and epoch == 0:
                    if resume_step is not None and step < resume_step:
                        pass
                # We could avoid this line since we set the accelerator with `device_placement=True`.
                batch.to(accelerator.device       )
                UpperCAmelCase  	=    model(**lowerCAmelCase       )
                UpperCAmelCase  	=    outputs.loss
                UpperCAmelCase  	=    loss / gradient_accumulation_steps
                # We keep track of the loss at each epoch
                if args.with_tracking:
                    total_loss += loss.detach().float()
                accelerator.backward(lowerCAmelCase       )
                if step % gradient_accumulation_steps == 0:
                    optimizer.step()
                    lr_scheduler.step()
                    optimizer.zero_grad()
                    # accelerator.print(lr_scheduler.get_lr())

                overall_step += 1

                if isinstance(lowerCAmelCase       , lowerCAmelCase       ):
                    UpperCAmelCase  	=    F"step_{overall_step}"
                    if overall_step % checkpointing_steps == 0:
                        if args.output_dir is not None:
                            UpperCAmelCase  	=    os.path.join(args.output_dir       , lowerCAmelCase       )
                        accelerator.save_state(lowerCAmelCase       )
        # New Code #
        # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
        accelerator.print('Memory before entering the train : {}'.format(bamb(tracemalloc.begin       )       )       )
        accelerator.print('Memory consumed at the end of the train (end-begin): {}'.format(tracemalloc.used       )       )
        accelerator.print('Peak Memory consumed during the train (max-begin): {}'.format(tracemalloc.peaked       )       )
        accelerator.print(
            'Total Peak Memory consumed during the train (max): {}'.format(
                tracemalloc.peaked + bamb(tracemalloc.begin       )       )       )
        # Logging the peak memory usage of the GPU to the tracker
        if args.with_tracking:
            accelerator.log(
                {
                    'train_total_peak_memory': tracemalloc.peaked + bamb(tracemalloc.begin       ),
                }       , step=lowerCAmelCase       , )

        # New Code #
        # context manager to track the peak memory usage during the evaluation
        with TorchTracemalloc() as tracemalloc:
            model.eval()
            for step, batch in enumerate(lowerCAmelCase       ):
                # We could avoid this line since we set the accelerator with `device_placement=True`.
                batch.to(accelerator.device       )
                with torch.no_grad():
                    UpperCAmelCase  	=    model(**lowerCAmelCase       )
                UpperCAmelCase  	=    outputs.logits.argmax(dim=-1       )
                UpperCAmelCase	,							UpperCAmelCase  	=    accelerator.gather_for_metrics((predictions, batch['labels'])       )
                metric.add_batch(
                    predictions=lowerCAmelCase       , references=lowerCAmelCase       , )

            UpperCAmelCase  	=    metric.compute()
            # Use accelerator.print to print only on the main process.
            accelerator.print(F"epoch {epoch}:"       , lowerCAmelCase       )
            if args.with_tracking:
                accelerator.log(
                    {
                        'accuracy': eval_metric['accuracy'],
                        'f1': eval_metric['f1'],
                        'train_loss': total_loss.item() / len(lowerCAmelCase       ),
                    }       , step=lowerCAmelCase       , )

            if checkpointing_steps == "epoch":
                UpperCAmelCase  	=    F"epoch_{epoch}"
                if args.output_dir is not None:
                    UpperCAmelCase  	=    os.path.join(args.output_dir       , lowerCAmelCase       )
                accelerator.save_state(lowerCAmelCase       )
        # New Code #
        # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
        accelerator.print('Memory before entering the eval : {}'.format(bamb(tracemalloc.begin       )       )       )
        accelerator.print('Memory consumed at the end of the eval (end-begin): {}'.format(tracemalloc.used       )       )
        accelerator.print('Peak Memory consumed during the eval (max-begin): {}'.format(tracemalloc.peaked       )       )
        accelerator.print(
            'Total Peak Memory consumed during the eval (max): {}'.format(tracemalloc.peaked + bamb(tracemalloc.begin       )       )       )
        # Logging the peak memory usage of the GPU to the tracker
        if args.with_tracking:
            accelerator.log(
                {
                    'eval_total_peak_memory': tracemalloc.peaked + bamb(tracemalloc.begin       ),
                }       , step=lowerCAmelCase       , )

    if args.with_tracking:
        accelerator.end_training()




def 			lowercase__  (    )       ->					Tuple:






    """simple docstring"""




    UpperCAmelCase  	=    argparse.ArgumentParser(description='Simple example of training script.'       )
    parser.add_argument(
        '--mixed_precision'       , type=lowerCAmelCase       , default=lowerCAmelCase       , choices=['no', 'fp16', 'bf16', 'fp8']       , help='Whether to use mixed precision. Choose'
        'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'
        'and an Nvidia Ampere GPU.'       , )
    parser.add_argument('--cpu'       , action='store_true'       , help='If passed, will train on the CPU.'       )
    parser.add_argument(
        '--checkpointing_steps'       , type=lowerCAmelCase       , default=lowerCAmelCase       , help='Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.'       , )
    parser.add_argument(
        '--resume_from_checkpoint'       , type=lowerCAmelCase       , default=lowerCAmelCase       , help='If the training should continue from a checkpoint folder.'       , )
    parser.add_argument(
        '--with_tracking'       , action='store_true'       , help='Whether to load in all available experiment trackers from the environment and use them for logging.'       , )
    parser.add_argument(
        '--output_dir'       , type=lowerCAmelCase       , default='.'       , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.'       , )
    parser.add_argument(
        '--logging_dir'       , type=lowerCAmelCase       , default='logs'       , help='Location on where to store experiment tracking logs`'       , )
    parser.add_argument(
        '--model_name_or_path'       , type=lowerCAmelCase       , help='Path to pretrained model or model identifier from huggingface.co/models.'       , required=lowerCAmelCase       , )
    UpperCAmelCase  	=    parser.parse_args()
    UpperCAmelCase  	=    {'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
    training_function(lowerCAmelCase       , lowerCAmelCase       )


if __name__ == "__main__":
   main()





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


SCREAMING_SNAKE_CASE_			    =  get_logger(__name__)




def 			lowercase__  (    lowerCAmelCase :    Dict       )       ->					Any:






    """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    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_							):
      __SCREAMING_SNAKE_CASE      :							Optional[Any]												=		False  # to tell pytest it's not a test class




      @staticmethod
      def 			a_					(							lowercase_							)  ->    int:
          UpperCAmelCase  	=    parser.add_parser('test'      ,				help='Test dataset implementation.'							)
          test_parser.add_argument('--name'      ,				type=lowercase_      ,				default=lowercase_      ,				help='Dataset processing name'							)
          test_parser.add_argument(
              '--cache_dir'      ,				type=lowercase_      ,				default=lowercase_      ,				help='Cache directory where the datasets are stored.'      ,				)
          test_parser.add_argument(
              '--data_dir'      ,				type=lowercase_      ,				default=lowercase_      ,				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=lowercase_      ,				help='Name of the dataset to download'							)
          test_parser.set_defaults(func=_test_command_factory							)




      def __init__(							self      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_      ,				)  ->    List[Any]:
          UpperCAmelCase  	=    dataset
          UpperCAmelCase  	=    name
          UpperCAmelCase  	=    cache_dir
          UpperCAmelCase  	=    data_dir
          UpperCAmelCase  	=    all_configs
          UpperCAmelCase  	=    save_infos
          UpperCAmelCase  	=    ignore_verifications
          UpperCAmelCase  	=    force_redownload
          UpperCAmelCase  	=    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  	=    True




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

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

          print('Test successful.'							)



