


import argparse
from typing import List

import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset

# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# 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)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# 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
#
########################################################################


lowerCamelCase						=		16
lowerCamelCase						=		32






def      lowerCamelCase_    (       _a	,   _a	,   _a	,   _a	,   _a = 16       ):




		"""simple docstring"""






		lowerCAmelCase__   :			Union[str, Any]         =					AutoTokenizer.from_pretrained('''bert-base-cased'''       )
		lowerCAmelCase__   :			str         =					DatasetDict(
		    {
		        '''train''': dataset['''train'''].select(__a       ),
		        '''validation''': dataset['''train'''].select(__a       ),
		        '''test''': dataset['''validation'''],
		    }       )

		def tokenize_function(_a       ):
				# max_length=None => use the model max length (it's actually the default)
				lowerCAmelCase__   :			Optional[int]         =					tokenizer(examples['''sentence1''']	,   examples['''sentence2''']	,   truncation=__a	,   max_length=__a       )
				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():
				lowerCAmelCase__   :			List[str]         =					datasets.map(
				    __a	,   batched=__a	,   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
		lowerCAmelCase__   :			List[Any]         =					tokenized_datasets.rename_column('''label'''	,   '''labels'''       )

		def collate_fn(_a       ):
				# On TPU it's best to pad everything to the same length or training will be very slow.
				lowerCAmelCase__   :			Dict         =					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":
						lowerCAmelCase__   :			Tuple         =					16
				elif accelerator.mixed_precision != "no":
						lowerCAmelCase__   :			List[Any]         =					8
				else:
						lowerCAmelCase__   :			List[Any]         =					None

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

		# Instantiate dataloaders.
		lowerCAmelCase__   :			Any         =					DataLoader(
		    tokenized_datasets['''train''']	,   shuffle=__a	,   collate_fn=__a	,   batch_size=__a       )
		lowerCAmelCase__   :			Optional[int]         =					DataLoader(
		    tokenized_datasets['''validation''']	,   shuffle=__a	,   collate_fn=__a	,   batch_size=__a       )

		lowerCAmelCase__   :			Optional[Any]         =					DataLoader(
		    tokenized_datasets['''test''']	,   shuffle=__a	,   collate_fn=__a	,   batch_size=__a       )

		return train_dataloader, eval_dataloader, test_dataloader






def      lowerCamelCase_    (       _a	,   _a       ):




		"""simple docstring"""






		lowerCAmelCase__   :			Dict         =					[]
		# Download the dataset
		lowerCAmelCase__   :			Tuple         =					load_dataset('''glue'''	,   '''mrpc'''       )
		# Create our splits
		lowerCAmelCase__   :			Union[str, Any]         =					StratifiedKFold(n_splits=int(args.num_folds       )       )
		# Initialize accelerator
		lowerCAmelCase__   :			Any         =					Accelerator(cpu=args.cpu	,   mixed_precision=args.mixed_precision       )
		# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
		lowerCAmelCase__   :			Optional[Any]         =					config['lr']
		lowerCAmelCase__   :			Optional[int]         =					int(config['''num_epochs''']       )
		lowerCAmelCase__   :			Dict         =					int(config['''seed''']       )
		lowerCAmelCase__   :			Dict         =					int(config['''batch_size''']       )

		lowerCAmelCase__   :			Optional[int]         =					evaluate.load('''glue'''	,   '''mrpc'''       )

		# If the batch size is too big we use gradient accumulation
		lowerCAmelCase__   :			List[Any]         =					1
		if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
				lowerCAmelCase__   :			Any         =					batch_size // MAX_GPU_BATCH_SIZE
				lowerCAmelCase__   :			List[str]         =					MAX_GPU_BATCH_SIZE

		set_seed(__a       )

		# New Code #
		# Create our folds:
		lowerCAmelCase__   :			int         =					kfold.split(np.zeros(datasets['''train'''].num_rows       )	,   datasets['''train''']['''label''']       )
		lowerCAmelCase__   :			Any         =					[]
		# Iterate over them
		for i, (train_idxs, valid_idxs) in enumerate(__a       ):
				lowerCAmelCase__   :			Optional[Any]         =					get_fold_dataloaders(
				    __a	,   __a	,   __a	,   __a	,   )
				# Instantiate the model (we build the model here so that the seed also control new weights initialization)
				lowerCAmelCase__   :			Dict         =					AutoModelForSequenceClassification.from_pretrained('''bert-base-cased'''	,   return_dict=__a       )

				# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
				# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
				# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
				lowerCAmelCase__   :			List[Any]         =					model.to(accelerator.device       )

				# Instantiate optimizer
				lowerCAmelCase__   :			List[str]         =					AdamW(params=model.parameters()	,   lr=__a       )

				# Instantiate scheduler
				lowerCAmelCase__   :			List[Any]         =					get_linear_schedule_with_warmup(
				    optimizer=__a	,   num_warmup_steps=100	,   num_training_steps=(len(__a       ) * num_epochs) // gradient_accumulation_steps	,   )

				# Prepare everything
				# 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.
				lowerCAmelCase__   :			Union[str, Any]         =					accelerator.prepare(
				    __a	,   __a	,   __a	,   __a	,   __a       )

				# Now we train the model
				for epoch in range(__a       ):
						model.train()
						for step, batch in enumerate(__a       ):
								# We could avoid this line since we set the accelerator with `device_placement=True`.
								batch.to(accelerator.device       )
								lowerCAmelCase__   :			Dict         =					model(**__a       )
								lowerCAmelCase__   :			int         =					outputs.loss
								lowerCAmelCase__   :			Any         =					loss / gradient_accumulation_steps
								accelerator.backward(__a       )
								if step % gradient_accumulation_steps == 0:
										optimizer.step()
										lr_scheduler.step()
										optimizer.zero_grad()

						model.eval()
						for step, batch in enumerate(__a       ):
								# We could avoid this line since we set the accelerator with `device_placement=True`.
								batch.to(accelerator.device       )
								with torch.no_grad():
										lowerCAmelCase__   :			Union[str, Any]         =					model(**__a       )
								lowerCAmelCase__   :			Tuple         =					outputs.logits.argmax(dim=-1       )
								lowerCAmelCase__   :			Any         =					accelerator.gather_for_metrics((predictions, batch['''labels'''])       )
								metric.add_batch(
								    predictions=__a	,   references=__a	,   )

						lowerCAmelCase__   :			List[Any]         =					metric.compute()
						# Use accelerator.print to print only on the main process.
						accelerator.print(f'epoch {epoch}:'	,   __a       )

				# New Code #
				# We also run predictions on the test set at the very end
				lowerCAmelCase__   :			Any         =					[]
				for step, batch in enumerate(__a       ):
						# We could avoid this line since we set the accelerator with `device_placement=True`.
						batch.to(accelerator.device       )
						with torch.no_grad():
								lowerCAmelCase__   :			Tuple         =					model(**__a       )
						lowerCAmelCase__   :			Dict         =					outputs.logits
						lowerCAmelCase__   :			Optional[int]         =					accelerator.gather_for_metrics((predictions, batch['''labels'''])       )
						fold_predictions.append(predictions.cpu()       )
						if i == 0:
								# We need all of the test predictions
								test_references.append(references.cpu()       )
        # Use accelerator.print to print only on the main process.
				test_predictions.append(torch.cat(__a	,   dim=0       )       )
				# We now need to release all our memory and get rid of the current model, optimizer, etc
				accelerator.free_memory()
		# New Code #
		# Finally we check the accuracy of our folded results:
		lowerCAmelCase__   :			Dict         =					torch.cat(__a	,   dim=0       )
		lowerCAmelCase__   :			Any         =					torch.stack(__a	,   dim=0       ).sum(dim=0       ).div(int(args.num_folds       )       ).argmax(dim=-1       )
		lowerCAmelCase__   :			str         =					metric.compute(predictions=__a	,   references=__a       )
		accelerator.print('''Average test metrics from all folds:'''	,   __a       )






def      lowerCamelCase_    (       ):




		"""simple docstring"""






		lowerCAmelCase__   :			Any         =					argparse.ArgumentParser(description='''Simple example of training script.'''       )
		parser.add_argument(
		    '''--mixed_precision'''	,   type=__a	,   default=__a	,   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.'''       )
		# New Code #
		parser.add_argument('''--num_folds'''	,   type=__a	,   default=3	,   help='''The number of splits to perform across the dataset'''       )
		lowerCAmelCase__   :			Any         =					parser.parse_args()
		lowerCAmelCase__   :			int         =					{'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
		training_function(__a	,   __a       )


if __name__ == "__main__":
		main()






'''simple docstring'''







import gzip
import hashlib
import json
import multiprocessing
import os
import re
import shutil
import time
from pathlib import Path

import numpy as np
from arguments import PreprocessingArguments
from datasets import load_dataset
from minhash_deduplication import deduplicate_dataset

from transformers import AutoTokenizer, HfArgumentParser


__lowerCAmelCase         =    re.compile(r"""\s+""")





def 					UpperCAmelCase_		(__a      :    Any ):






   """simple docstring"""

   return {"hash": hashlib.mda(re.sub(__a ,	'' ,	example['content'] ).encode('utf-8' ) ).hexdigest()}





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

   _a				:	List[str]			=   [len(__a ) for line in example['content'].splitlines()]
   return {"line_mean": np.mean(__a ), "line_max": max(__a )}





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

   _a				:	Union[str, Any]			=   np.mean([c.isalnum() for c in example['content']] )
   return {"alpha_frac": alpha_frac}





def 					UpperCAmelCase_		(__a      :    Optional[int] ,	__a      :    Any ):






   """simple docstring"""

   if example["hash"] in uniques:
      uniques.remove(example['hash'] )
      return True
   else:
      return False





def 					UpperCAmelCase_		(__a      :    int ,	__a      :    Union[str, Any]=5 ):






   """simple docstring"""

   _a				:	Optional[int]			=   ['auto-generated', 'autogenerated', 'automatically generated']
   _a				:	List[str]			=   example['content'].splitlines()
   for _, line in zip(range(__a ) ,	__a ):
      for keyword in keywords:
         if keyword in line.lower():
            return {"autogenerated": True}
   else:
      return {"autogenerated": False}





def 					UpperCAmelCase_		(__a      :    List[str] ,	__a      :    Dict=5 ,	__a      :    Tuple=0.05 ):






   """simple docstring"""

   _a				:	Optional[int]			=   ['unit tests', 'test file', 'configuration file']
   _a				:	int			=   example['content'].splitlines()
   _a				:	int			=   0
   _a				:	Dict			=   0
   # first test
   for _, line in zip(range(__a ) ,	__a ):
      for keyword in keywords:
         if keyword in line.lower():
            return {"config_or_test": True}
    # second test
   _a				:	int			=   example['content'].count('\n' )
   _a				:	int			=   int(coeff * nlines )
   for line in lines:
      count_config += line.lower().count('config' )
      count_test += line.lower().count('test' )
      if count_config > threshold or count_test > threshold:
         return {"config_or_test": True}
   return {"config_or_test": False}





def 					UpperCAmelCase_		(__a      :    Optional[int] ):






   """simple docstring"""

   _a				:	List[str]			=   ['def ', 'class ', 'for ', 'while ']
   _a				:	str			=   example['content'].splitlines()
   for line in lines:
      for keyword in keywords:
         if keyword in line.lower():
            return {"has_no_keywords": False}
   return {"has_no_keywords": True}





def 					UpperCAmelCase_		(__a      :    int ,	__a      :    Any=4 ):






   """simple docstring"""

   _a				:	List[str]			=   example['content'].splitlines()
   _a				:	Dict			=   0
   for line in lines:
      counter += line.lower().count('=' )
      if counter > minimum:
         return {"has_few_assignments": False}
   return {"has_few_assignments": True}





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

   _a				:	Optional[Any]			=   tokenizer(example['content'] ,	truncation=__a )['input_ids']
   _a				:	Optional[int]			=   len(example['content'] ) / len(__a )
   return {"ratio": ratio}





def 					UpperCAmelCase_		(__a      :    str ):






   """simple docstring"""

   _a				:	Dict			=   {}
   results.update(get_hash(__a ) )
   results.update(line_stats(__a ) )
   results.update(alpha_stats(__a ) )
   results.update(char_token_ratio(__a ) )
   results.update(is_autogenerated(__a ) )
   results.update(is_config_or_test(__a ) )
   results.update(has_no_keywords(__a ) )
   results.update(has_few_assignments(__a ) )
   return results





def 					UpperCAmelCase_		(__a      :    Any ,	__a      :    Any ,	__a      :    str ):






   """simple docstring"""

   if not check_uniques(__a ,	__a ):
      return False
   elif example["autogenerated"]:
      return False
   elif example["line_max"] > args.line_max:
      return False
   elif example["line_mean"] > args.line_mean:
      return False
   elif example["alpha_frac"] < args.alpha_frac:
      return False
   elif example["ratio"] < args.min_token_ratio:
      return False
   elif example["config_or_test"] and np.random.rand() <= args.filter_proba:
      return False
   elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba:
      return False
   elif example["has_few_assignments"]:
      return False
   else:
      return True





def 					UpperCAmelCase_		(__a      :    Union[str, Any] ):






   """simple docstring"""

   with open(__a ,	'rb' ) as f_in:
      with gzip.open(str(__a ) + '.gz' ,	'wb' ,	compresslevel=6 ) as f_out:
         shutil.copyfileobj(__a ,	__a )
   os.unlink(__a )


# Settings
__lowerCAmelCase         =    HfArgumentParser(PreprocessingArguments)
__lowerCAmelCase         =    parser.parse_args()
if args.num_workers is None:
  __lowerCAmelCase         =    multiprocessing.cpu_count()
__lowerCAmelCase         =    AutoTokenizer.from_pretrained(args.tokenizer_dir)

# Load dataset
__lowerCAmelCase         =    time.time()
__lowerCAmelCase         =    load_dataset(args.dataset_name, split="""train""")
print(f'''Time to load dataset: {time.time()-t_start:.2f}''')

# Run preprocessing
__lowerCAmelCase         =    time.time()
__lowerCAmelCase         =    ds.map(preprocess, num_proc=args.num_workers)
print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''')

# Deduplicate hashes
__lowerCAmelCase         =    set(ds.unique("""hash"""))
__lowerCAmelCase         =    len(uniques) / len(ds)
print(f'''Fraction of duplicates: {1-frac:.2%}''')

# Deduplicate data and apply heuristics
__lowerCAmelCase         =    time.time()
__lowerCAmelCase         =    ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args})
print(f'''Time to filter dataset: {time.time()-t_start:.2f}''')
print(f'''Size of filtered dataset: {len(ds_filter)}''')

# Deduplicate with minhash and jaccard similarity
if args.near_deduplication:
  __lowerCAmelCase         =    time.time()
  __lowerCAmelCase   ,				__lowerCAmelCase         =    deduplicate_dataset(ds_filter, args.jaccard_threshold)
  print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''')
  print(f'''Size of deduplicate dataset: {len(ds_filter)}''')

# Save data in batches of samples_per_file
__lowerCAmelCase         =    Path(args.output_dir)
output_dir.mkdir(exist_ok=True)

# save duplicate_clusters in the output_dir as artifacts
# not sure it is the right place the save it
if args.near_deduplication:
  with open(output_dir / """duplicate_clusters.json""", """w""") as f:
    json.dump(duplicate_clusters, f)

__lowerCAmelCase         =    output_dir / """data"""
data_dir.mkdir(exist_ok=True)

__lowerCAmelCase         =    time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
  __lowerCAmelCase         =    str(data_dir / f'''file-{file_number+1:012}.json''')
  __lowerCAmelCase         =    min(len(ds_filter), index + args.samples_per_file)
  ds_filter.select(list(range(index, end_index))).to_json(file_path)
  compress_file(file_path)
print(f'''Time to save dataset: {time.time()-t_start:.2f}''')



