import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_lowerCAmelCase        =       logging.getLogger(__name__)


def       a__      (					a							)		->	int:
       A_							:       List[Any]	      =				p * torch.log(a							)
       A_							:       Tuple	      =				0
       return -plogp.sum(dim=-1							)


def       a__      (					a							)		->	Dict:
       logger.info('''lv, h >\t''' + '''\t'''.join(f"""{x + 1}""" for x in range(len(a							)							)							)							)
       for row in range(len(a							)							):
              if tensor.dtype != torch.long:
                     logger.info(f"""layer {row + 1}:\t""" + '''\t'''.join(f"""{x:.5f}""" for x in tensor[row].cpu().data							)							)
              else:
                     logger.info(f"""layer {row + 1}:\t""" + '''\t'''.join(f"""{x:d}""" for x in tensor[row].cpu().data							)							)


def       a__      (					a  ,   a  ,   a  ,   a=True  ,   a=True  ,   a=None  ,   a=False							)		->	List[Any]:
       A_      ,							A_							:       Optional[int]	      =				model.config.num_hidden_layers, model.config.num_attention_heads
       A_							:       Union[str, Any]	      =				torch.zeros(a  ,   a							).to(args.device							)
       A_							:       Optional[int]	      =				torch.zeros(a  ,   a							).to(args.device							)

       if head_mask is None:
              A_							:       int	      =				torch.ones(a  ,   a							).to(args.device							)

       head_mask.requires_grad_(requires_grad=a							)
       # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
       if actually_pruned:
              A_							:       Union[str, Any]	      =				None

       A_							:       List[str]	      =				None
       A_							:       Optional[int]	      =				None
       A_							:       Dict	      =				0.0

       for step, inputs in enumerate(tqdm(a  ,   desc='''Iteration'''  ,   disable=args.local_rank not in [-1, 0]							)							):
              for k, v in inputs.items():
                     A_							:       List[Any]	      =				v.to(args.device							)

              # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
              A_							:       Tuple	      =				model(**a  ,   head_mask=a							)
              A_      ,							A_      ,							A_							:       Optional[int]	      =				(
                  outputs[0],
                  outputs[1],
                  outputs[-1],
              )  # Loss and logits are the first, attention the last
              loss.backward()  # Backpropagate to populate the gradients in the head mask

              if compute_entropy:
                     for layer, attn in enumerate(a							):
                            A_							:       List[Any]	      =				entropy(attn.detach()							) * inputs['''attention_mask'''].float().unsqueeze(1							)
                            attn_entropy[layer] += masked_entropy.sum(-1							).sum(0							).detach()

              if compute_importance:
                     head_importance += head_mask.grad.abs().detach()

              # Also store our logits/labels if we want to compute metrics afterwards
              if preds is None:
                     A_							:       int	      =				logits.detach().cpu().numpy()
                     A_							:       int	      =				inputs['''labels'''].detach().cpu().numpy()
              else:
                     A_							:       Dict	      =				np.append(a  ,   logits.detach().cpu().numpy()  ,   axis=0							)
                     A_							:       Optional[Any]	      =				np.append(a  ,   inputs['''labels'''].detach().cpu().numpy()  ,   axis=0							)

              tot_tokens += inputs["attention_mask"].float().detach().sum().data

       # Normalize
       attn_entropy /= tot_tokens
       head_importance /= tot_tokens
       # Layerwise importance normalization
       if not args.dont_normalize_importance_by_layer:
              A_							:       int	      =				2
              A_							:       Union[str, Any]	      =				torch.pow(torch.pow(a  ,   a							).sum(-1							)  ,   1 / exponent							)
              head_importance /= norm_by_layer.unsqueeze(-1							) + 1E-2_0

       if not args.dont_normalize_global_importance:
              A_							:       Dict	      =				(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

       # Print/save matrices
       np.save(os.path.join(args.output_dir  ,   '''attn_entropy.npy'''							)  ,   attn_entropy.detach().cpu().numpy()							)
       np.save(os.path.join(args.output_dir  ,   '''head_importance.npy'''							)  ,   head_importance.detach().cpu().numpy()							)

       logger.info('''Attention entropies'''							)
       print_ad_tensor(a							)
       logger.info('''Head importance scores'''							)
       print_ad_tensor(a							)
       logger.info('''Head ranked by importance scores'''							)
       A_							:       Union[str, Any]	      =				torch.zeros(head_importance.numel()  ,   dtype=torch.long  ,   device=args.device							)
       A_							:       Tuple	      =				torch.arange(
           head_importance.numel()  ,   device=args.device							)
       A_							:       str	      =				head_ranks.view_as(a							)
       print_ad_tensor(a							)

       return attn_entropy, head_importance, preds, labels


def       a__      (					a  ,   a  ,   a							)		->	str:
       A_      ,							A_      ,							A_      ,							A_							:       Dict	      =				compute_heads_importance(a  ,   a  ,   a  ,   compute_entropy=a							)
       A_							:       int	      =				np.argmax(a  ,   axis=1							) if args.output_mode == '''classification''' else np.squeeze(a							)
       A_							:       List[str]	      =				glue_compute_metrics(args.task_name  ,   a  ,   a							)[args.metric_name]
       logger.info('''Pruning: original score: %f, threshold: %f'''  ,   a  ,   original_score * args.masking_threshold							)

       A_							:       Optional[int]	      =				torch.ones_like(a							)
       A_							:       int	      =				max(1  ,   int(new_head_mask.numel() * args.masking_amount							)							)

       A_							:       Union[str, Any]	      =				original_score
       while current_score >= original_score * args.masking_threshold:
              A_							:       Any	      =				new_head_mask.clone()  # save current head mask
              # heads from least important to most - keep only not-masked heads
              A_							:       Optional[Any]	      =				float('''Inf'''							)
              A_							:       Tuple	      =				head_importance.view(-1							).sort()[1]

              if len(a							) <= num_to_mask:
                     break

              # mask heads
              A_							:       Any	      =				current_heads_to_mask[:num_to_mask]
              logger.info('''Heads to mask: %s'''  ,   str(current_heads_to_mask.tolist()							)							)
              A_							:       str	      =				new_head_mask.view(-1							)
              A_							:       Dict	      =				0.0
              A_							:       int	      =				new_head_mask.view_as(a							)
              A_							:       Any	      =				new_head_mask.clone().detach()
              print_ad_tensor(a							)

              # Compute metric and head importance again
              A_      ,							A_      ,							A_      ,							A_							:       Tuple	      =				compute_heads_importance(
                  a  ,   a  ,   a  ,   compute_entropy=a  ,   head_mask=a							)
              A_							:       List[str]	      =				np.argmax(a  ,   axis=1							) if args.output_mode == '''classification''' else np.squeeze(a							)
              A_							:       List[str]	      =				glue_compute_metrics(args.task_name  ,   a  ,   a							)[args.metric_name]
              logger.info(
                  '''Masking: current score: %f, remaining heads %d (%.1f percents)'''  ,   a  ,   new_head_mask.sum()  ,   new_head_mask.sum() / new_head_mask.numel() * 1_0_0  ,   )

       logger.info('''Final head mask'''							)
       print_ad_tensor(a							)
       np.save(os.path.join(args.output_dir  ,   '''head_mask.npy'''							)  ,   head_mask.detach().cpu().numpy()							)

       return head_mask


def       a__      (					a  ,   a  ,   a  ,   a							)		->	Tuple:
       A_							:       List[str]	      =				datetime.now()
       A_      ,							A_      ,							A_      ,							A_							:       Optional[int]	      =				compute_heads_importance(
           a  ,   a  ,   a  ,   compute_entropy=a  ,   compute_importance=a  ,   head_mask=a							)
       A_							:       Dict	      =				np.argmax(a  ,   axis=1							) if args.output_mode == '''classification''' else np.squeeze(a							)
       A_							:       List[str]	      =				glue_compute_metrics(args.task_name  ,   a  ,   a							)[args.metric_name]
       A_							:       int	      =				datetime.now() - before_time

       A_							:       Optional[Any]	      =				sum(p.numel() for p in model.parameters()							)
       A_							:       Dict	      =				{
           layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(a							)							)
       }

       assert sum(len(a							) for h in heads_to_prune.values()							) == (1 - head_mask.long()).sum().item()
       model.prune_heads(a							)
       A_							:       Tuple	      =				sum(p.numel() for p in model.parameters()							)

       A_							:       str	      =				datetime.now()
       A_      ,							A_      ,							A_      ,							A_							:       Dict	      =				compute_heads_importance(
           a  ,   a  ,   a  ,   compute_entropy=a  ,   compute_importance=a  ,   head_mask=a  ,   actually_pruned=a  ,   )
       A_							:       List[Any]	      =				np.argmax(a  ,   axis=1							) if args.output_mode == '''classification''' else np.squeeze(a							)
       A_							:       Tuple	      =				glue_compute_metrics(args.task_name  ,   a  ,   a							)[args.metric_name]
       A_							:       int	      =				datetime.now() - before_time

       logger.info(
           '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'''  ,   a  ,   a  ,   pruned_num_params / original_num_params * 1_0_0  ,   )
       logger.info('''Pruning: score with masking: %f score with pruning: %f'''  ,   a  ,   a							)
       logger.info('''Pruning: speed ratio (new timing / original timing): %f percents'''  ,   original_time / new_time * 1_0_0							)


