You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_text_bert_tokenizer.py 9.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """
  16. Testing BertTokenizer op in DE
  17. """
  18. import numpy as np
  19. import mindspore.dataset as ds
  20. from mindspore import log as logger
  21. import mindspore.dataset.text as text
  22. BERT_TOKENIZER_FILE = "../data/dataset/testTokenizerData/bert_tokenizer.txt"
  23. vocab_bert = [
  24. "床", "前", "明", "月", "光", "疑", "是", "地", "上", "霜", "举", "头", "望", "低", "思", "故", "乡",
  25. "繁", "體", "字", "嘿", "哈", "大", "笑", "嘻",
  26. "i", "am", "mak", "make", "small", "mistake", "##s", "during", "work", "##ing", "hour",
  27. "😀", "😃", "😄", "😁", "+", "/", "-", "=", "12", "28", "40", "16", " ", "I",
  28. "[CLS]", "[SEP]", "[UNK]", "[PAD]", "[MASK]", "[unused1]", "[unused10]"
  29. ]
  30. pad = '<pad>'
  31. test_paras = [
  32. # test chinese text
  33. dict(
  34. first=1,
  35. last=4,
  36. expect_str=[['床', '前', '明', '月', '光'],
  37. ['疑', '是', '地', '上', '霜'],
  38. ['举', '头', '望', '明', '月'],
  39. ['低', '头', '思', '故', '乡']],
  40. expected_offsets_start=[[0, 3, 6, 9, 12],
  41. [0, 3, 6, 9, 12],
  42. [0, 3, 6, 9, 12],
  43. [0, 3, 6, 9, 12]],
  44. expected_offsets_limit=[[3, 6, 9, 12, 15],
  45. [3, 6, 9, 12, 15],
  46. [3, 6, 9, 12, 15],
  47. [3, 6, 9, 12, 15]],
  48. vocab_list=vocab_bert
  49. ),
  50. # test english text
  51. dict(
  52. first=5,
  53. last=5,
  54. expect_str=[['i', 'am', 'mak', '##ing', 'small', 'mistake', '##s', 'during', 'work', '##ing', 'hour', '##s']],
  55. expected_offsets_start=[[0, 2, 5, 8, 12, 18, 25, 27, 34, 38, 42, 46]],
  56. expected_offsets_limit=[[1, 4, 8, 11, 17, 25, 26, 33, 38, 41, 46, 47]],
  57. lower_case=True,
  58. vocab_list=vocab_bert
  59. ),
  60. dict(
  61. first=5,
  62. last=5,
  63. expect_str=[['I', "am", 'mak', '##ing', 'small', 'mistake', '##s', 'during', 'work', '##ing', 'hour', '##s']],
  64. expected_offsets_start=[[0, 2, 5, 8, 12, 18, 25, 27, 34, 38, 42, 46]],
  65. expected_offsets_limit=[[1, 4, 8, 11, 17, 25, 26, 33, 38, 41, 46, 47]],
  66. lower_case=False,
  67. vocab_list=vocab_bert
  68. ),
  69. # test emoji tokens
  70. dict(
  71. first=6,
  72. last=7,
  73. expect_str=[
  74. ['😀', '嘿', '嘿', '😃', '哈', '哈', '😄', '大', '笑', '😁', '嘻', '嘻'],
  75. ['繁', '體', '字']],
  76. expected_offsets_start=[[0, 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37], [0, 3, 6]],
  77. expected_offsets_limit=[[4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40], [3, 6, 9]],
  78. normalization_form=text.utils.NormalizeForm.NFKC,
  79. vocab_list=vocab_bert
  80. ),
  81. # test preserved tokens
  82. dict(
  83. first=8,
  84. last=14,
  85. expect_str=[
  86. ['[UNK]', '[CLS]'],
  87. ['[UNK]', '[SEP]'],
  88. ['[UNK]', '[UNK]'],
  89. ['[UNK]', '[PAD]'],
  90. ['[UNK]', '[MASK]'],
  91. ['[unused1]'],
  92. ['[unused10]']
  93. ],
  94. expected_offsets_start=[[0, 7], [0, 7], [0, 7], [0, 7], [0, 7], [0], [0]],
  95. expected_offsets_limit=[[6, 12], [6, 12], [6, 12], [6, 12], [6, 13], [9], [10]],
  96. lower_case=False,
  97. vocab_list=vocab_bert,
  98. preserve_unused_token=True,
  99. ),
  100. dict(
  101. first=8,
  102. last=14,
  103. expect_str=[
  104. ['[UNK]', '[CLS]'],
  105. ['[UNK]', '[SEP]'],
  106. ['[UNK]', '[UNK]'],
  107. ['[UNK]', '[PAD]'],
  108. ['[UNK]', '[MASK]'],
  109. ['[unused1]'],
  110. ['[unused10]']
  111. ],
  112. expected_offsets_start=[[0, 7], [0, 7], [0, 7], [0, 7], [0, 7], [0], [0]],
  113. expected_offsets_limit=[[6, 12], [6, 12], [6, 12], [6, 12], [6, 13], [9], [10]],
  114. lower_case=True,
  115. vocab_list=vocab_bert,
  116. preserve_unused_token=True,
  117. ),
  118. # test special symbol
  119. dict(
  120. first=15,
  121. last=15,
  122. expect_str=[['12', '+', '/', '-', '28', '=', '40', '/', '-', '16']],
  123. expected_offsets_start=[[0, 2, 3, 4, 5, 7, 8, 10, 11, 12]],
  124. expected_offsets_limit=[[2, 3, 4, 5, 7, 8, 10, 11, 12, 14]],
  125. preserve_unused_token=True,
  126. vocab_list=vocab_bert
  127. ),
  128. # test non-default parms
  129. dict(
  130. first=8,
  131. last=8,
  132. expect_str=[['[UNK]', ' ', '[CLS]']],
  133. expected_offsets_start=[[0, 6, 7]],
  134. expected_offsets_limit=[[6, 7, 12]],
  135. lower_case=False,
  136. vocab_list=vocab_bert,
  137. preserve_unused_token=True,
  138. keep_whitespace=True
  139. ),
  140. dict(
  141. first=8,
  142. last=8,
  143. expect_str=[['unused', ' ', '[CLS]']],
  144. expected_offsets_start=[[0, 6, 7]],
  145. expected_offsets_limit=[[6, 7, 12]],
  146. lower_case=False,
  147. vocab_list=vocab_bert,
  148. preserve_unused_token=True,
  149. keep_whitespace=True,
  150. unknown_token=''
  151. ),
  152. dict(
  153. first=8,
  154. last=8,
  155. expect_str=[['unused', ' ', '[', 'CLS', ']']],
  156. expected_offsets_start=[[0, 6, 7, 8, 11]],
  157. expected_offsets_limit=[[6, 7, 8, 11, 12]],
  158. lower_case=False,
  159. vocab_list=vocab_bert,
  160. preserve_unused_token=False,
  161. keep_whitespace=True,
  162. unknown_token=''
  163. ),
  164. ]
  165. def check_bert_tokenizer_default(first, last, expect_str,
  166. expected_offsets_start, expected_offsets_limit,
  167. vocab_list, suffix_indicator='##',
  168. max_bytes_per_token=100, unknown_token='[UNK]',
  169. lower_case=False, keep_whitespace=False,
  170. normalization_form=text.utils.NormalizeForm.NONE,
  171. preserve_unused_token=False):
  172. dataset = ds.TextFileDataset(BERT_TOKENIZER_FILE, shuffle=False)
  173. if first > 1:
  174. dataset = dataset.skip(first - 1)
  175. if last >= first:
  176. dataset = dataset.take(last - first + 1)
  177. vocab = text.Vocab.from_list(vocab_list)
  178. tokenizer_op = text.BertTokenizer(
  179. vocab=vocab, suffix_indicator=suffix_indicator,
  180. max_bytes_per_token=max_bytes_per_token, unknown_token=unknown_token,
  181. lower_case=lower_case, keep_whitespace=keep_whitespace,
  182. normalization_form=normalization_form,
  183. preserve_unused_token=preserve_unused_token)
  184. dataset = dataset.map(operations=tokenizer_op)
  185. count = 0
  186. for i in dataset.create_dict_iterator():
  187. token = text.to_str(i['text'])
  188. logger.info("Out:", token)
  189. logger.info("Exp:", expect_str[count])
  190. np.testing.assert_array_equal(token, expect_str[count])
  191. count = count + 1
  192. def check_bert_tokenizer_with_offsets(first, last, expect_str,
  193. expected_offsets_start, expected_offsets_limit,
  194. vocab_list, suffix_indicator='##',
  195. max_bytes_per_token=100, unknown_token='[UNK]',
  196. lower_case=False, keep_whitespace=False,
  197. normalization_form=text.utils.NormalizeForm.NONE,
  198. preserve_unused_token=False):
  199. dataset = ds.TextFileDataset(BERT_TOKENIZER_FILE, shuffle=False)
  200. if first > 1:
  201. dataset = dataset.skip(first - 1)
  202. if last >= first:
  203. dataset = dataset.take(last - first + 1)
  204. vocab = text.Vocab.from_list(vocab_list)
  205. tokenizer_op = text.BertTokenizer(
  206. vocab=vocab, suffix_indicator=suffix_indicator, max_bytes_per_token=max_bytes_per_token,
  207. unknown_token=unknown_token, lower_case=lower_case, keep_whitespace=keep_whitespace,
  208. normalization_form=normalization_form, preserve_unused_token=preserve_unused_token, with_offsets=True)
  209. dataset = dataset.map(input_columns=['text'], output_columns=['token', 'offsets_start', 'offsets_limit'],
  210. columns_order=['token', 'offsets_start', 'offsets_limit'], operations=tokenizer_op)
  211. count = 0
  212. for i in dataset.create_dict_iterator():
  213. token = text.to_str(i['token'])
  214. logger.info("Out:", token)
  215. logger.info("Exp:", expect_str[count])
  216. np.testing.assert_array_equal(token, expect_str[count])
  217. np.testing.assert_array_equal(i['offsets_start'], expected_offsets_start[count])
  218. np.testing.assert_array_equal(i['offsets_limit'], expected_offsets_limit[count])
  219. count = count + 1
  220. def test_bert_tokenizer_default():
  221. """
  222. Test WordpieceTokenizer when with_offsets=False
  223. """
  224. for paras in test_paras:
  225. check_bert_tokenizer_default(**paras)
  226. def test_bert_tokenizer_with_offsets():
  227. """
  228. Test WordpieceTokenizer when with_offsets=True
  229. """
  230. for paras in test_paras:
  231. check_bert_tokenizer_with_offsets(**paras)
  232. if __name__ == '__main__':
  233. test_bert_tokenizer_default()
  234. test_bert_tokenizer_with_offsets()