| ''' 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.
|
| '''
|
|
|
|
|
|
|
|
|
| import struct, hashlib
|
| def sha1_hash32(data):
|
| return struct.unpack("<I", hashlib.sha1(data).digest()[:4])[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| from itertools import tee
|
| from typing import Any, Dict, Iterable, List, Tuple
|
|
|
| def ngrams(sequence: List[str], n: int, min_ngram_size: int) -> 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]+")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| import numpy as np
|
| MAX_HASH = np.uint64((1 << 32) - 1)
|
| MERSENNE_PRIME = np.uint64((1 << 61) - 1)
|
|
|
| def doc2hashvalues(
|
| content: str,
|
| num_perm: int,
|
| hashranges: List[Tuple[int, int]],
|
| permutations: np.ndarray,
|
| 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)
|
|
|
| a, b = permutations
|
| phv = np.bitwise_and(((hv * np.tile(a, (len(hv), 1)).T).T + b) % MERSENNE_PRIME, MAX_HASH)
|
|
|
| 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 ]
|
|
|
|
|
|
|
|
|
| from scipy.integrate import quad as integrate
|
| def optimal_param(
|
| threshold: float,
|
| num_perm: int,
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
| num_perm = 256
|
| threshold = 0.7
|
| K = 6
|
|
|
|
|
|
|
|
|
|
|
|
|
| params = optimal_param(threshold, num_perm)
|
| B = params["number_of_bands"]
|
| R = params["number_of_rows"]
|
|
|
|
|
| HASH_RANGES = [(i * R, (i + 1) * R) for i in range(B)]
|
|
|
|
|
| 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
|
|
|
|
|
| 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 ]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| '''
|
| 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
|
|
|
|
|
| if self.parent[x] != x:
|
| self.parent[x] = self.find(self.parent[x])
|
|
|
| return self.parent[x]
|
|
|
| def union(self, x, y):
|
| px = self.find(x)
|
| py = self.find(y)
|
| ret = min(px, py)
|
|
|
| self.parent[px] = ret
|
| self.parent[py] = ret
|
| return ret
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| '''
|
| `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__":
|
|
|
| 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 = 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)
|
|
|
| uf = UnionFind()
|
|
|
| for table in HASH_TABLES:
|
| for cluster in table.values():
|
| if len(cluster) <= 1: continue
|
| min_idx = min(cluster)
|
| for x in cluster:
|
| uf.union(x, min_idx)
|
|
|
|
|
|
|
| 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")
|
|
|