




"""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[Any]					=				re.compile(r"""\s+""")



def        a__					(							snake_case__							)		->   Union[str, Any]:
			return {"hash": hashlib.mda(re.sub(snake_case__			,					""""""			,					example["""content"""]							).encode("""utf-8"""							)							).hexdigest()}



def        a__					(							snake_case__							)		->   Dict:
			lowerCamelCase      =   [len(snake_case__							) for line in example["""content"""].splitlines()]
			return {"line_mean": np.mean(snake_case__							), "line_max": max(snake_case__							)}



def        a__					(							snake_case__							)		->   List[str]:
			lowerCamelCase      =   np.mean([c.isalnum() for c in example["""content"""]]							)
			return {"alpha_frac": alpha_frac}



def        a__					(							snake_case__			,					snake_case__							)		->   int:
			if example["hash"] in uniques:
						uniques.remove(example["""hash"""]							)
						return True
			else:
						return False



def        a__					(							snake_case__			,					snake_case__=5							)		->   int:
			lowerCamelCase      =   ["""auto-generated""", """autogenerated""", """automatically generated"""]
			lowerCamelCase      =   example["""content"""].splitlines()
			for _, line in zip(range(snake_case__							)			,					snake_case__							):
						for keyword in keywords:
									if keyword in line.lower():
												return {"autogenerated": True}
			else:
						return {"autogenerated": False}



def        a__					(							snake_case__			,					snake_case__=5			,					snake_case__=0.05							)		->   List[str]:
			lowerCamelCase      =   ["""unit tests""", """test file""", """configuration file"""]
			lowerCamelCase      =   example["""content"""].splitlines()
			lowerCamelCase      =   0
			lowerCamelCase      =   0
			# first test
			for _, line in zip(range(snake_case__							)			,					snake_case__							):
						for keyword in keywords:
									if keyword in line.lower():
												return {"config_or_test": True}
    # second test
			lowerCamelCase      =   example["""content"""].count("""\n"""							)
			lowerCamelCase      =   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        a__					(							snake_case__							)		->   Optional[Any]:
			lowerCamelCase      =   ["""def """, """class """, """for """, """while """]
			lowerCamelCase      =   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        a__					(							snake_case__			,					snake_case__=4							)		->   Tuple:
			lowerCamelCase      =   example["""content"""].splitlines()
			lowerCamelCase      =   0
			for line in lines:
						counter += line.lower().count("""="""							)
						if counter > minimum:
									return {"has_few_assignments": False}
			return {"has_few_assignments": True}



def        a__					(							snake_case__							)		->   Union[str, Any]:
			lowerCamelCase      =   tokenizer(example["""content"""]			,					truncation=snake_case__							)["""input_ids"""]
			lowerCamelCase      =   len(example["""content"""]							) / len(snake_case__							)
			return {"ratio": ratio}



def        a__					(							snake_case__							)		->   str:
			lowerCamelCase      =   {}
			results.update(get_hash(snake_case__							)							)
			results.update(line_stats(snake_case__							)							)
			results.update(alpha_stats(snake_case__							)							)
			results.update(char_token_ratio(snake_case__							)							)
			results.update(is_autogenerated(snake_case__							)							)
			results.update(is_config_or_test(snake_case__							)							)
			results.update(has_no_keywords(snake_case__							)							)
			results.update(has_few_assignments(snake_case__							)							)
			return results



def        a__					(							snake_case__			,					snake_case__			,					snake_case__							)		->   List[Any]:
			if not check_uniques(snake_case__			,					snake_case__							):
						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        a__					(							snake_case__							)		->   Optional[Any]:
			with open(snake_case__			,					"""rb"""							) as f_in:
						with gzip.open(str(snake_case__							) + """.gz"""			,					"""wb"""			,					compresslevel=6							) as f_out:
									shutil.copyfileobj(snake_case__			,					snake_case__							)
			os.unlink(snake_case__							)


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

# Load dataset
lowerCAmelCase				:     List[str]					=				time.time()
lowerCAmelCase				:     Optional[Any]					=				load_dataset(args.dataset_name, split="""train""")
print(F"""Time to load dataset: {time.time()-t_start:.2f}""")

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

# Deduplicate hashes
lowerCAmelCase				:     str					=				set(ds.unique("""hash"""))
lowerCAmelCase				:     List[str]					=				len(uniques) / len(ds)
print(F"""Fraction of duplicates: {1-frac:.2%}""")

# Deduplicate data and apply heuristics
lowerCAmelCase				:     int					=				time.time()
lowerCAmelCase				:     Optional[int]					=				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				:     str					=				time.time()
					lowerCAmelCase				,		lowerCAmelCase				:     Union[str, Any]					=				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				:     Union[str, 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				:     Union[str, Any]					=				time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
					lowerCAmelCase				:     List[str]					=				str(data_dir / F"""file-{file_number+1:012}.json""")
					lowerCAmelCase				:     int					=				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}""")









