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

tokenization.py 12 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization classes."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import collections
  20. import re
  21. import unicodedata
  22. import six
  23. import tensorflow as tf
  24. def validate_case_matches_checkpoint(do_lower_case, init_checkpoint):
  25. """Checks whether the casing config is consistent with the checkpoint name."""
  26. # The casing has to be passed in by the user and there is no explicit check
  27. # as to whether it matches the checkpoint. The casing information probably
  28. # should have been stored in the bert_config.json file, but it's not, so
  29. # we have to heuristically detect it to validate.
  30. if not init_checkpoint:
  31. return
  32. m = re.match("^.*?([A-Za-z0-9_-]+)/bert_model.ckpt", init_checkpoint)
  33. if m is None:
  34. return
  35. model_name = m.group(1)
  36. lower_models = [
  37. "uncased_L-24_H-1024_A-16", "uncased_L-12_H-768_A-12",
  38. "multilingual_L-12_H-768_A-12", "chinese_L-12_H-768_A-12"
  39. ]
  40. cased_models = [
  41. "cased_L-12_H-768_A-12", "cased_L-24_H-1024_A-16",
  42. "multi_cased_L-12_H-768_A-12"
  43. ]
  44. is_bad_config = False
  45. if model_name in lower_models and not do_lower_case:
  46. is_bad_config = True
  47. actual_flag = "False"
  48. case_name = "lowercased"
  49. opposite_flag = "True"
  50. if model_name in cased_models and do_lower_case:
  51. is_bad_config = True
  52. actual_flag = "True"
  53. case_name = "cased"
  54. opposite_flag = "False"
  55. if is_bad_config:
  56. raise ValueError(
  57. "You passed in `--do_lower_case=%s` with `--init_checkpoint=%s`. "
  58. "However, `%s` seems to be a %s model, so you "
  59. "should pass in `--do_lower_case=%s` so that the fine-tuning matches "
  60. "how the model was pre-training. If this error is wrong, please "
  61. "just comment out this check." % (actual_flag, init_checkpoint,
  62. model_name, case_name, opposite_flag))
  63. def convert_to_unicode(text):
  64. """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
  65. if six.PY3:
  66. if isinstance(text, str):
  67. return text
  68. elif isinstance(text, bytes):
  69. return text.decode("utf-8", "ignore")
  70. else:
  71. raise ValueError("Unsupported string type: %s" % (type(text)))
  72. elif six.PY2:
  73. if isinstance(text, str):
  74. return text.decode("utf-8", "ignore")
  75. elif isinstance(text, unicode):
  76. return text
  77. else:
  78. raise ValueError("Unsupported string type: %s" % (type(text)))
  79. else:
  80. raise ValueError("Not running on Python2 or Python 3?")
  81. def printable_text(text):
  82. """Returns text encoded in a way suitable for print or `tf.logging`."""
  83. # These functions want `str` for both Python2 and Python3, but in one case
  84. # it's a Unicode string and in the other it's a byte string.
  85. if six.PY3:
  86. if isinstance(text, str):
  87. return text
  88. elif isinstance(text, bytes):
  89. return text.decode("utf-8", "ignore")
  90. else:
  91. raise ValueError("Unsupported string type: %s" % (type(text)))
  92. elif six.PY2:
  93. if isinstance(text, str):
  94. return text
  95. elif isinstance(text, unicode):
  96. return text.encode("utf-8")
  97. else:
  98. raise ValueError("Unsupported string type: %s" % (type(text)))
  99. else:
  100. raise ValueError("Not running on Python2 or Python 3?")
  101. # 加载词表
  102. # OrderedDict([('!', 999), ('"', 1000), ('#', 1001), ('##!', 29612), ('##"', 29613)...('###', 29614)])
  103. def load_vocab(vocab_file):
  104. """Loads a vocabulary file into a dictionary."""
  105. vocab = collections.OrderedDict()
  106. index = 0
  107. with tf.gfile.GFile(vocab_file, "r") as reader:
  108. while True:
  109. token = convert_to_unicode(reader.readline())
  110. if not token:
  111. break
  112. token = token.strip()
  113. vocab[token] = index
  114. index += 1
  115. return vocab
  116. def convert_by_vocab(vocab, items):
  117. """Converts a sequence of [tokens|ids] using the vocab."""
  118. # output --> [101, 2572, 3217, 5831, 102, 7727, 2000, 102]
  119. output = []
  120. for item in items:
  121. output.append(vocab[item])
  122. return output
  123. def convert_tokens_to_ids(vocab, tokens):
  124. return convert_by_vocab(vocab, tokens)
  125. def convert_ids_to_tokens(inv_vocab, ids):
  126. return convert_by_vocab(inv_vocab, ids)
  127. def whitespace_tokenize(text):
  128. """Runs basic whitespace cleaning and splitting on a piece of text."""
  129. # 按照空格切分每个词,并且去除两边多余空白
  130. text = text.strip()
  131. if not text:
  132. return []
  133. tokens = text.split()
  134. return tokens
  135. class FullTokenizer(object):
  136. """Runs end-to-end tokenziation."""
  137. def __init__(self, vocab_file, do_lower_case=True):
  138. self.vocab = load_vocab(vocab_file)
  139. # 键值对颠倒
  140. self.inv_vocab = {v: k for k, v in self.vocab.items()}
  141. self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
  142. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
  143. # 空格切分之后再采用词切分,将单词划分为更精细的结构
  144. def tokenize(self, text):
  145. split_tokens = []
  146. for token in self.basic_tokenizer.tokenize(text):
  147. for sub_token in self.wordpiece_tokenizer.tokenize(token):
  148. split_tokens.append(sub_token)
  149. return split_tokens
  150. def convert_tokens_to_ids(self, tokens):
  151. return convert_by_vocab(self.vocab, tokens)
  152. def convert_ids_to_tokens(self, ids):
  153. return convert_by_vocab(self.inv_vocab, ids)
  154. class BasicTokenizer(object):
  155. """Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
  156. def __init__(self, do_lower_case=True):
  157. """Constructs a BasicTokenizer.
  158. Args:
  159. do_lower_case: Whether to lower case the input.
  160. """
  161. self.do_lower_case = do_lower_case
  162. def tokenize(self, text):
  163. """Tokenizes a piece of text."""
  164. text = convert_to_unicode(text)
  165. text = self._clean_text(text)
  166. # This was added on November 1st, 2018 for the multilingual and Chinese
  167. # models. This is also applied to the English models now, but it doesn't
  168. # matter since the English models were not trained on any Chinese data
  169. # and generally don't have any Chinese data in them (there are Chinese
  170. # characters in the vocabulary because Wikipedia does have some Chinese
  171. # words in the English Wikipedia.).
  172. text = self._tokenize_chinese_chars(text)
  173. orig_tokens = whitespace_tokenize(text)
  174. split_tokens = []
  175. for token in orig_tokens:
  176. # 全部转成小写
  177. if self.do_lower_case:
  178. token = token.lower()
  179. token = self._run_strip_accents(token)
  180. split_tokens.extend(self._run_split_on_punc(token))
  181. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  182. return output_tokens
  183. def _run_strip_accents(self, text):
  184. """Strips accents from a piece of text."""
  185. # 去除各种变音字符
  186. text = unicodedata.normalize("NFD", text)
  187. output = []
  188. for char in text:
  189. cat = unicodedata.category(char)
  190. if cat == "Mn":
  191. continue
  192. output.append(char)
  193. return "".join(output)
  194. def _run_split_on_punc(self, text):
  195. """Splits punctuation on a piece of text."""
  196. # 切分标点字符 e.g. One-hot --> ["one","-","hot"]
  197. chars = list(text)
  198. i = 0
  199. start_new_word = True
  200. output = []
  201. while i < len(chars):
  202. char = chars[i]
  203. if _is_punctuation(char):
  204. output.append([char])
  205. start_new_word = True
  206. else:
  207. if start_new_word:
  208. output.append([])
  209. start_new_word = False
  210. output[-1].append(char)
  211. i += 1
  212. return ["".join(x) for x in output]
  213. def _tokenize_chinese_chars(self, text):
  214. # e.g. 源码一定要读懂呀 --> 源 码 一 定 要 读 懂 呀
  215. """Adds whitespace around any CJK character."""
  216. output = []
  217. for char in text:
  218. cp = ord(char)
  219. if self._is_chinese_char(cp):
  220. output.append(" ")
  221. output.append(char)
  222. output.append(" ")
  223. else:
  224. output.append(char)
  225. return "".join(output)
  226. def _is_chinese_char(self, cp):
  227. """Checks whether CP is the codepoint of a CJK character."""
  228. # This defines a "chinese character" as anything in the CJK Unicode block:
  229. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  230. #
  231. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  232. # despite its name. The modern Korean Hangul alphabet is a different block,
  233. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  234. # space-separated words, so they are not treated specially and handled
  235. # like the all of the other languages.
  236. if ((cp >= 0x4E00 and cp <= 0x9FFF) or #
  237. (cp >= 0x3400 and cp <= 0x4DBF) or #
  238. (cp >= 0x20000 and cp <= 0x2A6DF) or #
  239. (cp >= 0x2A700 and cp <= 0x2B73F) or #
  240. (cp >= 0x2B740 and cp <= 0x2B81F) or #
  241. (cp >= 0x2B820 and cp <= 0x2CEAF) or
  242. (cp >= 0xF900 and cp <= 0xFAFF) or #
  243. (cp >= 0x2F800 and cp <= 0x2FA1F)): #
  244. return True
  245. return False
  246. def _clean_text(self, text):
  247. """Performs invalid character removal and whitespace cleanup on text."""
  248. output = []
  249. for char in text:
  250. cp = ord(char)
  251. if cp == 0 or cp == 0xfffd or _is_control(char):
  252. continue
  253. if _is_whitespace(char):
  254. output.append(" ")
  255. else:
  256. output.append(char)
  257. return "".join(output)
  258. class WordpieceTokenizer(object):
  259. """Runs WordPiece tokenziation."""
  260. def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=200):
  261. self.vocab = vocab
  262. self.unk_token = unk_token
  263. self.max_input_chars_per_word = max_input_chars_per_word
  264. def tokenize(self, text):
  265. """Tokenizes a piece of text into its word pieces.
  266. This uses a greedy longest-match-first algorithm to perform tokenization
  267. using the given vocabulary.
  268. For example:
  269. input = "unaffable"
  270. output = ["un", "##aff", "##able"]
  271. Args:
  272. text: A single token or whitespace separated tokens. This should have
  273. already been passed through `BasicTokenizer.
  274. Returns:
  275. A list of wordpiece tokens.
  276. """
  277. text = convert_to_unicode(text)
  278. output_tokens = []
  279. for token in whitespace_tokenize(text):
  280. chars = list(token)
  281. if len(chars) > self.max_input_chars_per_word:
  282. output_tokens.append(self.unk_token)
  283. continue
  284. is_bad = False
  285. start = 0
  286. sub_tokens = []
  287. while start < len(chars):
  288. end = len(chars)
  289. cur_substr = None
  290. while start < end:
  291. substr = "".join(chars[start:end])
  292. if start > 0:
  293. substr = "##" + substr
  294. if substr in self.vocab:
  295. cur_substr = substr
  296. break
  297. end -= 1
  298. if cur_substr is None:
  299. is_bad = True
  300. break
  301. sub_tokens.append(cur_substr)
  302. start = end
  303. if is_bad:
  304. output_tokens.append(self.unk_token)
  305. else:
  306. output_tokens.extend(sub_tokens)
  307. return output_tokens
  308. def _is_whitespace(char):
  309. """Checks whether `chars` is a whitespace character."""
  310. # \t, \n, and \r are technically contorl characters but we treat them
  311. # as whitespace since they are generally considered as such.
  312. if char == " " or char == "\t" or char == "\n" or char == "\r":
  313. return True
  314. cat = unicodedata.category(char)
  315. if cat == "Zs":
  316. return True
  317. return False
  318. def _is_control(char):
  319. """Checks whether `chars` is a control character."""
  320. # These are technically control characters but we count them as whitespace
  321. # characters.
  322. if char == "\t" or char == "\n" or char == "\r":
  323. return False
  324. cat = unicodedata.category(char)
  325. if cat in ("Cc", "Cf"):
  326. return True
  327. return False
  328. def _is_punctuation(char):
  329. """Checks whether `chars` is a punctuation character."""
  330. cp = ord(char)
  331. # We treat all non-letter/number ASCII as punctuation.
  332. # Characters such as "^", "$", and "`" are not in the Unicode
  333. # Punctuation class but we treat them as punctuation anyways, for
  334. # consistency.
  335. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or
  336. (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):
  337. return True
  338. cat = unicodedata.category(char)
  339. if cat.startswith("P"):
  340. return True
  341. return False
Tip!

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

Comments

Loading...