Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

preprocess.py 10 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2017-present, Facebook, Inc.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the license found in the LICENSE file in
  6. # the root directory of this source tree. An additional grant of patent rights
  7. # can be found in the PATENTS file in the same directory.
  8. """
  9. Data pre-processing: build vocabularies and binarize training data.
  10. """
  11. from collections import Counter
  12. from itertools import zip_longest
  13. import os
  14. import shutil
  15. from fairseq import options, tasks
  16. from fairseq.data import indexed_dataset
  17. from fairseq.tokenizer import Tokenizer
  18. from multiprocessing import Pool
  19. from fairseq.utils import import_user_module
  20. def main(args):
  21. import_user_module(args)
  22. print(args)
  23. os.makedirs(args.destdir, exist_ok=True)
  24. target = not args.only_source
  25. task = tasks.get_task(args.task)
  26. def train_path(lang):
  27. return "{}{}".format(args.trainpref, ("." + lang) if lang else "")
  28. def file_name(prefix, lang):
  29. fname = prefix
  30. if lang is not None:
  31. fname += ".{lang}".format(lang=lang)
  32. return fname
  33. def dest_path(prefix, lang):
  34. return os.path.join(args.destdir, file_name(prefix, lang))
  35. def dict_path(lang):
  36. return dest_path("dict", lang) + ".txt"
  37. def build_dictionary(filenames, src=False, tgt=False):
  38. assert src ^ tgt
  39. return task.build_dictionary(
  40. filenames,
  41. workers=args.workers,
  42. threshold=args.thresholdsrc if src else args.thresholdtgt,
  43. nwords=args.nwordssrc if src else args.nwordstgt,
  44. padding_factor=args.padding_factor,
  45. )
  46. if args.joined_dictionary:
  47. assert (
  48. not args.srcdict or not args.tgtdict
  49. ), "cannot use both --srcdict and --tgtdict with --joined-dictionary"
  50. if args.srcdict:
  51. src_dict = task.load_dictionary(args.srcdict)
  52. elif args.tgtdict:
  53. src_dict = task.load_dictionary(args.tgtdict)
  54. else:
  55. assert (
  56. args.trainpref
  57. ), "--trainpref must be set if --srcdict is not specified"
  58. src_dict = build_dictionary({train_path(lang) for lang in [args.source_lang, args.target_lang]}, src=True)
  59. tgt_dict = src_dict
  60. else:
  61. if args.srcdict:
  62. src_dict = task.load_dictionary(args.srcdict)
  63. else:
  64. assert (
  65. args.trainpref
  66. ), "--trainpref must be set if --srcdict is not specified"
  67. src_dict = build_dictionary([train_path(args.source_lang)], src=True)
  68. if target:
  69. if args.tgtdict:
  70. tgt_dict = task.load_dictionary(args.tgtdict)
  71. else:
  72. assert (
  73. args.trainpref
  74. ), "--trainpref must be set if --tgtdict is not specified"
  75. tgt_dict = build_dictionary([train_path(args.target_lang)], tgt=True)
  76. else:
  77. tgt_dict = None
  78. src_dict.save(dict_path(args.source_lang))
  79. if target and tgt_dict is not None:
  80. tgt_dict.save(dict_path(args.target_lang))
  81. def make_binary_dataset(input_prefix, output_prefix, lang, num_workers):
  82. dict = task.load_dictionary(dict_path(lang))
  83. print("| [{}] Dictionary: {} types".format(lang, len(dict) - 1))
  84. n_seq_tok = [0, 0]
  85. replaced = Counter()
  86. def merge_result(worker_result):
  87. replaced.update(worker_result["replaced"])
  88. n_seq_tok[0] += worker_result["nseq"]
  89. n_seq_tok[1] += worker_result["ntok"]
  90. input_file = "{}{}".format(
  91. input_prefix, ("." + lang) if lang is not None else ""
  92. )
  93. offsets = Tokenizer.find_offsets(input_file, num_workers)
  94. pool = None
  95. if num_workers > 1:
  96. pool = Pool(processes=num_workers - 1)
  97. for worker_id in range(1, num_workers):
  98. prefix = "{}{}".format(output_prefix, worker_id)
  99. pool.apply_async(
  100. binarize,
  101. (
  102. args,
  103. input_file,
  104. dict,
  105. prefix,
  106. lang,
  107. offsets[worker_id],
  108. offsets[worker_id + 1],
  109. ),
  110. callback=merge_result,
  111. )
  112. pool.close()
  113. ds = indexed_dataset.IndexedDatasetBuilder(
  114. dataset_dest_file(args, output_prefix, lang, "bin")
  115. )
  116. merge_result(
  117. Tokenizer.binarize(
  118. input_file, dict, lambda t: ds.add_item(t), offset=0, end=offsets[1]
  119. )
  120. )
  121. if num_workers > 1:
  122. pool.join()
  123. for worker_id in range(1, num_workers):
  124. prefix = "{}{}".format(output_prefix, worker_id)
  125. temp_file_path = dataset_dest_prefix(args, prefix, lang)
  126. ds.merge_file_(temp_file_path)
  127. os.remove(indexed_dataset.data_file_path(temp_file_path))
  128. os.remove(indexed_dataset.index_file_path(temp_file_path))
  129. ds.finalize(dataset_dest_file(args, output_prefix, lang, "idx"))
  130. print(
  131. "| [{}] {}: {} sents, {} tokens, {:.3}% replaced by {}".format(
  132. lang,
  133. input_file,
  134. n_seq_tok[0],
  135. n_seq_tok[1],
  136. 100 * sum(replaced.values()) / n_seq_tok[1],
  137. dict.unk_word,
  138. )
  139. )
  140. def make_dataset(input_prefix, output_prefix, lang, num_workers=1):
  141. if args.output_format == "binary":
  142. make_binary_dataset(input_prefix, output_prefix, lang, num_workers)
  143. elif args.output_format == "raw":
  144. # Copy original text file to destination folder
  145. output_text_file = dest_path(
  146. output_prefix + ".{}-{}".format(args.source_lang, args.target_lang),
  147. lang,
  148. )
  149. shutil.copyfile(file_name(input_prefix, lang), output_text_file)
  150. def make_all(lang):
  151. if args.trainpref:
  152. make_dataset(args.trainpref, "train", lang, num_workers=args.workers)
  153. if args.validpref:
  154. for k, validpref in enumerate(args.validpref.split(",")):
  155. outprefix = "valid{}".format(k) if k > 0 else "valid"
  156. make_dataset(validpref, outprefix, lang)
  157. if args.testpref:
  158. for k, testpref in enumerate(args.testpref.split(",")):
  159. outprefix = "test{}".format(k) if k > 0 else "test"
  160. make_dataset(testpref, outprefix, lang)
  161. make_all(args.source_lang)
  162. if target:
  163. make_all(args.target_lang)
  164. print("| Wrote preprocessed data to {}".format(args.destdir))
  165. if args.alignfile:
  166. assert args.trainpref, "--trainpref must be set if --alignfile is specified"
  167. src_file_name = train_path(args.source_lang)
  168. tgt_file_name = train_path(args.target_lang)
  169. freq_map = {}
  170. with open(args.alignfile, "r", encoding='utf-8') as align_file:
  171. with open(src_file_name, "r", encoding='utf-8') as src_file:
  172. with open(tgt_file_name, "r", encoding='utf-8') as tgt_file:
  173. for a, s, t in zip_longest(align_file, src_file, tgt_file):
  174. si = Tokenizer.tokenize(s, src_dict, add_if_not_exist=False)
  175. ti = Tokenizer.tokenize(t, tgt_dict, add_if_not_exist=False)
  176. ai = list(map(lambda x: tuple(x.split("-")), a.split()))
  177. for sai, tai in ai:
  178. srcidx = si[int(sai)]
  179. tgtidx = ti[int(tai)]
  180. if srcidx != src_dict.unk() and tgtidx != tgt_dict.unk():
  181. assert srcidx != src_dict.pad()
  182. assert srcidx != src_dict.eos()
  183. assert tgtidx != tgt_dict.pad()
  184. assert tgtidx != tgt_dict.eos()
  185. if srcidx not in freq_map:
  186. freq_map[srcidx] = {}
  187. if tgtidx not in freq_map[srcidx]:
  188. freq_map[srcidx][tgtidx] = 1
  189. else:
  190. freq_map[srcidx][tgtidx] += 1
  191. align_dict = {}
  192. for srcidx in freq_map.keys():
  193. align_dict[srcidx] = max(freq_map[srcidx], key=freq_map[srcidx].get)
  194. with open(
  195. os.path.join(
  196. args.destdir,
  197. "alignment.{}-{}.txt".format(args.source_lang, args.target_lang),
  198. ),
  199. "w", encoding='utf-8'
  200. ) as f:
  201. for k, v in align_dict.items():
  202. print("{} {}".format(src_dict[k], tgt_dict[v]), file=f)
  203. def binarize(args, filename, dict, output_prefix, lang, offset, end, append_eos=True):
  204. ds = indexed_dataset.IndexedDatasetBuilder(
  205. dataset_dest_file(args, output_prefix, lang, "bin")
  206. )
  207. def consumer(tensor):
  208. ds.add_item(tensor)
  209. res = Tokenizer.binarize(
  210. filename,
  211. dict,
  212. consumer,
  213. offset=offset,
  214. end=end,
  215. append_eos=append_eos
  216. )
  217. ds.finalize(dataset_dest_file(args, output_prefix, lang, "idx"))
  218. return res
  219. def dataset_dest_prefix(args, output_prefix, lang):
  220. base = "{}/{}".format(args.destdir, output_prefix)
  221. lang_part = (
  222. ".{}-{}.{}".format(args.source_lang, args.target_lang, lang) if lang is not None else ""
  223. )
  224. return "{}{}".format(base, lang_part)
  225. def dataset_dest_file(args, output_prefix, lang, extension):
  226. base = dataset_dest_prefix(args, output_prefix, lang)
  227. return "{}.{}".format(base, extension)
  228. def get_offsets(input_file, num_workers):
  229. return Tokenizer.find_offsets(input_file, num_workers)
  230. def merge_files(files, outpath):
  231. ds = indexed_dataset.IndexedDatasetBuilder("{}.bin".format(outpath))
  232. for file in files:
  233. ds.merge_file_(file)
  234. os.remove(indexed_dataset.data_file_path(file))
  235. os.remove(indexed_dataset.index_file_path(file))
  236. ds.finalize("{}.idx".format(outpath))
  237. def cli_main():
  238. parser = options.get_preprocessing_parser()
  239. args = parser.parse_args()
  240. main(args)
  241. if __name__ == "__main__":
  242. cli_main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...