"""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        __magic_name__				(			UpperCAmelCase__		,   UpperCAmelCase__		,   UpperCAmelCase__							):






				'''simple docstring'''
				__UpperCamelCase         =		[R"h\.\d+\.attn\.bias", R"h\.\d+\.attn\.masked_bias"]





				@register_to_config
				def __init__(			self						,					_a						,					_a						,					_a = None						,					_a = 50_257						,					_a = 1_024						,					_a = 768						,					_a = 12						,					_a = 12						,					_a = None						,					_a = "gelu_new"						,					_a = 0.1						,					_a = 0.1						,					_a = 0.1						,					_a = 1e-5						,					_a = 0.02						,					_a = True						,					_a = True						,					_a = False						,					_a = False						,					):





							"""simple docstring"""
							super().__init__()

							lowerCamelCase      =   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.'					)

							lowerCamelCase      =   prefix_inner_dim
							lowerCamelCase      =   prefix_hidden_dim

							lowerCamelCase      =   (
							    nn.Linear(self.prefix_inner_dim						,					self.prefix_hidden_dim					)
							    if self.prefix_hidden_dim is not None
							    else nn.Identity()
							)
							lowerCamelCase      =   (
							    nn.Linear(self.prefix_hidden_dim						,					_a					) if self.prefix_hidden_dim is not None else nn.Identity()
							)

							lowerCamelCase      =   GPTaConfig(
							    vocab_size=_a						,					n_positions=_a						,					n_embd=_a						,					n_layer=_a						,					n_head=_a						,					n_inner=_a						,					activation_function=_a						,					resid_pdrop=_a						,					embd_pdrop=_a						,					attn_pdrop=_a						,					layer_norm_epsilon=_a						,					initializer_range=_a						,					scale_attn_weights=_a						,					use_cache=_a						,					scale_attn_by_inverse_layer_idx=_a						,					reorder_and_upcast_attn=_a						,					)
							lowerCamelCase      =   GPTaLMHeadModel(_a					)





				def   _lowerCAmelCase							(			self						,					_a						,					_a						,					_a = None						,					_a = None						,					):





							"""simple docstring"""
							lowerCamelCase      =   self.transformer.transformer.wte(_a					)
							lowerCamelCase      =   self.encode_prefix(_a					)
							lowerCamelCase      =   self.decode_prefix(_a					)
							lowerCamelCase      =   torch.cat((prefix_embeds, embedding_text)						,					dim=1					)

							if labels is not None:
										lowerCamelCase      =   self.get_dummy_token(input_ids.shape[0]						,					input_ids.device					)
										lowerCamelCase      =   torch.cat((dummy_token, input_ids)						,					dim=1					)
							lowerCamelCase      =   self.transformer(inputs_embeds=_a						,					labels=_a						,					attention_mask=_a					)
							if self.prefix_hidden_dim is not None:
										return out, hidden
							else:
										return out





				def   _lowerCAmelCase							(			self						,					_a						,					_a					):





							"""simple docstring"""
							return torch.zeros(_a						,					self.prefix_length						,					dtype=torch.intaa						,					device=_a					)





				def   _lowerCAmelCase							(			self						,					_a					):





							"""simple docstring"""
							return self.encode_prefix(_a					)





				@torch.no_grad()
				def   _lowerCAmelCase							(			self						,					_a						,					_a						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   torch.split(_a						,					1						,					dim=0					)
							lowerCamelCase      =   []
							lowerCamelCase      =   []
							for feature in features:
										lowerCamelCase      =   self.decode_prefix(feature.to(_a					)					)  # back to the clip feature
										# Only support beam search for now
										lowerCamelCase ,  lowerCamelCase      =   self.generate_beam(
										    input_embeds=_a						,					device=_a						,					eos_token_id=_a					)
										generated_tokens.append(output_tokens[0]					)
										generated_seq_lengths.append(seq_lengths[0]					)
							lowerCamelCase      =   torch.stack(_a					)
							lowerCamelCase      =   torch.stack(_a					)
							return generated_tokens, generated_seq_lengths





				@torch.no_grad()
				def   _lowerCAmelCase							(			self						,					_a=None						,					_a=None						,					_a=None						,					_a = 5						,					_a = 67						,					_a = 1.0						,					_a = None						,					):





							"""simple docstring"""
							lowerCamelCase      =   eos_token_id
							lowerCamelCase      =   None
							lowerCamelCase      =   None
							lowerCamelCase      =   torch.ones(_a						,					device=_a						,					dtype=torch.int					)
							lowerCamelCase      =   torch.zeros(_a						,					device=_a						,					dtype=torch.bool					)

							if input_embeds is not None:
										lowerCamelCase      =   input_embeds
							else:
										lowerCamelCase      =   self.transformer.transformer.wte(_a					)

							for i in range(_a					):
										lowerCamelCase      =   self.transformer(inputs_embeds=_a					)
										lowerCamelCase      =   outputs.logits
										lowerCamelCase      =   logits[:, -1, :] / (temperature if temperature > 0 else 1.0)
										lowerCamelCase      =   logits.softmax(-1					).log()

										if scores is None:
													lowerCamelCase ,  lowerCamelCase      =   logits.topk(_a						,					-1					)
													lowerCamelCase      =   generated.expand(_a						,					*generated.shape[1:]					)
													lowerCamelCase ,  lowerCamelCase      =   next_tokens.permute(1						,					0					), scores.squeeze(0					)
													if tokens is None:
																lowerCamelCase      =   next_tokens
													else:
																lowerCamelCase      =   tokens.expand(_a						,					*tokens.shape[1:]					)
																lowerCamelCase      =   torch.cat((tokens, next_tokens)						,					dim=1					)
										else:
													lowerCamelCase      =   -float(np.inf					)
													lowerCamelCase      =   0
													lowerCamelCase      =   scores[:, None] + logits
													seq_lengths[~is_stopped] += 1
													lowerCamelCase      =   scores_sum / seq_lengths[:, None]
													lowerCamelCase ,  lowerCamelCase      =   scores_sum_average.view(-1					).topk(_a						,					-1					)
													lowerCamelCase      =   next_tokens // scores_sum.shape[1]
													lowerCamelCase      =   seq_lengths[next_tokens_source]
													lowerCamelCase      =   next_tokens % scores_sum.shape[1]
													lowerCamelCase      =   next_tokens.unsqueeze(1					)
													lowerCamelCase      =   tokens[next_tokens_source]
													lowerCamelCase      =   torch.cat((tokens, next_tokens)						,					dim=1					)
													lowerCamelCase      =   generated[next_tokens_source]
													lowerCamelCase      =   scores_sum_average * seq_lengths
													lowerCamelCase      =   is_stopped[next_tokens_source]

										lowerCamelCase      =   self.transformer.transformer.wte(next_tokens.squeeze()					).view(generated.shape[0]						,					1						,					-1					)
										lowerCamelCase      =   torch.cat((generated, next_token_embed)						,					dim=1					)
										lowerCamelCase      =   is_stopped + next_tokens.eq(_a					).squeeze()
										if is_stopped.all():
													break

							lowerCamelCase      =   scores / seq_lengths
							lowerCamelCase      =   scores.argsort(descending=_a					)
							# tokens tensors are already padded to max_seq_length
							lowerCamelCase      =   [tokens[i] for i in order]
							lowerCamelCase      =   torch.stack(_a						,					dim=0					)
							lowerCamelCase      =   torch.tensor([seq_lengths[i] for i in order]						,					dtype=seq_lengths.dtype					)
							return output_texts, seq_lengths



