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

dictionary.py 6.0 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
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the LICENSE file in
  5. # the root directory of this source tree. An additional grant of patent rights
  6. # can be found in the PATENTS file in the same directory.
  7. from collections import Counter
  8. import os
  9. import torch
  10. class Dictionary(object):
  11. """A mapping from symbols to consecutive integers"""
  12. def __init__(self, pad='<pad>', eos='</s>', unk='<unk>'):
  13. self.unk_word, self.pad_word, self.eos_word = unk, pad, eos
  14. self.symbols = []
  15. self.count = []
  16. self.indices = {}
  17. # dictionary indexing starts at 1 for consistency with Lua
  18. self.add_symbol('<Lua heritage>')
  19. self.pad_index = self.add_symbol(pad)
  20. self.eos_index = self.add_symbol(eos)
  21. self.unk_index = self.add_symbol(unk)
  22. self.nspecial = len(self.symbols)
  23. def __eq__(self, other):
  24. return self.indices == other.indices
  25. def __getitem__(self, idx):
  26. if idx < len(self.symbols):
  27. return self.symbols[idx]
  28. return self.unk_word
  29. def __len__(self):
  30. """Returns the number of symbols in the dictionary"""
  31. return len(self.symbols)
  32. def index(self, sym):
  33. """Returns the index of the specified symbol"""
  34. if sym in self.indices:
  35. return self.indices[sym]
  36. return self.unk_index
  37. def string(self, tensor, bpe_symbol=None, escape_unk=False):
  38. """Helper for converting a tensor of token indices to a string.
  39. Can optionally remove BPE symbols or escape <unk> words.
  40. """
  41. if torch.is_tensor(tensor) and tensor.dim() == 2:
  42. return '\n'.join(self.string(t) for t in tensor)
  43. def token_string(i):
  44. if i == self.unk():
  45. return self.unk_string(escape_unk)
  46. else:
  47. return self[i]
  48. sent = ' '.join(token_string(i) for i in tensor if i != self.eos())
  49. if bpe_symbol is not None:
  50. sent = (sent + ' ').replace(bpe_symbol, '').rstrip()
  51. return sent
  52. def unk_string(self, escape=False):
  53. """Return unknown string, optionally escaped as: <<unk>>"""
  54. if escape:
  55. return '<{}>'.format(self.unk_word)
  56. else:
  57. return self.unk_word
  58. def add_symbol(self, word, n=1):
  59. """Adds a word to the dictionary"""
  60. if word in self.indices:
  61. idx = self.indices[word]
  62. self.count[idx] = self.count[idx] + n
  63. return idx
  64. else:
  65. idx = len(self.symbols)
  66. self.indices[word] = idx
  67. self.symbols.append(word)
  68. self.count.append(n)
  69. return idx
  70. def finalize(self, threshold=1, nwords=-1, padding_factor=8):
  71. """Sort symbols by frequency in descending order, ignoring special ones.
  72. Args:
  73. - threshold defines the minimum word count
  74. - nwords defines the total number of words in the final dictionary,
  75. including special symbols
  76. - padding_factor can be used to pad the dictionary size to be a
  77. multiple of 8, which is important on some hardware (e.g., Nvidia
  78. Tensor Cores).
  79. """
  80. if nwords == -1:
  81. nwords = len(self)
  82. new_symbols = self.symbols[:self.nspecial]
  83. new_count = self.count[:self.nspecial]
  84. c = Counter(dict(zip(self.symbols[self.nspecial:], self.count[self.nspecial:])))
  85. for symbol, count in c.most_common(nwords - self.nspecial):
  86. if count >= threshold:
  87. new_symbols.append(symbol)
  88. new_count.append(count)
  89. else:
  90. break
  91. threshold_nwords = len(new_symbols)
  92. if padding_factor > 1:
  93. i = 0
  94. while threshold_nwords % padding_factor != 0:
  95. new_symbols.append('madeupword{:04d}'.format(i))
  96. i += 1
  97. threshold_nwords += 1
  98. assert min(new_count[self.nspecial:]) >= threshold
  99. assert len(new_symbols) % padding_factor == 0
  100. self.count = tuple(new_count)
  101. self.symbols = tuple(new_symbols)
  102. def pad(self):
  103. """Helper to get index of pad symbol"""
  104. return self.pad_index
  105. def eos(self):
  106. """Helper to get index of end-of-sentence symbol"""
  107. return self.eos_index
  108. def unk(self):
  109. """Helper to get index of unk symbol"""
  110. return self.unk_index
  111. @classmethod
  112. def load(cls, f, ignore_utf_errors=False):
  113. """Loads the dictionary from a text file with the format:
  114. ```
  115. <symbol0> <count0>
  116. <symbol1> <count1>
  117. ...
  118. ```
  119. """
  120. if isinstance(f, str):
  121. try:
  122. if not ignore_utf_errors:
  123. with open(f, 'r', encoding='utf-8') as fd:
  124. return cls.load(fd)
  125. else:
  126. with open(f, 'r', encoding='utf-8', errors='ignore') as fd:
  127. return cls.load(fd)
  128. except FileNotFoundError as fnfe:
  129. raise fnfe
  130. except Exception:
  131. raise Exception("Incorrect encoding detected in {}, please "
  132. "rebuild the dataset".format(f))
  133. d = cls()
  134. for line in f.readlines():
  135. idx = line.rfind(' ')
  136. word = line[:idx]
  137. count = int(line[idx+1:])
  138. d.indices[word] = len(d.symbols)
  139. d.symbols.append(word)
  140. d.count.append(count)
  141. return d
  142. def save(self, f, threshold=3, nwords=-1):
  143. """Stores dictionary into a text file"""
  144. if isinstance(f, str):
  145. os.makedirs(os.path.dirname(f), exist_ok=True)
  146. with open(f, 'w', encoding='utf-8') as fd:
  147. return self.save(fd, threshold, nwords)
  148. for symbol, count in zip(self.symbols[self.nspecial:], self.count[self.nspecial:]):
  149. print('{} {}'.format(symbol, count), file=f)
Tip!

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

Comments

Loading...