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 7.8 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
  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. if bpe_symbol == 'sentencepiece':
  49. sent = ''.join(token_string(i) for i in tensor if i != self.eos())
  50. sent = sent.replace('\u2581', ' ').strip()
  51. else:
  52. sent = ' '.join(token_string(i) for i in tensor if i != self.eos())
  53. if bpe_symbol is not None and bpe_symbol != 'sentencepiece':
  54. sent = (sent + ' ').replace(bpe_symbol, '').rstrip()
  55. return sent
  56. def unk_string(self, escape=False):
  57. """Return unknown string, optionally escaped as: <<unk>>"""
  58. if escape:
  59. return '<{}>'.format(self.unk_word)
  60. else:
  61. return self.unk_word
  62. def add_symbol(self, word, n=1):
  63. """Adds a word to the dictionary"""
  64. if word in self.indices:
  65. idx = self.indices[word]
  66. self.count[idx] = self.count[idx] + n
  67. return idx
  68. else:
  69. idx = len(self.symbols)
  70. self.indices[word] = idx
  71. self.symbols.append(word)
  72. self.count.append(n)
  73. return idx
  74. def update(self, new_dict):
  75. """Updates counts from new dictionary."""
  76. for word in new_dict.symbols:
  77. idx2 = new_dict.indices[word]
  78. if word in self.indices:
  79. idx = self.indices[word]
  80. self.count[idx] = self.count[idx] + new_dict.count[idx2]
  81. else:
  82. idx = len(self.symbols)
  83. self.indices[word] = idx
  84. self.symbols.append(word)
  85. self.count.append(new_dict.count[idx2])
  86. def finalize(self, threshold=-1, nwords=-1, padding_factor=8):
  87. """Sort symbols by frequency in descending order, ignoring special ones.
  88. Args:
  89. - threshold defines the minimum word count
  90. - nwords defines the total number of words in the final dictionary,
  91. including special symbols
  92. - padding_factor can be used to pad the dictionary size to be a
  93. multiple of 8, which is important on some hardware (e.g., Nvidia
  94. Tensor Cores).
  95. """
  96. if nwords <= 0:
  97. nwords = len(self)
  98. new_indices = dict(zip(self.symbols[:self.nspecial], range(self.nspecial)))
  99. new_symbols = self.symbols[:self.nspecial]
  100. new_count = self.count[:self.nspecial]
  101. c = Counter(dict(zip(self.symbols[self.nspecial:], self.count[self.nspecial:])))
  102. for symbol, count in c.most_common(nwords - self.nspecial):
  103. if count >= threshold:
  104. new_indices[symbol] = len(new_symbols)
  105. new_symbols.append(symbol)
  106. new_count.append(count)
  107. else:
  108. break
  109. threshold_nwords = len(new_symbols)
  110. if padding_factor > 1:
  111. i = 0
  112. while threshold_nwords % padding_factor != 0:
  113. symbol = 'madeupword{:04d}'.format(i)
  114. new_indices[symbol] = len(new_symbols)
  115. new_symbols.append(symbol)
  116. new_count.append(0)
  117. i += 1
  118. threshold_nwords += 1
  119. assert len(new_symbols) % padding_factor == 0
  120. assert len(new_symbols) == len(new_indices)
  121. self.count = list(new_count)
  122. self.symbols = list(new_symbols)
  123. self.indices = new_indices
  124. def pad(self):
  125. """Helper to get index of pad symbol"""
  126. return self.pad_index
  127. def eos(self):
  128. """Helper to get index of end-of-sentence symbol"""
  129. return self.eos_index
  130. def unk(self):
  131. """Helper to get index of unk symbol"""
  132. return self.unk_index
  133. @classmethod
  134. def load(cls, f, ignore_utf_errors=False):
  135. """Loads the dictionary from a text file with the format:
  136. ```
  137. <symbol0> <count0>
  138. <symbol1> <count1>
  139. ...
  140. ```
  141. """
  142. if isinstance(f, str):
  143. try:
  144. if not ignore_utf_errors:
  145. with open(f, 'r', encoding='utf-8') as fd:
  146. return cls.load(fd)
  147. else:
  148. with open(f, 'r', encoding='utf-8', errors='ignore') as fd:
  149. return cls.load(fd)
  150. except FileNotFoundError as fnfe:
  151. raise fnfe
  152. except UnicodeError:
  153. raise Exception("Incorrect encoding detected in {}, please "
  154. "rebuild the dataset".format(f))
  155. d = cls()
  156. for line in f.readlines():
  157. idx = line.rfind(' ')
  158. if idx == -1:
  159. raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'")
  160. word = line[:idx]
  161. count = int(line[idx+1:])
  162. d.indices[word] = len(d.symbols)
  163. d.symbols.append(word)
  164. d.count.append(count)
  165. return d
  166. def save(self, f):
  167. """Stores dictionary into a text file"""
  168. if isinstance(f, str):
  169. os.makedirs(os.path.dirname(f), exist_ok=True)
  170. with open(f, 'w', encoding='utf-8') as fd:
  171. return self.save(fd)
  172. for symbol, count in zip(self.symbols[self.nspecial:], self.count[self.nspecial:]):
  173. print('{} {}'.format(symbol, count), file=f)
  174. def dummy_sentence(self, length):
  175. t = torch.Tensor(length).uniform_(self.nspecial + 1, len(self)).long()
  176. t[-1] = self.eos()
  177. return t
  178. class TruncatedDictionary(object):
  179. def __init__(self, wrapped_dict, length):
  180. self.__class__ = type(
  181. wrapped_dict.__class__.__name__,
  182. (self.__class__, wrapped_dict.__class__),
  183. {}
  184. )
  185. self.__dict__ = wrapped_dict.__dict__
  186. self.wrapped_dict = wrapped_dict
  187. self.length = min(len(self.wrapped_dict), length)
  188. def __len__(self):
  189. return self.length
  190. def __getitem__(self, i):
  191. if i < self.length:
  192. return self.wrapped_dict[i]
  193. return self.wrapped_dict.unk()
Tip!

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

Comments

Loading...