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

path_context_reader.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
  1. import tensorflow as tf
  2. from typing import Dict, Tuple, NamedTuple, Union, Optional, Iterable
  3. from config import Config
  4. from vocabularies import Code2VecVocabs
  5. import abc
  6. from functools import reduce
  7. from enum import Enum
  8. class EstimatorAction(Enum):
  9. Train = 'train'
  10. Evaluate = 'evaluate'
  11. Predict = 'predict'
  12. @property
  13. def is_train(self):
  14. return self is EstimatorAction.Train
  15. @property
  16. def is_evaluate(self):
  17. return self is EstimatorAction.Evaluate
  18. @property
  19. def is_predict(self):
  20. return self is EstimatorAction.Predict
  21. @property
  22. def is_evaluate_or_predict(self):
  23. return self.is_evaluate or self.is_predict
  24. class ReaderInputTensors(NamedTuple):
  25. """
  26. Used mostly for convenient-and-clear access to input parts (by their names).
  27. """
  28. path_source_token_indices: tf.Tensor
  29. path_indices: tf.Tensor
  30. path_target_token_indices: tf.Tensor
  31. context_valid_mask: tf.Tensor
  32. target_index: Optional[tf.Tensor] = None
  33. target_string: Optional[tf.Tensor] = None
  34. path_source_token_strings: Optional[tf.Tensor] = None
  35. path_strings: Optional[tf.Tensor] = None
  36. path_target_token_strings: Optional[tf.Tensor] = None
  37. class ModelInputTensorsFormer(abc.ABC):
  38. """
  39. Should be inherited by the model implementation.
  40. An instance of the inherited class is passed by the model to the reader in order to help the reader
  41. to construct the input in the form that the model expects to receive it.
  42. This class also enables conveniently & clearly access input parts by their field names.
  43. eg: 'tensors.path_indices' instead if 'tensors[1]'.
  44. This allows the input tensors to be passed as pure tuples along the computation graph, while the
  45. python functions that construct the graph can easily (and clearly) access tensors.
  46. """
  47. @abc.abstractmethod
  48. def to_model_input_form(self, input_tensors: ReaderInputTensors):
  49. ...
  50. @abc.abstractmethod
  51. def from_model_input_form(self, input_row) -> ReaderInputTensors:
  52. ...
  53. class PathContextReader:
  54. def __init__(self,
  55. vocabs: Code2VecVocabs,
  56. config: Config,
  57. model_input_tensors_former: ModelInputTensorsFormer,
  58. estimator_action: EstimatorAction,
  59. repeat_endlessly: bool = False):
  60. self.vocabs = vocabs
  61. self.config = config
  62. self.model_input_tensors_former = model_input_tensors_former
  63. self.estimator_action = estimator_action
  64. self.repeat_endlessly = repeat_endlessly
  65. self.CONTEXT_PADDING = ','.join([self.vocabs.token_vocab.special_words.PAD,
  66. self.vocabs.path_vocab.special_words.PAD,
  67. self.vocabs.token_vocab.special_words.PAD])
  68. self.csv_record_defaults = [[self.vocabs.target_vocab.special_words.OOV]] + \
  69. ([[self.CONTEXT_PADDING]] * self.config.MAX_CONTEXTS)
  70. # initialize the needed lookup tables (if not already initialized).
  71. self.create_needed_vocabs_lookup_tables(self.vocabs)
  72. self._dataset: Optional[tf.data.Dataset] = None
  73. @classmethod
  74. def create_needed_vocabs_lookup_tables(cls, vocabs: Code2VecVocabs):
  75. vocabs.token_vocab.get_word_to_index_lookup_table()
  76. vocabs.path_vocab.get_word_to_index_lookup_table()
  77. vocabs.target_vocab.get_word_to_index_lookup_table()
  78. @tf.function
  79. def process_input_row(self, row_placeholder):
  80. parts = tf.io.decode_csv(
  81. row_placeholder, record_defaults=self.csv_record_defaults, field_delim=' ', use_quote_delim=False)
  82. # Note: we DON'T apply the filter `_filter_input_rows()` here.
  83. tensors = self._map_raw_dataset_row_to_input_tensors(*parts)
  84. # make it batched (first batch axis is going to have dimension 1)
  85. tensors_expanded = ReaderInputTensors(
  86. **{name: None if tensor is None else tf.expand_dims(tensor, axis=0)
  87. for name, tensor in tensors._asdict().items()})
  88. return self.model_input_tensors_former.to_model_input_form(tensors_expanded)
  89. def process_and_iterate_input_from_data_lines(self, input_data_lines: Iterable) -> Iterable:
  90. for data_row in input_data_lines:
  91. processed_row = self.process_input_row(data_row)
  92. yield processed_row
  93. def get_dataset(self, input_data_rows: Optional = None) -> tf.data.Dataset:
  94. if self._dataset is None:
  95. self._dataset = self._create_dataset_pipeline(input_data_rows)
  96. return self._dataset
  97. def _create_dataset_pipeline(self, input_data_rows: Optional = None) -> tf.data.Dataset:
  98. if input_data_rows is None:
  99. assert not self.estimator_action.is_predict
  100. dataset = tf.data.experimental.CsvDataset(
  101. self.config.data_path(is_evaluating=self.estimator_action.is_evaluate),
  102. record_defaults=self.csv_record_defaults, field_delim=' ', use_quote_delim=False,
  103. buffer_size=self.config.CSV_BUFFER_SIZE)
  104. else:
  105. dataset = tf.data.Dataset.from_tensor_slices(input_data_rows)
  106. dataset = dataset.map(
  107. lambda input_line: tf.io.decode_csv(
  108. tf.reshape(tf.cast(input_line, tf.string), ()),
  109. record_defaults=self.csv_record_defaults,
  110. field_delim=' ', use_quote_delim=False))
  111. if self.repeat_endlessly:
  112. dataset = dataset.repeat()
  113. if self.estimator_action.is_train:
  114. if not self.repeat_endlessly and self.config.NUM_TRAIN_EPOCHS > 1:
  115. dataset = dataset.repeat(self.config.NUM_TRAIN_EPOCHS)
  116. dataset = dataset.shuffle(self.config.SHUFFLE_BUFFER_SIZE, reshuffle_each_iteration=True)
  117. dataset = dataset.map(self._map_raw_dataset_row_to_expected_model_input_form,
  118. num_parallel_calls=self.config.READER_NUM_PARALLEL_BATCHES)
  119. batch_size = self.config.batch_size(is_evaluating=self.estimator_action.is_evaluate)
  120. if self.estimator_action.is_predict:
  121. dataset = dataset.batch(1)
  122. else:
  123. dataset = dataset.filter(self._filter_input_rows)
  124. dataset = dataset.batch(batch_size)
  125. dataset = dataset.prefetch(buffer_size=40) # original: tf.contrib.data.AUTOTUNE) -- got OOM err; 10 seems promising.
  126. return dataset
  127. def _filter_input_rows(self, *row_parts) -> tf.bool:
  128. row_parts = self.model_input_tensors_former.from_model_input_form(row_parts)
  129. #assert all(tensor.shape == (self.config.MAX_CONTEXTS,) for tensor in
  130. # {row_parts.path_source_token_indices, row_parts.path_indices,
  131. # row_parts.path_target_token_indices, row_parts.context_valid_mask})
  132. # FIXME: Does "valid" here mean just "no padding" or "neither padding nor OOV"? I assumed just "no padding".
  133. any_word_valid_mask_per_context_part = [
  134. tf.not_equal(tf.reduce_max(row_parts.path_source_token_indices, axis=0),
  135. self.vocabs.token_vocab.word_to_index[self.vocabs.token_vocab.special_words.PAD]),
  136. tf.not_equal(tf.reduce_max(row_parts.path_target_token_indices, axis=0),
  137. self.vocabs.token_vocab.word_to_index[self.vocabs.token_vocab.special_words.PAD]),
  138. tf.not_equal(tf.reduce_max(row_parts.path_indices, axis=0),
  139. self.vocabs.path_vocab.word_to_index[self.vocabs.path_vocab.special_words.PAD])]
  140. any_contexts_is_valid = reduce(tf.logical_or, any_word_valid_mask_per_context_part) # scalar
  141. if self.estimator_action.is_evaluate:
  142. cond = any_contexts_is_valid # scalar
  143. else: # training
  144. word_is_valid = tf.greater(
  145. row_parts.target_index, self.vocabs.target_vocab.word_to_index[self.vocabs.target_vocab.special_words.OOV]) # scalar
  146. cond = tf.logical_and(word_is_valid, any_contexts_is_valid) # scalar
  147. return cond # scalar
  148. def _map_raw_dataset_row_to_expected_model_input_form(self, *row_parts) -> \
  149. Tuple[Union[tf.Tensor, Tuple[tf.Tensor, ...], Dict[str, tf.Tensor]], ...]:
  150. tensors = self._map_raw_dataset_row_to_input_tensors(*row_parts)
  151. return self.model_input_tensors_former.to_model_input_form(tensors)
  152. def _map_raw_dataset_row_to_input_tensors(self, *row_parts) -> ReaderInputTensors:
  153. row_parts = list(row_parts)
  154. target_str = row_parts[0]
  155. target_index = self.vocabs.target_vocab.lookup_index(target_str)
  156. contexts_str = tf.stack(row_parts[1:(self.config.MAX_CONTEXTS + 1)], axis=0)
  157. split_contexts = tf.compat.v1.string_split(contexts_str, sep=',', skip_empty=False)
  158. # dense_split_contexts = tf.sparse_tensor_to_dense(split_contexts, default_value=self.vocabs.token_vocab.special_words.PAD)
  159. sparse_split_contexts = tf.sparse.SparseTensor(
  160. indices=split_contexts.indices, values=split_contexts.values, dense_shape=[self.config.MAX_CONTEXTS, 3])
  161. dense_split_contexts = tf.reshape(
  162. tf.sparse.to_dense(sp_input=sparse_split_contexts, default_value=self.vocabs.token_vocab.special_words.PAD),
  163. shape=[self.config.MAX_CONTEXTS, 3]) # (max_contexts, 3)
  164. path_source_token_strings = tf.squeeze(
  165. tf.slice(dense_split_contexts, begin=[0, 0], size=[self.config.MAX_CONTEXTS, 1]), axis=1) # (max_contexts,)
  166. path_strings = tf.squeeze(
  167. tf.slice(dense_split_contexts, begin=[0, 1], size=[self.config.MAX_CONTEXTS, 1]), axis=1) # (max_contexts,)
  168. path_target_token_strings = tf.squeeze(
  169. tf.slice(dense_split_contexts, begin=[0, 2], size=[self.config.MAX_CONTEXTS, 1]), axis=1) # (max_contexts,)
  170. path_source_token_indices = self.vocabs.token_vocab.lookup_index(path_source_token_strings) # (max_contexts, )
  171. path_indices = self.vocabs.path_vocab.lookup_index(path_strings) # (max_contexts, )
  172. path_target_token_indices = self.vocabs.token_vocab.lookup_index(path_target_token_strings) # (max_contexts, )
  173. # FIXME: Does "valid" here mean just "no padding" or "neither padding nor OOV"? I assumed just "no padding".
  174. valid_word_mask_per_context_part = [
  175. tf.not_equal(path_source_token_indices, self.vocabs.token_vocab.word_to_index[self.vocabs.token_vocab.special_words.PAD]),
  176. tf.not_equal(path_target_token_indices, self.vocabs.token_vocab.word_to_index[self.vocabs.token_vocab.special_words.PAD]),
  177. tf.not_equal(path_indices, self.vocabs.path_vocab.word_to_index[self.vocabs.path_vocab.special_words.PAD])] # [(max_contexts, )]
  178. context_valid_mask = tf.cast(reduce(tf.logical_or, valid_word_mask_per_context_part), dtype=tf.float32) # (max_contexts, )
  179. #assert all(tensor.shape == (self.config.MAX_CONTEXTS,) for tensor in {path_source_token_indices, path_indices, path_target_token_indices, context_valid_mask})
  180. return ReaderInputTensors(
  181. path_source_token_indices=path_source_token_indices,
  182. path_indices=path_indices,
  183. path_target_token_indices=path_target_token_indices,
  184. context_valid_mask=context_valid_mask,
  185. target_index=target_index,
  186. target_string=target_str,
  187. path_source_token_strings=path_source_token_strings,
  188. path_strings=path_strings,
  189. path_target_token_strings=path_target_token_strings
  190. )
Tip!

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

Comments

Loading...