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

vocabularies.py 11 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
  1. from itertools import chain
  2. from typing import Optional, Dict, Iterable, Set, NamedTuple
  3. import pickle
  4. import os
  5. from enum import Enum
  6. from config import Config
  7. import tensorflow as tf
  8. from argparse import Namespace
  9. from common import common
  10. class VocabType(Enum):
  11. Token = 1
  12. Target = 2
  13. Path = 3
  14. SpecialVocabWordsType = Namespace
  15. _SpecialVocabWords_OnlyOov = Namespace(
  16. OOV='<OOV>'
  17. )
  18. _SpecialVocabWords_SeparateOovPad = Namespace(
  19. PAD='<PAD>',
  20. OOV='<OOV>'
  21. )
  22. _SpecialVocabWords_JoinedOovPad = Namespace(
  23. PAD_OR_OOV='<PAD_OR_OOV>',
  24. PAD='<PAD_OR_OOV>',
  25. OOV='<PAD_OR_OOV>'
  26. )
  27. class Vocab:
  28. def __init__(self, vocab_type: VocabType, words: Iterable[str],
  29. special_words: Optional[SpecialVocabWordsType] = None):
  30. if special_words is None:
  31. special_words = Namespace()
  32. self.vocab_type = vocab_type
  33. self.word_to_index: Dict[str, int] = {}
  34. self.index_to_word: Dict[int, str] = {}
  35. self._word_to_index_lookup_table = None
  36. self._index_to_word_lookup_table = None
  37. self.special_words: SpecialVocabWordsType = special_words
  38. for index, word in enumerate(chain(common.get_unique_list(special_words.__dict__.values()), words)):
  39. self.word_to_index[word] = index
  40. self.index_to_word[index] = word
  41. self.size = len(self.word_to_index)
  42. def save_to_file(self, file):
  43. # Notice: From historical reasons, a saved vocab doesn't include special words.
  44. special_words_as_unique_list = common.get_unique_list(self.special_words.__dict__.values())
  45. nr_special_words = len(special_words_as_unique_list)
  46. word_to_index_wo_specials = {word: idx for word, idx in self.word_to_index.items() if idx >= nr_special_words}
  47. index_to_word_wo_specials = {idx: word for idx, word in self.index_to_word.items() if idx >= nr_special_words}
  48. size_wo_specials = self.size - nr_special_words
  49. pickle.dump(word_to_index_wo_specials, file)
  50. pickle.dump(index_to_word_wo_specials, file)
  51. pickle.dump(size_wo_specials, file)
  52. @classmethod
  53. def load_from_file(cls, vocab_type: VocabType, file, special_words: SpecialVocabWordsType) -> 'Vocab':
  54. special_words_as_unique_list = common.get_unique_list(special_words.__dict__.values())
  55. # Notice: From historical reasons, a saved vocab doesn't include special words,
  56. # so they should be added upon loading.
  57. word_to_index_wo_specials = pickle.load(file)
  58. index_to_word_wo_specials = pickle.load(file)
  59. size_wo_specials = pickle.load(file)
  60. assert len(index_to_word_wo_specials) == len(word_to_index_wo_specials) == size_wo_specials
  61. min_word_idx_wo_specials = min(index_to_word_wo_specials.keys())
  62. if min_word_idx_wo_specials != len(special_words_as_unique_list):
  63. raise ValueError(
  64. "Error while attempting to load vocabulary `{vocab_type}` from file `{file_path}`. "
  65. "The stored vocabulary has minimum word index {min_word_idx}, "
  66. "while expecting minimum word index to be {nr_special_words} "
  67. "because having to use {nr_special_words} special words, which are: {special_words}. "
  68. "Please check the parameter `config.SEPARATE_OOV_AND_PAD`.".format(
  69. vocab_type=vocab_type, file_path=file.name, min_word_idx=min_word_idx_wo_specials,
  70. nr_special_words=len(special_words_as_unique_list), special_words=special_words))
  71. vocab = cls(vocab_type, [], special_words)
  72. vocab.word_to_index = {**word_to_index_wo_specials,
  73. **{word: idx for idx, word in enumerate(special_words_as_unique_list)}}
  74. vocab.index_to_word = {**index_to_word_wo_specials,
  75. **{idx: word for idx, word in enumerate(special_words_as_unique_list)}}
  76. vocab.size = size_wo_specials + len(special_words_as_unique_list)
  77. return vocab
  78. @classmethod
  79. def create_from_freq_dict(cls, vocab_type: VocabType, word_to_count: Dict[str, int], max_size: int,
  80. special_words: Optional[SpecialVocabWordsType] = None):
  81. if special_words is None:
  82. special_words = Namespace()
  83. words_sorted_by_counts = sorted(word_to_count, key=word_to_count.get, reverse=True)
  84. words_sorted_by_counts_and_limited = words_sorted_by_counts[:max_size]
  85. return cls(vocab_type, words_sorted_by_counts_and_limited, special_words)
  86. @staticmethod
  87. def _create_word_to_index_lookup_table(word_to_index: Dict[str, int], default_value: int):
  88. return tf.lookup.StaticHashTable(
  89. tf.lookup.KeyValueTensorInitializer(
  90. list(word_to_index.keys()), list(word_to_index.values()), key_dtype=tf.string, value_dtype=tf.int32),
  91. default_value=tf.constant(default_value, dtype=tf.int32))
  92. @staticmethod
  93. def _create_index_to_word_lookup_table(index_to_word: Dict[int, str], default_value: str) \
  94. -> tf.lookup.StaticHashTable:
  95. return tf.lookup.StaticHashTable(
  96. tf.lookup.KeyValueTensorInitializer(
  97. list(index_to_word.keys()), list(index_to_word.values()), key_dtype=tf.int32, value_dtype=tf.string),
  98. default_value=tf.constant(default_value, dtype=tf.string))
  99. def get_word_to_index_lookup_table(self) -> tf.lookup.StaticHashTable:
  100. if self._word_to_index_lookup_table is None:
  101. self._word_to_index_lookup_table = self._create_word_to_index_lookup_table(
  102. self.word_to_index, default_value=self.word_to_index[self.special_words.OOV])
  103. return self._word_to_index_lookup_table
  104. def get_index_to_word_lookup_table(self) -> tf.lookup.StaticHashTable:
  105. if self._index_to_word_lookup_table is None:
  106. self._index_to_word_lookup_table = self._create_index_to_word_lookup_table(
  107. self.index_to_word, default_value=self.special_words.OOV)
  108. return self._index_to_word_lookup_table
  109. def lookup_index(self, word: tf.Tensor) -> tf.Tensor:
  110. return self.get_word_to_index_lookup_table().lookup(word)
  111. def lookup_word(self, index: tf.Tensor) -> tf.Tensor:
  112. return self.get_index_to_word_lookup_table().lookup(index)
  113. WordFreqDictType = Dict[str, int]
  114. class Code2VecWordFreqDicts(NamedTuple):
  115. token_to_count: WordFreqDictType
  116. path_to_count: WordFreqDictType
  117. target_to_count: WordFreqDictType
  118. class Code2VecVocabs:
  119. def __init__(self, config: Config):
  120. self.config = config
  121. self.token_vocab: Optional[Vocab] = None
  122. self.path_vocab: Optional[Vocab] = None
  123. self.target_vocab: Optional[Vocab] = None
  124. # Used to avoid re-saving a non-modified vocabulary to a path it is already saved in.
  125. self._already_saved_in_paths: Set[str] = set()
  126. self._load_or_create()
  127. def _load_or_create(self):
  128. assert self.config.is_training or self.config.is_loading
  129. if self.config.is_loading:
  130. vocabularies_load_path = self.config.get_vocabularies_path_from_model_path(self.config.MODEL_LOAD_PATH)
  131. if not os.path.isfile(vocabularies_load_path):
  132. raise ValueError(
  133. "Model dictionaries file is not found in model load dir. "
  134. "Expecting file `{vocabularies_load_path}`.".format(vocabularies_load_path=vocabularies_load_path))
  135. self._load_from_path(vocabularies_load_path)
  136. else:
  137. self._create_from_word_freq_dict()
  138. def _load_from_path(self, vocabularies_load_path: str):
  139. assert os.path.exists(vocabularies_load_path)
  140. self.config.log('Loading model vocabularies from: `%s` ... ' % vocabularies_load_path)
  141. with open(vocabularies_load_path, 'rb') as file:
  142. self.token_vocab = Vocab.load_from_file(
  143. VocabType.Token, file, self._get_special_words_by_vocab_type(VocabType.Token))
  144. self.target_vocab = Vocab.load_from_file(
  145. VocabType.Target, file, self._get_special_words_by_vocab_type(VocabType.Target))
  146. self.path_vocab = Vocab.load_from_file(
  147. VocabType.Path, file, self._get_special_words_by_vocab_type(VocabType.Path))
  148. self.config.log('Done loading model vocabularies.')
  149. self._already_saved_in_paths.add(vocabularies_load_path)
  150. def _create_from_word_freq_dict(self):
  151. word_freq_dict = self._load_word_freq_dict()
  152. self.config.log('Word frequencies dictionaries loaded. Now creating vocabularies.')
  153. self.token_vocab = Vocab.create_from_freq_dict(
  154. VocabType.Token, word_freq_dict.token_to_count, self.config.MAX_TOKEN_VOCAB_SIZE,
  155. special_words=self._get_special_words_by_vocab_type(VocabType.Token))
  156. self.config.log('Created token vocab. size: %d' % self.token_vocab.size)
  157. self.path_vocab = Vocab.create_from_freq_dict(
  158. VocabType.Path, word_freq_dict.path_to_count, self.config.MAX_PATH_VOCAB_SIZE,
  159. special_words=self._get_special_words_by_vocab_type(VocabType.Path))
  160. self.config.log('Created path vocab. size: %d' % self.path_vocab.size)
  161. self.target_vocab = Vocab.create_from_freq_dict(
  162. VocabType.Target, word_freq_dict.target_to_count, self.config.MAX_TARGET_VOCAB_SIZE,
  163. special_words=self._get_special_words_by_vocab_type(VocabType.Target))
  164. self.config.log('Created target vocab. size: %d' % self.target_vocab.size)
  165. def _get_special_words_by_vocab_type(self, vocab_type: VocabType) -> SpecialVocabWordsType:
  166. if not self.config.SEPARATE_OOV_AND_PAD:
  167. return _SpecialVocabWords_JoinedOovPad
  168. if vocab_type == VocabType.Target:
  169. return _SpecialVocabWords_OnlyOov
  170. return _SpecialVocabWords_SeparateOovPad
  171. def save(self, vocabularies_save_path: str):
  172. if vocabularies_save_path in self._already_saved_in_paths:
  173. return
  174. with open(vocabularies_save_path, 'wb') as file:
  175. self.token_vocab.save_to_file(file)
  176. self.target_vocab.save_to_file(file)
  177. self.path_vocab.save_to_file(file)
  178. self._already_saved_in_paths.add(vocabularies_save_path)
  179. def _load_word_freq_dict(self) -> Code2VecWordFreqDicts:
  180. assert self.config.is_training
  181. self.config.log('Loading word frequencies dictionaries from: %s ... ' % self.config.word_freq_dict_path)
  182. with open(self.config.word_freq_dict_path, 'rb') as file:
  183. token_to_count = pickle.load(file)
  184. path_to_count = pickle.load(file)
  185. target_to_count = pickle.load(file)
  186. self.config.log('Done loading word frequencies dictionaries.')
  187. # assert all(isinstance(item, WordFreqDictType) for item in {token_to_count, path_to_count, target_to_count})
  188. return Code2VecWordFreqDicts(
  189. token_to_count=token_to_count, path_to_count=path_to_count, target_to_count=target_to_count)
  190. def get(self, vocab_type: VocabType) -> Vocab:
  191. if not isinstance(vocab_type, VocabType):
  192. raise ValueError('`vocab_type` should be `VocabType.Token`, `VocabType.Target` or `VocabType.Path`.')
  193. if vocab_type == VocabType.Token:
  194. return self.token_vocab
  195. if vocab_type == VocabType.Target:
  196. return self.target_vocab
  197. if vocab_type == VocabType.Path:
  198. return self.path_vocab
Tip!

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

Comments

Loading...