''' minhash dedup, nguồn: - blog https://huggingface.co/blog/dedup - code https://github.com/bigcode-project/bigcode-dataset/blob/main/near_deduplication/minhash_deduplication.py Giờ ta sẽ đi vào chi tiết từng bước cài đặt thuật toán minhash dedup. ''' #################################################################################### # Đầu tiên là một hàm hash biến dữ liệu có độ dài bất kỳ thành 1 số nguyên (8 bytes) import struct, hashlib def sha1_hash32(data): # data : bytes, return : int return struct.unpack(" Iterable: if len(sequence) < min_ngram_size: return [] iterables = tee(sequence, n) for i, sub_iterable in enumerate(iterables): for _ in range(i): next(sub_iterable, None) return zip(*iterables) import re; NON_ALPHA = re.compile("[^A-Za-z_0-9]+") # Test code # if __name__ == "__main__": # doc = "a b f h k h, m" # x = ngrams(NON_ALPHA.split(doc), 5, 5) # print(f'ngrams("{doc}".split(), 5, 5)') # for i, ngram in enumerate(x): print(f"{i}: {ngram}") # assert i == 2 # assert ngram == ('f', 'h', 'k', 'h', 'm') ###################################################################################### # Hàm quan trọng nhất biến nội dung 1 doc thành các hashvalues để so sánh sự trùng lặp # Nó map doc vào khoảng 2000 bytes của hashvalues, xem chi tiết ở ví dụ bên dưới import numpy as np MAX_HASH = np.uint64((1 << 32) - 1) MERSENNE_PRIME = np.uint64((1 << 61) - 1) def doc2hashvalues( content: str, # The content of the doc to be embedded. num_perm: int, # The number of permutations. hashranges: List[Tuple[int, int]], # The ranges of hash values. permutations: np.ndarray, # The permutations for the minhash. ngram_size: int = 5, min_ngram_size: int = 5, ): tokens = {" ".join(t) for t in ngrams(NON_ALPHA.split(content), ngram_size, min_ngram_size)} hv = np.array([sha1_hash32(token.encode("utf-8")) for token in tokens], dtype=np.uint64) # noqa: E501 a, b = permutations phv = np.bitwise_and(((hv * np.tile(a, (len(hv), 1)).T).T + b) % MERSENNE_PRIME, MAX_HASH) # noqa: E501 hashvalues = np.ones(num_perm, dtype=np.uint64) * MAX_HASH hashvalues = np.vstack([phv, hashvalues]).min(axis=0) return [ bytes(hashvalues[start:end].byteswap().data) \ for start, end in hashranges ] #################################################################################### # Hàm trợ giúp để tính toán ra các tham số tối ưu để chạy thuật toán from scipy.integrate import quad as integrate def optimal_param( threshold: float, # The threshold for similarity. num_perm: int, # The number of permutations. false_positive_weight: float = 0.5, false_negative_weight: float = 0.5, ): def false_positive_probability(threshold: float, b: int, r: int): def proba(s): return 1 - (1 - s ** float(r)) ** float(b) a, _ = integrate(proba, 0.0, threshold) return a def false_negative_probability(threshold: float, b: int, r: int): def proba(s): return 1 - (1 - (1 - s ** float(r)) ** float(b)) a, _ = integrate(proba, threshold, 1.0) return a min_error = float("inf") for b in range(1, num_perm + 1): max_r = int(num_perm / b) for r in range(1, max_r + 1): fp = false_positive_probability(threshold, b, r) fn = false_negative_probability(threshold, b, r) error = fp * false_positive_weight + fn * false_negative_weight if error < min_error: min_error = error opt = { "number_of_bands": b, "number_of_rows" : r, } return opt #################################################################################### # Các tham số, xem https://huggingface.co/blog/dedup#minhash-walkthrough # Đây là bộ tham số của thuật toán MinHash + LSH parameters (P, T, K, B, R) # Dưới đây sẽ định nghĩa và giải thích ý nghĩa của từng tham số num_perm = 256 # P: number of permutations / hashes threshold = 0.7 # T: Jaccard similarity threshold K = 6 # K: n-gram/shingle size # K = 13 # K: n-gram/shingle size ## Điều chỉnh K = 13 cho giống với cách làm của GPT3 # https://stanford-cs324.github.io/winter2022/lectures/data/#gpt-3-dataset # LSH breaks the fingerprint array into bands, each band containing the same number of rows # https://huggingface.co/blog/dedup#locality-sensitive-hashing params = optimal_param(threshold, num_perm) B = params["number_of_bands"] # 25 R = params["number_of_rows"] # 10 # Dựa vào R, B để tính ra HASH_RANGES (easy donkey) HASH_RANGES = [(i * R, (i + 1) * R) for i in range(B)] # [(0, 10), (10, 20), ..., (240, 250)] # Khởi tạo PERMUTATIONS ngẫu nhiên SEED = 42; RNG = np.random.RandomState(SEED) X = lambda : ( RNG.randint(1, MERSENNE_PRIME, dtype=np.uint64), RNG.randint(0, MERSENNE_PRIME, dtype=np.uint64) ) PERMUTATIONS = np.array( [ X() for _ in range(num_perm) ], dtype=np.uint64 ).T # Utils from base64 import b85encode, b85decode import json def to_b85hashvalues(hashvalues): return [ str(b85encode(hv), encoding="ascii") for hv in hashvalues ] def from_b85hashvalues(b85hashvalues): return [ b85decode(x) for x in b85hashvalues ] # Test code: giờ ta áp các hyper params này vào thuật toán doc2hashvalues # if __name__ == "__main__": # hashvalues = doc2hashvalues("a b c d e f", num_perm, HASH_RANGES, PERMUTATIONS, K, K) # size = len(hashvalues[0]); total = len(hashvalues) * size # print(f"Mỗi doc's content được đại diện bởi {B} hashvalues, {size} bytes each, total {total}") # # => Mỗi doc's content được đại diện bởi 25 hashvalues, 80 bytes each, total 2000 # b85hashvalues = to_b85hashvalues(hashvalues) # print(json.dumps(b85hashvalues, ensure_ascii=False)) # for idx, hv in enumerate(from_b85hashvalues(b85hashvalues)): # assert hv == hashvalues[idx] #################################################################################### # Cấu trúc dữ liệu và thuật toán UnionFind để tìm các docs trùng lặp trong 1 cluster # https://huggingface.co/blog/dedup#beyond-duplicate-pairs ''' our experiments from The Stack show that treating all of them as duplicates improves the downstream model's performance the best. And now we gradually moved towards this method instead, and it saves time as well. But to apply this to your dataset, we still recommend going over your dataset and looking at your duplicates, and then making a data-driven decision. ''' class UnionFind: def __init__(self): self.parent: Dict[int, int] = {} def find(self, x): if x not in self.parent: self.parent[x] = x # => tao là trùm cuối, # trùm cuối là thằng trỏ tới chính nó (ko có ai cao hơn) if self.parent[x] != x: # nếu không phải trùm cuối thì self.parent[x] = self.find(self.parent[x]) # => tìm thằng cấp cao hơn # đương nhiên sẽ chỉ dừng lại khi gặp trùm cuối return self.parent[x] # và trả lại giá trị trùm cuối def union(self, x, y): px = self.find(x) # px là trùm cuối của x py = self.find(y) # py là trùm cuối của y ret = min(px, py) self.parent[px] = ret self.parent[py] = ret return ret # hợp nhất 2 băng lại với nhau với trùm cuối có giá trị min(px, py) # Note: về lý thuyết có thể chọn bất kỳ px hoặc py là trùm cuối # Việc chọn min của px và py có lẽ liên quan tới hàm minhash ?!? # => cần tìm hiểu thêm !!! #################################################################################### # Tóm tắt thuật toán dedup dùng minhash ''' `hashvalues` của 1 doc gồm 20 giá trị hash gộp thành, và mỗi giá trị đó được phân vào một bảng khác nhau theo thứ tự xuất hiện. doc's hashvalues[ 0] vào HASH_TABLES[ 0] doc's hashvalues[ 1] vào HASH_TABLES[ 1] ... doc's hashvalues[19] vào HASH_TABLES[19] Các hashvalue lẻ được dùng làm key để nhóm các doc idx trong từng bảng lại với nhau HASH_TABLES[0][hashvalue] => { idx1, idx2, idx3 ... } Các idx trong cùng 1 nhóm (cluster) tức là nội dung bị trùng lặp và sẽ chỉ giữ lại 1 idx thôi và đó là min_idx của cluster đó. sau đó lại tiếp tục dedup ở các bảng khác theo kiểu union (phép hợp), để loại trừ tiếp ... ''' if __name__ == "__main__": # load docs import sys, gzip, os, subprocess, lzma input_file = sys.argv[1] if ".xz" in input_file: fin = lzma.open(input_file, "rt") output_file = input_file.replace(".jsonl.xz", "_dedup.jsonl") else: output_file = input_file.replace(".jsonl", "_dedup.jsonl") fin = open(input_file, "rt") if os.path.exists(output_file): print(f"Output file {output_file} đã tồn tại") sys.exit() docs = [] for line in fin: docs.append(line) fin.close() from collections import defaultdict HASH_TABLES = [ defaultdict(set) for _ in range(B) ] from multiprocessing import Pool def f(doc): # text = json.loads(doc)["text"] text = doc hashvalues = doc2hashvalues(text, num_perm, HASH_RANGES, PERMUTATIONS) return hashvalues with Pool(os.cpu_count() - 5) as p: docs2hashvalues = p.map(f, docs) for idx, hashvalues in enumerate(docs2hashvalues): for hashvalue, hashtable in zip(hashvalues, HASH_TABLES): hashtable[hashvalue].add(idx) # => 1 hash value trỏ 1 tập nhiều giá trị idx uf = UnionFind() for table in HASH_TABLES: for cluster in table.values(): # [{idx2, idx3}, {idx1}] if len(cluster) <= 1: continue # có <= 1 phần tử khỏi dedup :) min_idx = min(cluster) for x in cluster: # với mỗi cluster (of doc idx) thì min_idx là trùm cuối uf.union(x, min_idx) ## Cuối cùng chỉ giữ lại trùm cuối, các bọn khác là trùng lặp của trùm cuối nên bị loại bỏ. ## và thế là xong việc dedup dùng minhash :D print("\nSau khi dedup giữ lại:") import random count = 0 dup = {} with open(output_file, "wt") as fout: for idx in range(len(docs)): keep_idx = uf.find(idx) if idx == keep_idx: count += 1 line = docs[idx] fout.write(line) else: if keep_idx not in dup: dup[keep_idx] = [] dup[keep_idx].append(idx) print(output_file, count, "/", len(docs)) with open("DEDUP_LOG.txt", "wt") as fout: for k, v in dup.items(): fout.write(docs[k]) for x in v: fout.write(docs[x]) fout.write("\n\n- - - - - -\n\n")