






'''simple docstring'''




from typing import Optional

import numpy as np
import torch
from torch import nn
from transformers import GPTaConfig, GPTaLMHeadModel
from transformers.modeling_utils import ModuleUtilsMixin

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin







class    A_	(a_						,					a_						,					a_							):
							"""simple docstring"""




							a__   		=	[r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias''']

							@register_to_config
							def __init__(		self			:Optional[Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:Optional[int] = None       ,							lowerCAmelCase__			:int = 50_257       ,							lowerCAmelCase__			:int = 1_024       ,							lowerCAmelCase__			:int = 768       ,							lowerCAmelCase__			:int = 12       ,							lowerCAmelCase__			:int = 12       ,							lowerCAmelCase__			:Optional[int] = None       ,							lowerCAmelCase__			:str = "gelu_new"       ,							lowerCAmelCase__			:float = 0.1       ,							lowerCAmelCase__			:float = 0.1       ,							lowerCAmelCase__			:float = 0.1       ,							lowerCAmelCase__			:float = 1E-5       ,							lowerCAmelCase__			:float = 0.0_2       ,							lowerCAmelCase__			:bool = True       ,							lowerCAmelCase__			:bool = True       ,							lowerCAmelCase__			:bool = False       ,							lowerCAmelCase__			:bool = False       ,							)				->  List[Any]:


										'''simple docstring'''




										super().__init__()

										snake_case_				:					str   =       prefix_length

										if prefix_inner_dim != n_embd and prefix_hidden_dim is None:
													raise ValueError(
													    F'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and'''
													    F''' `n_embd`: {n_embd} are not equal.'''				)

										snake_case_				:					Any   =       prefix_inner_dim
										snake_case_				:					List[Any]   =       prefix_hidden_dim

										snake_case_				:					str   =       (
										    nn.Linear(self.prefix_inner_dim       ,							self.prefix_hidden_dim				)
										    if self.prefix_hidden_dim is not None
										    else nn.Identity()
										)
										snake_case_				:					Optional[int]   =       (
										    nn.Linear(self.prefix_hidden_dim       ,							lowerCAmelCase__				) if self.prefix_hidden_dim is not None else nn.Identity()
										)

										snake_case_				:					int   =       GPTaConfig(
										    vocab_size=lowerCAmelCase__       ,							n_positions=lowerCAmelCase__       ,							n_embd=lowerCAmelCase__       ,							n_layer=lowerCAmelCase__       ,							n_head=lowerCAmelCase__       ,							n_inner=lowerCAmelCase__       ,							activation_function=lowerCAmelCase__       ,							resid_pdrop=lowerCAmelCase__       ,							embd_pdrop=lowerCAmelCase__       ,							attn_pdrop=lowerCAmelCase__       ,							layer_norm_epsilon=lowerCAmelCase__       ,							initializer_range=lowerCAmelCase__       ,							scale_attn_weights=lowerCAmelCase__       ,							use_cache=lowerCAmelCase__       ,							scale_attn_by_inverse_layer_idx=lowerCAmelCase__       ,							reorder_and_upcast_attn=lowerCAmelCase__       ,							)
										snake_case_				:					Dict   =       GPTaLMHeadModel(lowerCAmelCase__				)

							def 							_A	(		self			:str       ,							lowerCAmelCase__			:torch.Tensor       ,							lowerCAmelCase__			:torch.Tensor       ,							lowerCAmelCase__			:Optional[torch.Tensor] = None       ,							lowerCAmelCase__			:Optional[torch.Tensor] = None       ,							)				->  int:


										'''simple docstring'''




										snake_case_				:					Dict   =       self.transformer.transformer.wte(lowerCAmelCase__				)
										snake_case_				:					List[Any]   =       self.encode_prefix(lowerCAmelCase__				)
										snake_case_				:					List[Any]   =       self.decode_prefix(lowerCAmelCase__				)
										snake_case_				:					List[str]   =       torch.cat((prefix_embeds, embedding_text)       ,							dim=1				)

										if labels is not None:
													snake_case_				:					int   =       self.get_dummy_token(input_ids.shape[0]       ,							input_ids.device				)
													snake_case_				:					Optional[Any]   =       torch.cat((dummy_token, input_ids)       ,							dim=1				)
										snake_case_				:					List[str]   =       self.transformer(inputs_embeds=lowerCAmelCase__       ,							labels=lowerCAmelCase__       ,							attention_mask=lowerCAmelCase__				)
										if self.prefix_hidden_dim is not None:
													return out, hidden
										else:
													return out

							def 							_A	(		self			:Union[str, Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:torch.device				)				->  torch.Tensor:


										'''simple docstring'''




										return torch.zeros(lowerCAmelCase__       ,							self.prefix_length       ,							dtype=torch.intaa       ,							device=lowerCAmelCase__				)

							def 							_A	(		self			:List[Any]       ,							lowerCAmelCase__			:Union[str, Any]				)				->  Dict:


										'''simple docstring'''




										return self.encode_prefix(lowerCAmelCase__				)

							@torch.no_grad()
							def 							_A	(		self			:Union[str, Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:Optional[Any]       ,							lowerCAmelCase__			:Tuple				)				->  str:


										'''simple docstring'''




										snake_case_				:					List[str]   =       torch.split(lowerCAmelCase__       ,							1       ,							dim=0				)
										snake_case_				:					Any   =       []
										snake_case_				:					int   =       []
										for feature in features:
													snake_case_				:					Dict   =       self.decode_prefix(feature.to(lowerCAmelCase__				)				)  # back to the clip feature
													# Only support beam search for now
													snake_case_				:					int   =       self.generate_beam(
													    input_embeds=lowerCAmelCase__       ,							device=lowerCAmelCase__       ,							eos_token_id=lowerCAmelCase__				)
													generated_tokens.append(output_tokens[0]				)
													generated_seq_lengths.append(seq_lengths[0]				)
										snake_case_				:					List[Any]   =       torch.stack(lowerCAmelCase__				)
										snake_case_				:					str   =       torch.stack(lowerCAmelCase__				)
										return generated_tokens, generated_seq_lengths






							@torch.no_grad()
							def 							_A	(		self			:Any       ,							lowerCAmelCase__			:Optional[Any]=None       ,							lowerCAmelCase__			:int=None       ,							lowerCAmelCase__			:List[Any]=None       ,							lowerCAmelCase__			:int = 5       ,							lowerCAmelCase__			:int = 67       ,							lowerCAmelCase__			:float = 1.0       ,							lowerCAmelCase__			:Optional[int] = None       ,							)				->  str:


										'''simple docstring'''




										snake_case_				:					Union[str, Any]   =       eos_token_id
										snake_case_				:					str   =       None
										snake_case_				:					int   =       None
										snake_case_				:					Tuple   =       torch.ones(lowerCAmelCase__       ,							device=lowerCAmelCase__       ,							dtype=torch.int				)
										snake_case_				:					Dict   =       torch.zeros(lowerCAmelCase__       ,							device=lowerCAmelCase__       ,							dtype=torch.bool				)

										if input_embeds is not None:
													snake_case_				:					List[str]   =       input_embeds
										else:
													snake_case_				:					List[str]   =       self.transformer.transformer.wte(lowerCAmelCase__				)

										for i in range(lowerCAmelCase__				):
													snake_case_				:					Any   =       self.transformer(inputs_embeds=lowerCAmelCase__				)
													snake_case_				:					Optional[Any]   =       outputs.logits
													snake_case_				:					str   =       logits[:, -1, :] / (temperature if temperature > 0 else 1.0)
													snake_case_				:					List[str]   =       logits.softmax(-1				).log()

													if scores is None:
																snake_case_				:					Optional[Any]   =       logits.topk(lowerCAmelCase__       ,							-1				)
																snake_case_				:					List[str]   =       generated.expand(lowerCAmelCase__       ,							*generated.shape[1:]				)
																snake_case_				:					int   =       next_tokens.permute(1       ,							0				), scores.squeeze(0				)
																if tokens is None:
																			snake_case_				:					Union[str, Any]   =       next_tokens
																else:
																			snake_case_				:					Optional[Any]   =       tokens.expand(lowerCAmelCase__       ,							*tokens.shape[1:]				)
																			snake_case_				:					Any   =       torch.cat((tokens, next_tokens)       ,							dim=1				)
													else:
																snake_case_				:					Tuple   =       -float(np.inf				)
																snake_case_				:					List[Any]   =       0
																snake_case_				:					Dict   =       scores[:, None] + logits
																seq_lengths[~is_stopped] += 1
																snake_case_				:					Any   =       scores_sum / seq_lengths[:, None]
																snake_case_				:					Dict   =       scores_sum_average.view(-1				).topk(lowerCAmelCase__       ,							-1				)
																snake_case_				:					Optional[Any]   =       next_tokens // scores_sum.shape[1]
																snake_case_				:					Optional[int]   =       seq_lengths[next_tokens_source]
																snake_case_				:					Optional[int]   =       next_tokens % scores_sum.shape[1]
																snake_case_				:					List[str]   =       next_tokens.unsqueeze(1				)
																snake_case_				:					Dict   =       tokens[next_tokens_source]
																snake_case_				:					Tuple   =       torch.cat((tokens, next_tokens)       ,							dim=1				)
																snake_case_				:					Optional[Any]   =       generated[next_tokens_source]
																snake_case_				:					List[str]   =       scores_sum_average * seq_lengths
																snake_case_				:					Optional[int]   =       is_stopped[next_tokens_source]

													snake_case_				:					List[str]   =       self.transformer.transformer.wte(next_tokens.squeeze()				).view(generated.shape[0]       ,							1       ,							-1				)
													snake_case_				:					int   =       torch.cat((generated, next_token_embed)       ,							dim=1				)
													snake_case_				:					Any   =       is_stopped + next_tokens.eq(lowerCAmelCase__				).squeeze()
													if is_stopped.all():
																break

										snake_case_				:					List[str]   =       scores / seq_lengths
										snake_case_				:					Dict   =       scores.argsort(descending=lowerCAmelCase__				)
										# tokens tensors are already padded to max_seq_length
										snake_case_				:					int   =       [tokens[i] for i in order]
										snake_case_				:					str   =       torch.stack(lowerCAmelCase__       ,							dim=0				)
										snake_case_				:					str   =       torch.tensor([seq_lengths[i] for i in order]       ,							dtype=seq_lengths.dtype				)
										return output_texts, seq_lengths












'''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   :					List[str]   							=					re.compile(R'''\s+''')

def 	__UpperCAmelCase       ( __magic_name__						)->    Union[str, Any]:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__						)->    str:



			"""simple docstring"""



			snake_case_				:					Optional[Any]   =       [len(__magic_name__						) for line in example["content"].splitlines()]
			return {"line_mean": np.mean(__magic_name__						), "line_max": max(__magic_name__						)}

def 	__UpperCAmelCase       ( __magic_name__						)->    int:



			"""simple docstring"""



			snake_case_				:					Optional[int]   =       np.mean([c.isalnum() for c in example["content"]]						)
			return {"alpha_frac": alpha_frac}

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    Tuple:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=5						)->    Tuple:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=5     ,__magic_name__=0.05						)->    Optional[Any]:



			"""simple docstring"""



			snake_case_				:					str   =       ["unit tests", "test file", "configuration file"]
			snake_case_				:					int   =       example["content"].splitlines()
			snake_case_				:					Optional[Any]   =       0
			snake_case_				:					Any   =       0
			# first test
			for _, line in zip(range(__magic_name__						)     ,__magic_name__						):
						for keyword in keywords:
									if keyword in line.lower():
												return {"config_or_test": True}
    # second test
			snake_case_				:					Tuple   =       example["content"].count("\n"						)
			snake_case_				:					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       ( __magic_name__						)->    str:



			"""simple docstring"""



			snake_case_				:					List[Any]   =       ["def ", "class ", "for ", "while "]
			snake_case_				:					Optional[Any]   =       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       ( __magic_name__     ,__magic_name__=4						)->    Optional[int]:



			"""simple docstring"""



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

def 	__UpperCAmelCase       ( __magic_name__						)->    List[Any]:



			"""simple docstring"""



			snake_case_				:					Tuple   =       tokenizer(example["content"]     ,truncation=__magic_name__						)["input_ids"]
			snake_case_				:					int   =       len(example["content"]						) / len(__magic_name__						)
			return {"ratio": ratio}

def 	__UpperCAmelCase       ( __magic_name__						)->    Optional[Any]:



			"""simple docstring"""



			snake_case_				:					Union[str, Any]   =       {}
			results.update(get_hash(__magic_name__						)						)
			results.update(line_stats(__magic_name__						)						)
			results.update(alpha_stats(__magic_name__						)						)
			results.update(char_token_ratio(__magic_name__						)						)
			results.update(is_autogenerated(__magic_name__						)						)
			results.update(is_config_or_test(__magic_name__						)						)
			results.update(has_no_keywords(__magic_name__						)						)
			results.update(has_few_assignments(__magic_name__						)						)
			return results

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__     ,__magic_name__						)->    Tuple:



			"""simple docstring"""



			if not check_uniques(__magic_name__     ,__magic_name__						):
						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       ( __magic_name__						)->    Dict:



			"""simple docstring"""



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


# Settings
__lowerCamelCase   :					List[Any]   							=					HfArgumentParser(PreprocessingArguments)
__lowerCamelCase   :					str   							=					parser.parse_args()
if args.num_workers is None:
		__lowerCamelCase   :					List[Any]   							=					multiprocessing.cpu_count()
__lowerCamelCase   :					Optional[int]   							=					AutoTokenizer.from_pretrained(args.tokenizer_dir)

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

# Run preprocessing
__lowerCamelCase   :					List[str]   							=					time.time()
__lowerCamelCase   :					Any   							=					ds.map(preprocess, num_proc=args.num_workers)
print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''')

# Deduplicate hashes
__lowerCamelCase   :					Any   							=					set(ds.unique('''hash'''))
__lowerCamelCase   :					Optional[int]   							=					len(uniques) / len(ds)
print(f'''Fraction of duplicates: {1-frac:.2%}''')

# Deduplicate data and apply heuristics
__lowerCamelCase   :					List[str]   							=					time.time()
__lowerCamelCase   :					Tuple   							=					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   :					List[str]   							=					time.time()
		__lowerCamelCase							,      __lowerCamelCase   :					Tuple   							=					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   :					List[Any]   							=					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   :					List[str]   							=					output_dir / '''data'''
data_dir.mkdir(exist_ok=True)

__lowerCamelCase   :					int   							=					time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
		__lowerCamelCase   :					Union[str, Any]   							=					str(data_dir / f'''file-{file_number+1:012}.json''')
		__lowerCamelCase   :					List[Any]   							=					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}''')




