3v324v23 commited on
Commit
e9210fc
·
1 Parent(s): db20422
dedup.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ''' minhash dedup, nguồn:
2
+ - blog https://huggingface.co/blog/dedup
3
+ - code https://github.com/bigcode-project/bigcode-dataset/blob/main/near_deduplication/minhash_deduplication.py
4
+
5
+ Giờ ta sẽ đi vào chi tiết từng bước cài đặt thuật toán minhash dedup.
6
+ '''
7
+
8
+ ####################################################################################
9
+ # Đầ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)
10
+
11
+ import struct, hashlib
12
+ def sha1_hash32(data): # data : bytes, return : int
13
+ return struct.unpack("<I", hashlib.sha1(data).digest()[:4])[0]
14
+
15
+ # Test code
16
+ # assert sha1_hash32(b'hello') == 499578026
17
+
18
+ ####################################################################################
19
+ # Một hàm tạo ngram từ mảng words đầu vào (easy donkey)
20
+
21
+ from itertools import tee
22
+ from typing import Any, Dict, Iterable, List, Tuple
23
+
24
+ def ngrams(sequence: List[str], n: int, min_ngram_size: int) -> Iterable:
25
+ if len(sequence) < min_ngram_size:
26
+ return []
27
+ iterables = tee(sequence, n)
28
+ for i, sub_iterable in enumerate(iterables):
29
+ for _ in range(i):
30
+ next(sub_iterable, None)
31
+ return zip(*iterables)
32
+
33
+ import re; NON_ALPHA = re.compile("[^A-Za-z_0-9]+")
34
+
35
+ # Test code
36
+ # if __name__ == "__main__":
37
+ # doc = "a b f h k h, m"
38
+ # x = ngrams(NON_ALPHA.split(doc), 5, 5)
39
+ # print(f'ngrams("{doc}".split(), 5, 5)')
40
+ # for i, ngram in enumerate(x): print(f"{i}: {ngram}")
41
+ # assert i == 2
42
+ # assert ngram == ('f', 'h', 'k', 'h', 'm')
43
+
44
+ ######################################################################################
45
+ # 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
46
+ # Nó map doc vào khoảng 2000 bytes của hashvalues, xem chi tiết ở ví dụ bên dưới
47
+
48
+ import numpy as np
49
+ MAX_HASH = np.uint64((1 << 32) - 1)
50
+ MERSENNE_PRIME = np.uint64((1 << 61) - 1)
51
+
52
+ def doc2hashvalues(
53
+ content: str, # The content of the doc to be embedded.
54
+ num_perm: int, # The number of permutations.
55
+ hashranges: List[Tuple[int, int]], # The ranges of hash values.
56
+ permutations: np.ndarray, # The permutations for the minhash.
57
+ ngram_size: int = 5,
58
+ min_ngram_size: int = 5,
59
+ ):
60
+ tokens = {" ".join(t) for t in ngrams(NON_ALPHA.split(content), ngram_size, min_ngram_size)}
61
+ hv = np.array([sha1_hash32(token.encode("utf-8")) for token in tokens], dtype=np.uint64) # noqa: E501
62
+
63
+ a, b = permutations
64
+ phv = np.bitwise_and(((hv * np.tile(a, (len(hv), 1)).T).T + b) % MERSENNE_PRIME, MAX_HASH) # noqa: E501
65
+
66
+ hashvalues = np.ones(num_perm, dtype=np.uint64) * MAX_HASH
67
+ hashvalues = np.vstack([phv, hashvalues]).min(axis=0)
68
+
69
+ return [ bytes(hashvalues[start:end].byteswap().data) \
70
+ for start, end in hashranges ]
71
+
72
+ ####################################################################################
73
+ # Hàm trợ giúp để tính toán ra các tham số tối ưu để chạy thuật toán
74
+
75
+ from scipy.integrate import quad as integrate
76
+ def optimal_param(
77
+ threshold: float, # The threshold for similarity.
78
+ num_perm: int, # The number of permutations.
79
+ false_positive_weight: float = 0.5,
80
+ false_negative_weight: float = 0.5,
81
+ ):
82
+ def false_positive_probability(threshold: float, b: int, r: int):
83
+ def proba(s): return 1 - (1 - s ** float(r)) ** float(b)
84
+ a, _ = integrate(proba, 0.0, threshold)
85
+ return a
86
+
87
+ def false_negative_probability(threshold: float, b: int, r: int):
88
+ def proba(s): return 1 - (1 - (1 - s ** float(r)) ** float(b))
89
+ a, _ = integrate(proba, threshold, 1.0)
90
+ return a
91
+
92
+ min_error = float("inf")
93
+
94
+ for b in range(1, num_perm + 1):
95
+ max_r = int(num_perm / b)
96
+ for r in range(1, max_r + 1):
97
+ fp = false_positive_probability(threshold, b, r)
98
+ fn = false_negative_probability(threshold, b, r)
99
+ error = fp * false_positive_weight + fn * false_negative_weight
100
+ if error < min_error:
101
+ min_error = error
102
+ opt = {
103
+ "number_of_bands": b,
104
+ "number_of_rows" : r,
105
+ }
106
+ return opt
107
+
108
+ ####################################################################################
109
+ # Các tham số, xem https://huggingface.co/blog/dedup#minhash-walkthrough
110
+ # Đây là bộ tham số của thuật toán MinHash + LSH parameters (P, T, K, B, R)
111
+ # Dưới đây sẽ định nghĩa và giải thích ý nghĩa của từng tham số
112
+
113
+ num_perm = 256 # P: number of permutations / hashes
114
+ threshold = 0.7 # T: Jaccard similarity threshold
115
+ K = 9 # K: n-gram/shingle size
116
+ # K = 13 # K: n-gram/shingle size
117
+ ## Điều chỉnh K = 13 cho giống với cách làm của GPT3
118
+ # https://stanford-cs324.github.io/winter2022/lectures/data/#gpt-3-dataset
119
+
120
+ # LSH breaks the fingerprint array into bands, each band containing the same number of rows
121
+ # https://huggingface.co/blog/dedup#locality-sensitive-hashing
122
+ params = optimal_param(threshold, num_perm)
123
+ B = params["number_of_bands"] # 25
124
+ R = params["number_of_rows"] # 10
125
+
126
+ # Dựa vào R, B để tính ra HASH_RANGES (easy donkey)
127
+ HASH_RANGES = [(i * R, (i + 1) * R) for i in range(B)] # [(0, 10), (10, 20), ..., (240, 250)]
128
+
129
+ # Khởi tạo PERMUTATIONS ngẫu nhiên
130
+ SEED = 42; RNG = np.random.RandomState(SEED)
131
+ X = lambda : (
132
+ RNG.randint(1, MERSENNE_PRIME, dtype=np.uint64),
133
+ RNG.randint(0, MERSENNE_PRIME, dtype=np.uint64)
134
+ )
135
+ PERMUTATIONS = np.array( [ X() for _ in range(num_perm) ], dtype=np.uint64 ).T
136
+
137
+ # Utils
138
+ from base64 import b85encode, b85decode
139
+ import json
140
+
141
+ def to_b85hashvalues(hashvalues):
142
+ return [ str(b85encode(hv), encoding="ascii") for hv in hashvalues ]
143
+
144
+ def from_b85hashvalues(b85hashvalues):
145
+ return [ b85decode(x) for x in b85hashvalues ]
146
+
147
+ # Test code: giờ ta áp các hyper params này vào thuật toán doc2hashvalues
148
+ # if __name__ == "__main__":
149
+ # hashvalues = doc2hashvalues("a b c d e f", num_perm, HASH_RANGES, PERMUTATIONS, K, K)
150
+ # size = len(hashvalues[0]); total = len(hashvalues) * size
151
+ # print(f"Mỗi doc's content được đại diện bởi {B} hashvalues, {size} bytes each, total {total}")
152
+ # # => Mỗi doc's content được đại diện bởi 25 hashvalues, 80 bytes each, total 2000
153
+ # b85hashvalues = to_b85hashvalues(hashvalues)
154
+ # print(json.dumps(b85hashvalues, ensure_ascii=False))
155
+ # for idx, hv in enumerate(from_b85hashvalues(b85hashvalues)):
156
+ # assert hv == hashvalues[idx]
157
+
158
+ ####################################################################################
159
+ # 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
160
+ # https://huggingface.co/blog/dedup#beyond-duplicate-pairs
161
+ '''
162
+ our experiments from The Stack show that treating all of them as duplicates improves
163
+ the downstream model's performance the best. And now we gradually moved towards this
164
+ method instead, and it saves time as well. But to apply this to your dataset, we
165
+ still recommend going over your dataset and looking at your duplicates,
166
+ and then making a data-driven decision.
167
+ '''
168
+ class UnionFind:
169
+
170
+ def __init__(self):
171
+ self.parent: Dict[int, int] = {}
172
+
173
+ def find(self, x):
174
+ if x not in self.parent:
175
+ self.parent[x] = x # => tao là trùm cuối,
176
+ # trùm cuối là thằng trỏ tới chính nó (ko có ai cao hơn)
177
+
178
+ if self.parent[x] != x: # nếu không phải trùm cuối thì
179
+ self.parent[x] = self.find(self.parent[x]) # => tìm thằng cấp cao hơn
180
+ # đương nhiên sẽ chỉ dừng lại khi gặp trùm cuối
181
+ return self.parent[x] # và trả lại giá trị trùm cuối
182
+
183
+ def union(self, x, y):
184
+ px = self.find(x) # px là trùm cuối của x
185
+ py = self.find(y) # py là trùm cuối của y
186
+ ret = min(px, py)
187
+
188
+ self.parent[px] = ret
189
+ self.parent[py] = ret
190
+ return ret
191
+ # hợp nhất 2 băng lại với nhau với trùm cuối có giá trị min(px, py)
192
+ # Note: về lý thuyết có thể chọn bất kỳ px hoặc py là trùm cuối
193
+ # Việc chọn min của px và py có lẽ liên quan tới hàm minhash ?!?
194
+ # => cần tìm hiểu thêm !!!
195
+
196
+ ####################################################################################
197
+ # Tóm tắt thuật toán dedup dùng minhash
198
+ '''
199
+ `hashvalues` của 1 doc gồm 20 giá trị hash gộp thành,
200
+ và mỗi giá trị đó được phân vào một bảng khác nhau theo thứ tự xuất hiện.
201
+
202
+ doc's hashvalues[ 0] vào HASH_TABLES[ 0]
203
+ doc's hashvalues[ 1] vào HASH_TABLES[ 1]
204
+ ...
205
+ doc's hashvalues[19] vào HASH_TABLES[19]
206
+
207
+ 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
208
+ HASH_TABLES[0][hashvalue] => { idx1, idx2, idx3 ... }
209
+ 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
210
+ và đó là min_idx của cluster đó.
211
+
212
+ 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 ...
213
+ '''
214
+
215
+ if __name__ == "__main__":
216
+ # load docs
217
+ import sys, gzip, os, subprocess, lzma
218
+ docs = []
219
+ input_file = sys.argv[1]
220
+ if ".xz" not in input_file:
221
+ print(f"Input file {input_file} cần có định dạng .xz")
222
+ sys.exit()
223
+
224
+ output_file = input_file.replace(".jsonl.xz", "_dedup.jsonl")
225
+ if os.path.exists(output_file):
226
+ print(f"Output file {output_file} đã tồn t��i")
227
+ sys.exit()
228
+
229
+ with lzma.open(input_file, "rt") as fin:
230
+ for line in fin: docs.append(line)
231
+
232
+ from collections import defaultdict
233
+ HASH_TABLES = [ defaultdict(set) for _ in range(B) ]
234
+
235
+ from multiprocessing import Pool
236
+ def f(doc):
237
+ # text = doc.split('", "time": "')[0][10:].replace("\\n", " ") # print(text) # OK!
238
+ text = doc
239
+ hashvalues = doc2hashvalues(text, num_perm, HASH_RANGES, PERMUTATIONS)
240
+ return hashvalues
241
+
242
+ with Pool(os.cpu_count() - 5) as p:
243
+ docs2hashvalues = p.map(f, docs)
244
+
245
+ for idx, hashvalues in enumerate(docs2hashvalues):
246
+ for hashvalue, hashtable in zip(hashvalues, HASH_TABLES):
247
+ hashtable[hashvalue].add(idx) # => 1 hash value trỏ 1 tập nhiều giá trị idx
248
+
249
+ uf = UnionFind()
250
+
251
+ for table in HASH_TABLES:
252
+ for cluster in table.values(): # [{idx2, idx3}, {idx1}]
253
+ if len(cluster) <= 1: continue # có <= 1 phần tử khỏi dedup :)
254
+ min_idx = min(cluster)
255
+ for x in cluster: # với mỗi cluster (of doc idx) thì min_idx là trùm cuối
256
+ uf.union(x, min_idx)
257
+
258
+ ## 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ỏ.
259
+ ## và thế là xong việc dedup dùng minhash :D
260
+ print("\nSau khi dedup giữ lại:")
261
+ import random
262
+ count = 0; b85 = 0; check = 5
263
+ with open(output_file, "wt") as fout:
264
+ for idx in range(len(docs)):
265
+ keep_idx = uf.find(idx)
266
+ if idx == keep_idx:
267
+ count += 1
268
+ if count % 10_000 == 0: print(count, b85)
269
+ line = docs[idx]
270
+ # if len(line) > 3000:
271
+ # b85 += 1
272
+ # hvs = to_b85hashvalues(docs2hashvalues[idx])
273
+ # hvs = json.dumps(hvs, ensure_ascii=False)
274
+ # line = line[:-2] + f', "hashvalues": {hvs}' + "}\n"
275
+ # if check > 0 and random.random() > 0.5: # kiểm tra ngẫu nhiên check lần
276
+ # check -= 1
277
+ # text = line.split('", "time": "')[0][10:].replace("\\n", " ")
278
+ # print(text) # OK!
279
+ # ohvs = doc2hashvalues(text, num_perm, HASH_RANGES, PERMUTATIONS)
280
+ # data = json.loads(line)
281
+ # chvs = data["hashvalues"]
282
+ # chvs = from_b85hashvalues(chvs)
283
+ # assert ohvs == chvs
284
+ fout.write(line)
285
+ print(output_file, count, b85)
qwen_finalize.py → tools/qwen_finalize.py RENAMED
File without changes
qwen_sort.py → tools/qwen_sort.py RENAMED
File without changes