def       a__      (					)		->	Optional[Any]:
       A_							:       Optional[Any]	      =				argparse.ArgumentParser()
       # Required parameters
       parser.add_argument(
           '''--data_dir'''  ,   default=a  ,   type=a  ,   required=a  ,   help='''The input data dir. Should contain the .tsv files (or other data files) for the task.'''  ,   )
       parser.add_argument(
           '''--model_name_or_path'''  ,   default=a  ,   type=a  ,   required=a  ,   help='''Path to pretrained model or model identifier from huggingface.co/models'''  ,   )
       parser.add_argument(
           '''--task_name'''  ,   default=a  ,   type=a  ,   required=a  ,   help='''The name of the task to train selected in the list: ''' + ''', '''.join(glue_processors.keys()							)  ,   )
       parser.add_argument(
           '''--output_dir'''  ,   default=a  ,   type=a  ,   required=a  ,   help='''The output directory where the model predictions and checkpoints will be written.'''  ,   )

       # Other parameters
       parser.add_argument(
           '''--config_name'''  ,   default=''''''  ,   type=a  ,   help='''Pretrained config name or path if not the same as model_name_or_path'''  ,   )
       parser.add_argument(
           '''--tokenizer_name'''  ,   default=''''''  ,   type=a  ,   help='''Pretrained tokenizer name or path if not the same as model_name_or_path'''  ,   )
       parser.add_argument(
           '''--cache_dir'''  ,   default=a  ,   type=a  ,   help='''Where do you want to store the pre-trained models downloaded from huggingface.co'''  ,   )
       parser.add_argument(
           '''--data_subset'''  ,   type=a  ,   default=-1  ,   help='''If > 0: limit the data to a subset of data_subset instances.'''							)
       parser.add_argument(
           '''--overwrite_output_dir'''  ,   action='''store_true'''  ,   help='''Whether to overwrite data in output directory'''							)
       parser.add_argument(
           '''--overwrite_cache'''  ,   action='''store_true'''  ,   help='''Overwrite the cached training and evaluation sets'''							)

       parser.add_argument(
           '''--dont_normalize_importance_by_layer'''  ,   action='''store_true'''  ,   help='''Don\'t normalize importance score by layers'''							)
       parser.add_argument(
           '''--dont_normalize_global_importance'''  ,   action='''store_true'''  ,   help='''Don\'t normalize all importance scores between 0 and 1'''  ,   )

       parser.add_argument(
           '''--try_masking'''  ,   action='''store_true'''  ,   help='''Whether to try to mask head until a threshold of accuracy.'''							)
       parser.add_argument(
           '''--masking_threshold'''  ,   default=0.9  ,   type=a  ,   help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'''  ,   )
       parser.add_argument(
           '''--masking_amount'''  ,   default=0.1  ,   type=a  ,   help='''Amount to heads to masking at each masking step.'''							)
       parser.add_argument('''--metric_name'''  ,   default='''acc'''  ,   type=a  ,   help='''Metric to use for head masking.'''							)

       parser.add_argument(
           '''--max_seq_length'''  ,   default=1_2_8  ,   type=a  ,   help=(
               '''The maximum total input sequence length after WordPiece tokenization. \n'''
               '''Sequences longer than this will be truncated, sequences shorter padded.'''
           )  ,   )
       parser.add_argument('''--batch_size'''  ,   default=1  ,   type=a  ,   help='''Batch size.'''							)

       parser.add_argument('''--seed'''  ,   type=a  ,   default=4_2							)
       parser.add_argument('''--local_rank'''  ,   type=a  ,   default=-1  ,   help='''local_rank for distributed training on gpus'''							)
       parser.add_argument('''--no_cuda'''  ,   action='''store_true'''  ,   help='''Whether not to use CUDA when available'''							)
       parser.add_argument('''--server_ip'''  ,   type=a  ,   default=''''''  ,   help='''Can be used for distant debugging.'''							)
       parser.add_argument('''--server_port'''  ,   type=a  ,   default=''''''  ,   help='''Can be used for distant debugging.'''							)
       A_							:       str	      =				parser.parse_args()

       if args.server_ip and args.server_port:
              # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
              import ptvsd

              print('''Waiting for debugger attach'''							)
              ptvsd.enable_attach(address=(args.server_ip, args.server_port)  ,   redirect_output=a							)
              ptvsd.wait_for_attach()

       # Setup devices and distributed training
       if args.local_rank == -1 or args.no_cuda:
              A_							:       str	      =				torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''							)
              A_							:       Dict	      =				0 if args.no_cuda else torch.cuda.device_count()
       else:
              torch.cuda.set_device(args.local_rank							)
              A_							:       int	      =				torch.device('''cuda'''  ,   args.local_rank							)
              A_							:       Union[str, Any]	      =				1
              torch.distributed.init_process_group(backend='''nccl'''							)  # Initializes the distributed backend

       # Setup logging
       logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN							)
       logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device  ,   args.n_gpu  ,   bool(args.local_rank != -1							)							)							)
       # Set the verbosity to info of the Transformers logger (on main process only):
       if is_main_process(args.local_rank							):
              transformers.utils.logging.set_verbosity_info()
              transformers.utils.logging.enable_default_handler()
              transformers.utils.logging.enable_explicit_format()

       # Set seeds
       set_seed(args.seed							)

       # Prepare GLUE task
       A_							:       Optional[Any]	      =				args.task_name.lower()
       if args.task_name not in glue_processors:
              raise ValueError('''Task not found: %s''' % (args.task_name)							)
       A_							:       Any	      =				glue_processors[args.task_name]()
       A_							:       Optional[int]	      =				glue_output_modes[args.task_name]
       A_							:       Dict	      =				processor.get_labels()
       A_							:       Union[str, Any]	      =				len(a							)

       # Load pretrained model and tokenizer
       #
       # Distributed training:
       # The .from_pretrained methods guarantee that only one local process can concurrently
       # download model & vocab.

       A_							:       Dict	      =				AutoConfig.from_pretrained(
           args.config_name if args.config_name else args.model_name_or_path  ,   num_labels=a  ,   finetuning_task=args.task_name  ,   output_attentions=a  ,   cache_dir=args.cache_dir  ,   )
       A_							:       Any	      =				AutoTokenizer.from_pretrained(
           args.tokenizer_name if args.tokenizer_name else args.model_name_or_path  ,   cache_dir=args.cache_dir  ,   )
       A_							:       Dict	      =				AutoModelForSequenceClassification.from_pretrained(
           args.model_name_or_path  ,   from_tf=bool('''.ckpt''' in args.model_name_or_path							)  ,   config=a  ,   cache_dir=args.cache_dir  ,   )

       # Distributed and parallel training
       model.to(args.device							)
       if args.local_rank != -1:
              A_							:       Optional[Any]	      =				nn.parallel.DistributedDataParallel(
                  a  ,   device_ids=[args.local_rank]  ,   output_device=args.local_rank  ,   find_unused_parameters=a							)
       elif args.n_gpu > 1:
              A_							:       List[Any]	      =				nn.DataParallel(a							)

       # Print/save training arguments
       os.makedirs(args.output_dir  ,   exist_ok=a							)
       torch.save(a  ,   os.path.join(args.output_dir  ,   '''run_args.bin'''							)							)
       logger.info('''Training/evaluation parameters %s'''  ,   a							)

       # Prepare dataset for the GLUE task
       A_							:       str	      =				GlueDataset(a  ,   tokenizer=a  ,   mode='''dev'''							)
       if args.data_subset > 0:
              A_							:       Optional[int]	      =				Subset(a  ,   list(range(min(args.data_subset  ,   len(a							)							)							)							)							)
       A_							:       str	      =				SequentialSampler(a							) if args.local_rank == -1 else DistributedSampler(a							)
       A_							:       Optional[int]	      =				DataLoader(
           a  ,   sampler=a  ,   batch_size=args.batch_size  ,   collate_fn=a							)

       # Compute head entropy and importance score
       compute_heads_importance(a  ,   a  ,   a							)

       # Try head masking (set heads to zero until the score goes under a threshole)
       # and head pruning (remove masked heads and see the effect on the network)
       if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
              A_							:       Dict	      =				mask_heads(a  ,   a  ,   a							)
              prune_heads(a  ,   a  ,   a  ,   a							)


if __name__ == "__main__":
    main()



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


_lowerCAmelCase        =       get_logger(__name__)


def       a__      (					a							)		->	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     __UpperCAmelCase(    A__				):






 """simple docstring"""




 __magic_name__          =   False  # to tell pytest it's not a test class
 @staticmethod
 def  UpperCAmelCase   (    __magic_name__      ):

        """simple docstring"""

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

        """simple docstring"""

        A_							:       Dict	      =				dataset
        A_							:       Any	      =				name
        A_							:       List[str]	      =				cache_dir
        A_							:       List[Any]	      =				data_dir
        A_							:       Any	      =				all_configs
        A_							:       int	      =				save_infos
        A_							:       Union[str, Any]	      =				ignore_verifications
        A_							:       List[Any]	      =				force_redownload
        A_							:       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:
               A_							:       Optional[Any]	      =				True
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

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

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

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


