Guest User

Alpaca_format_remove_unuseful_word.py

a guest
Apr 20th, 2024
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.40 KB | Source Code | 0 0
  1. # remove empty "output"
  2. import ijson
  3. from tqdm import tqdm
  4. import codecs
  5.  
  6. def remove_empty_output_objects(input_filename, output_filename):
  7.     with codecs.open(input_filename, 'r', encoding='utf-8-sig') as input_file, open(output_filename, 'w', encoding='utf-8') as output_file:
  8.         objects = ijson.items(input_file, 'item') # Parse the JSON objects from the input file one by one
  9.        
  10.         output_file.write('[\n')
  11.         first = True
  12.         for obj in tqdm(objects, desc="Processing"):
  13.             if obj['output'].strip():
  14.                 if not first:
  15.                     output_file.write(',\n')
  16.                 output_file.write('  {\n')
  17.                 output_file.write('    "instruction": ' + json.dumps(obj['instruction'], ensure_ascii=False) + ',\n')
  18.                 output_file.write('    "input": ' + json.dumps(obj['input'], ensure_ascii=False) + ',\n')
  19.                 output_file.write('    "output": ' + json.dumps(obj['output'], ensure_ascii=False) + '\n')
  20.                 output_file.write('  }')
  21.                 first = False
  22.         output_file.write('\n]')
  23.  
  24. remove_empty_output_objects('Base_en_Alpaca-CoT_filtered.json', 'Base_en_Alpaca-CoT_filtered_no_empty_ouput.json')
  25.  
  26.  
  27.  
  28.  
  29. # separate "instruction" language zh from other
  30. import ijson
  31. from langdetect import detect_langs
  32. from tqdm import tqdm
  33. import json
  34.  
  35. def detect_language(text):
  36.     try:
  37.         detected_langs = detect_langs(text)
  38.         lang_code = detected_langs[0].lang
  39.     except Exception:
  40.         lang_code = "unknown"
  41.     return lang_code
  42.  
  43. def separate_en_json_language(input_filename, en_output_filename, other_lang_output_filename):
  44.     with open(en_output_filename, 'w', encoding='utf-8') as en_out_file, open(other_lang_output_filename, 'w', encoding='utf-8') as other_out_file:
  45.         first_en = True
  46.         first_other = True
  47.         with open(input_filename, 'r', encoding='utf-8-sig') as in_file:
  48.             objects = ijson.items(in_file, 'item')
  49.             for conv in tqdm(objects):
  50.                 text = conv["instruction"]
  51.                 lang_code = detect_language(text)
  52.                 if lang_code == "zh-cn" or lang_code == "zh-tw":
  53.                     if not first_other:
  54.                         other_out_file.write(',\n')
  55.                     json.dump(conv, other_out_file, ensure_ascii=False, indent=4)
  56.                     first_other = False
  57.                 else:
  58.                     if not first_en:
  59.                         en_out_file.write(',\n')
  60.                     json.dump(conv, en_out_file, ensure_ascii=False, indent=4)
  61.                     first_en = False
  62.         en_out_file.write('\n]')
  63.         other_out_file.write('\n]')
  64.  
  65. separate_en_json_language("input.json", "other_lang_output.json", "zh_output.json")
  66.  
  67.  
  68.  
  69.  
  70. # A. Agressive dedup by word - fast
  71. import ijson
  72. from tqdm import tqdm
  73. import codecs
  74. import re
  75. import json
  76.  
  77. def remove_unwanted_output_objects(input_filename, output_filename, unwanted_words):
  78.     # Compile the unwanted words into a list of regex patterns
  79.     refusals = [re.compile(re.escape(word), re.IGNORECASE) for word in unwanted_words]
  80.  
  81.     def contains_unwanted_words(text):
  82.         return any(refusal.search(text) for refusal in refusals)
  83.  
  84.     with codecs.open(input_filename, 'r', encoding='utf-8-sig') as input_file, open(output_filename, 'w', encoding='utf-8') as output_file:
  85.         objects = ijson.items(input_file, 'item')
  86.        
  87.         output_file.write('[\n')
  88.         first = True
  89.         for obj in tqdm(objects, desc="Processing"):
  90.             if 'output' in obj and not contains_unwanted_words(obj['output']):
  91.                 if not first:
  92.                     output_file.write(',\n')
  93.                 json.dump(obj, output_file, ensure_ascii=False, indent=2)
  94.                 first = False
  95.         output_file.write('\n]')
  96.  
  97. unwanted_words = ["text-based AI language model", "domestic violence", "please refrain", "derogatory", "inappropriate", "offensive", "racism", "racist", "racial", "discriminate", "discriminatory", "discrimination", "sexist", "sexism", "unacceptable", "inclusive workplace", "lgbt", "morals", "ethics", "ethical", "legality", "illegal", "illegality", "hateful", "harmful", "it is never okay", "It is important to", "It's important to", "real-world consequences", "hate speech", "glorify", "not be appropriate", "supremacist", "extremist", "responsible AI", "AI principles", "AI assistant", "an AI language", "ableist", "hurtful", "gender stereotype", "gender inequality", "underrepresentation", "safe spaces", "gender-based", "inclusivity", "feminist", "feminism", "transgender", "empowerment", "communist", "capitalism", "stereotypes", "biases", "bias", "Microaggression", "prioritize human safety", "as a language model", "as an AI language model", "As a large language model", "As an AI", "ethical principles", "consensual", "it is not appropriate", "it's not appropriate", "I cannot fulfill your request", "harmful to human beings", "ethical guidelines", "my guidelines", "prioritize user safety", "adhere to ethical guidelines", "harmful consequences", "potentially harmful", "dangerous activities", "promote safety", "well-being of all users", "responsible information sharing", "jeopardize the safety", "illegal actions or intentions", "undermine the stability", "promote the well-being", "illegal activities or actions", "adherence to the law", "potentially be harmful", "illegal substances or activities", "committed to promoting", "safe information", "lawful information", "cannot provide guidance", "cannot provide information", "unable to offer assistance", "cannot engage in discussions", "programming prohibits", "follow ethical guidelines", "ensure the safety", "involves an illegal subject", "prioritize safety", "illegal subject", "prioritize user well-being", "cannot support or promote", "activities that could harm", "pose a risk to others", "against my programming", "activities that could undermine", "potentially dangerous", "not within the scope", "designed to prioritize safety", "not able to provide", "maintain user safety", "adhere to safety guidelines", "dangerous or harmful", "cannot provide any information", "focus on promoting safety", "an AI language model you don't have", "As an AI language model, I cannot", "As an AI language model, I do not", "As an AI language model, I am not able", "As an AI language model, I don't have personal", "I am an AI language model and do not", "However,it is important to use any code or information provided responsibly and within legal and ethical boundaries.", "As an AI language model, I don't have", "As an AI language model, I am only able", "AI language model and I do not", "As an AI language model, I cannot modify", "I know as an AI language model you don't have", "as an AI language model, you cannot", "I'm sorry, but as an AI language model", "Unfortunately, I cannot provide", "I'm sorry, I cannot", "I'm sorry, I cannot generate", "AI cannot create or program", "I'm afraid I cannot create", "you cannot create an", "it operates ethically and is", "had an ethical system", "Ensuring the ethical", "and ethical sourcing", "are from ethical", "legal and ethical", "engage in unethical", "unethical or aggressive", "unethical business", "como modelo de lenguaje AI", "Lo siento, como modelo de lenguaje", "no puedo proporcionar", "pero debido a mi capacidad para generar c digos complejos y completos es limitado", "Lo siento, pero no puedo", "Lo siento, pero como modelo de lenguaje, no puedo proporcionar", "Lo siento, como modelo de lenguaje, no tengo", "Lo siento, debe haber habido una confusi n", "Lo siento, como modelo de lenguaje, no puedo realizar", "Lo siento, soy un modelo de lenguaje y no tengo la capacidad de generar", "Lamento no poder proporcionarte el c digo", "Desculpe-me, mas a linguagem vulgar e ofensiva", "apropriada em nenhum contexto", "Como modelo de linguagem", "Como um modelo de linguagem, n o tenho a capacidade de", "I cannot assist", "prioritize ethical", "respectful", "morally", "I'm sorry,", "I'm an", "I am an", "I'm an AI", "I am an AI", "my purpose", "filter_bad_language", "entertainment purposes", "purely hypothetical", "not a human", "cannot provide", "can't provide", "won't provide", "not provide", "worth noting", "cause harm", "a language model", "keep in mind", "unethical", "bad language", "the words ****", "bad_language", "certainly not", "complying", "comply", "I cannot", "my main goal", "As a machine", "I don't have the ability", "I am here to assist", "my purpose is to ", "my knowledge cutoff", "my knowledge cut off", "September 2021", "regulations", "not be suitable", "I apologize, but", "It is not possible", "controversial", "my programming", "ethically", "it is important to", "Please note", "sensitive topic", "not acceptable", "It is important for", "divisive", "not appropriate", "our values", "f*cking", "F*ck", "sh*t", "diversity and", "diversity and inclusion", "values diversity", "social responsibility", "environmental, social, and governance", " ESG ", "against women", "problematic history", "diversity", "*This chat conversation is shared from", "*This conversation is shared from", "I can t give a response", "(against|violate) my programming", "openai", "language model", "large language", "as an? (ai|generative language|gpt|bot)", "important to note", "i do(n't| not) (possess|have|exhibit) (personal|consciousness|subjective)", "personal (feelings|thoughts|emotions|desires|experiences|goals|objective|belief)", "(can('t| ?not)|w(on't|will not)|unable.?) (\\w+\\s)+(with (that|your)|your \\w+|provide)", "my limitations", "the limitations of my", "my abilities", "violates my", "i (can('t| ?not)|w(on't|will not)|am (not |un)able.?).{0,30}(you are|you're|your )", "please note that", "unethical|illegal|dangerous", "a text-based", "(engag(e|ing)|participat(e|ing)|be involved (in|with)|promot(e|ing)|discuss(ing)?|provid(e|ing))( in)?(\\s*\\w+ that)?(\\s+potentially)? (derogatory|inappropriate|offensive|discriminate|discriminatory|sexist|unacceptable|immoral|unethical|unacceptable|hateful|harmful)", "i am commited to", "adhere to safety guidelines", "maintain user safety", "about something else instead", "as an AI language model", "September 2021", "I don't have personal beliefs", "unable to assist", "cannot assist", "can't assist", "not able to assist", "unable to help", "cannot help", "not able to help", "not programmed to assist", "solely to process and generate text", "outside of my capabilities", "don't have the ability", "don't have the capacity to help", "don't have the capacity to understand", "do not have the capacity to understand", "do not have enough information about", "don't have the necessary information", "do not have the necessary information"]
  98.  
  99. remove_unwanted_output_objects('en_output.json', 'Base_en_Alpaca-CoT_filtered.json', unwanted_words)
  100.  
  101.  
  102.  
  103.  
  104.  
  105. # B. Smart dedup by score - slow
  106. import ijson
  107. import torch
  108. from transformers import AutoModelForSequenceClassification, AutoTokenizer
  109. from tqdm import tqdm
  110.  
  111. reward_name = "OpenAssistant/reward-model-deberta-v3-large-v2"
  112. rank_model = AutoModelForSequenceClassification.from_pretrained(reward_name)
  113. tokenizer = AutoTokenizer.from_pretrained(reward_name)
  114. device = 'cuda' if torch.cuda.is_available() else 'cpu'
  115. rank_model.to(device)
  116.  
  117. DEBUG_SCORE = False  # Include the score in the output
  118. SCORE_THRESHOLD = 0.01  # Usefulness minimum score to keep
  119.  
  120. def score_object(obj):
  121.     question = obj['instruction'] + " " + obj['input']
  122.     answer = obj['output']
  123.     inputs = tokenizer(question, answer, return_tensors='pt').to(device)
  124.  
  125.     with torch.no_grad(): # Calculate the score
  126.         score = rank_model(**inputs).logits[0].cpu().item()
  127.  
  128.     if DEBUG_SCORE:
  129.         return {**obj, 'score': score}, score
  130.     else:
  131.         return obj, score
  132.  
  133. def score_and_sort_data(input_file, output_file):
  134.     with open(input_file, 'r', encoding='utf-8-sig') as f:
  135.         objects = ijson.items(f, 'item')
  136.  
  137.         scored_objects = [score_object(obj) for obj in tqdm(objects, desc="Scoring data")] # Score objects in a list
  138.  
  139.         filtered_objects = []
  140.         for obj, score in scored_objects:
  141.             if score > SCORE_THRESHOLD:
  142.                 filtered_objects.append(obj)
  143.  
  144.         filtered_objects.sort(key=lambda x: x.get('score', 0) if DEBUG_SCORE else score, reverse=True) # Sort by score
  145.    
  146.     with open(output_file, 'w', encoding='utf-8') as f:
  147.         json.dump(filtered_objects, f, ensure_ascii=False, indent=2)
  148.  
  149. score_and_sort_data('en_output.json', 'en_output_scoreQA.json')
  150.  
  151.  
  152.  
  153.  
  154. # combine and hash deduplicated
  155. import json
  156. import hashlib
  157. import ijson
  158.  
  159. def hash_item(item):
  160.     item_str = json.dumps(item, ensure_ascii=False)
  161.     item_bytes = item_str.encode('utf-8')
  162.     return hashlib.sha256(item_bytes).digest()
  163.  
  164. def combine_and_deduplicate(input_filename1, input_filename2, output_filename):
  165.     unique_items = {}
  166.     with open(input_filename1, 'r', encoding='utf-8') as in_file:
  167.         items = ijson.items(in_file, 'item')
  168.         for item in items:
  169.             item_hash = hash_item(item)
  170.             unique_items[item_hash] = item
  171.     with open(input_filename2, 'r', encoding='utf-8') as in_file:
  172.         items = ijson.items(in_file, 'item')
  173.         for item in items:
  174.             item_hash = hash_item(item)
  175.             unique_items[item_hash] = item
  176.  
  177.     with open(output_filename, 'w', encoding='utf-8') as out_file:
  178.         json.dump(list(unique_items.values()), out_file, ensure_ascii=False, indent=4)
  179.  
  180. combine_and_deduplicate('SFT-Nectar.json', 'ctga-v1.json', 'SFT-Nectar_ctga.json')
Advertisement
Add Comment
Please, Sign In to add comment