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

rnn_train.py 10 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
  1. import argparse
  2. from collections import defaultdict
  3. import os
  4. import pickle
  5. import shutil
  6. import optuna
  7. import pandas as pd
  8. from sklearn.model_selection import train_test_split
  9. import torch
  10. import torch.nn as nn
  11. import torch.nn.functional as F
  12. from transformers import AutoTokenizer, AutoModel
  13. from common.nn_tools import *
  14. os.environ["CUDA_VISIBLE_DEVICES"] = "3"
  15. parser = argparse.ArgumentParser()
  16. parser.add_argument("GRAPH_VER", help="version of the graph you want regex to label your CSV with", type=str)
  17. parser.add_argument("DATASET_PATH", help="path to your input CSV", type=str)
  18. args = parser.parse_args()
  19. GRAPH_VER = args.GRAPH_VER
  20. DATASET_PATH = args.DATASET_PATH
  21. MODEL_DIR = "../models/rnn_codebert_graph_v{}.pt".format(GRAPH_VER)
  22. CHECKPOINT_PATH_TEMPLATE = "../checkpoints/rnn_codebert_trial{}.pt"
  23. LEARNING_HISTORY_PATH_TEMPLATE = "../checkpoints/rnn_codebert_history_trial{}.pickle"
  24. DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  25. EMBEDDING_SIZE = 768
  26. MAX_SEQUENCE_LENGTH = 512 # this is required by transformers for some reason
  27. RANDOM_SEED = 42
  28. N_EPOCHS = 25
  29. N_TRIALS = 15
  30. torch.manual_seed(RANDOM_SEED)
  31. tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
  32. codebert_model = AutoModel.from_pretrained("microsoft/codebert-base").to(DEVICE)
  33. EXPERIMENT_DATA_PATH = ".."
  34. CODE_COLUMN = "code_block"
  35. TARGET_COLUMN = "graph_vertex_id"
  36. SEARCH_SPACE = {
  37. "rnn_size": (64, 256),
  38. "n_rnn_layers": (1, 4),
  39. "lin_size": (32, 266),
  40. "n_conv_layers": (1, 5),
  41. "n_features": (32, 256),
  42. }
  43. class CodeblocksDataset(torch.utils.data.Dataset):
  44. def __init__(self, data):
  45. super(CodeblocksDataset, self).__init__()
  46. self.data = data
  47. def __len__(self):
  48. return self.data.shape[0]
  49. def __getitem__(self, idx):
  50. return {
  51. "code": self.data.iloc[idx][CODE_COLUMN],
  52. "label": self.data.iloc[idx][TARGET_COLUMN]
  53. }
  54. class CNNLayerNorm(nn.Module):
  55. def __init__(self, n_features):
  56. super(CNNLayerNorm, self).__init__()
  57. self.layer_norm = nn.LayerNorm(n_features)
  58. def forward(self, x):
  59. x = x.transpose(1, 2).contiguous() # (batch_size, time, features)
  60. x = self.layer_norm(x)
  61. return x.transpose(1, 2).contiguous() # (batch_size, features, time)
  62. class ResidualCNN(nn.Module):
  63. """
  64. skip connections are supposed to make loss surface flatter
  65. for details see https://arxiv.org/abs/1712.09913
  66. """
  67. def __init__(self, in_channels, out_channels, kernel_size, stride_size, dropout=0.1):
  68. super(ResidualCNN, self).__init__()
  69. self.cnn1 = nn.Conv1d(in_channels, out_channels, kernel_size, stride_size, padding=kernel_size // 2)
  70. self.cnn2 = nn.Conv1d(out_channels, out_channels, kernel_size, stride_size, padding=kernel_size // 2)
  71. self.dropout1 = nn.Dropout(dropout)
  72. self.dropout2 = nn.Dropout(dropout)
  73. self.layer_norm1 = CNNLayerNorm(in_channels)
  74. self.layer_norm2 = CNNLayerNorm(in_channels)
  75. def forward(self, x):
  76. out = F.gelu(self.layer_norm1(x))
  77. out = self.dropout1(out)
  78. out = self.cnn1(out)
  79. out = F.gelu(self.layer_norm2(out))
  80. out = self.dropout2(out)
  81. out = self.cnn2(out)
  82. return out + x
  83. class Classifier(nn.Module):
  84. def __init__(self, rnn_size, n_rnn_layers, lin_size, n_features, n_conv_layers, n_classes):
  85. super(Classifier, self).__init__()
  86. self.cnn = nn.Conv1d(EMBEDDING_SIZE, n_features, kernel_size=3, stride=1, padding=1)
  87. self.rcnn_layers = nn.Sequential(*[
  88. ResidualCNN(n_features, n_features, kernel_size=3, stride_size=1)
  89. for _ in range(n_conv_layers)
  90. ])
  91. self.fc = nn.Sequential(
  92. nn.Linear(n_features, rnn_size),
  93. nn.GELU(),
  94. )
  95. self.birnn = nn.LSTM(
  96. EMBEDDING_SIZE,
  97. rnn_size,
  98. num_layers=n_rnn_layers,
  99. bidirectional=True,
  100. dropout=0.1,
  101. batch_first=True,
  102. )
  103. decoder_layers = []
  104. for i in range(3):
  105. if i == 0:
  106. decoder_layers.append(nn.Linear(2 * rnn_size, lin_size))
  107. else:
  108. decoder_layers.append(nn.Linear(lin_size, lin_size))
  109. decoder_layers.extend([nn.Dropout(0.1, inplace=True), nn.GELU()])
  110. decoder_layers.append(nn.Linear(lin_size, n_classes))
  111. self.decoder = nn.Sequential(*decoder_layers)
  112. size = 0
  113. for p in self.parameters():
  114. size += p.nelement()
  115. print("Total param size: {}".format(size))
  116. def forward(self, x, lengths):
  117. # initial shape (batch_size, time, features)
  118. x = x.transpose(1, 2) # (batch_size, features, time)
  119. out = self.cnn(x)
  120. out = self.rcnn_layers(out)
  121. out = out.transpose(1, 2) # (batch, time, feature)
  122. out = self.fc(out)
  123. packed_sequences = nn.utils.rnn.pack_padded_sequence(out, lengths, batch_first=True)
  124. out, _ = self.birnn(packed_sequences)
  125. out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first=True)
  126. indices = torch.LongTensor((lengths - 1).view(-1, 1).expand(out.size(0), out.size(2)).unsqueeze(1))
  127. indices = indices.to(DEVICE)
  128. out = out.gather(dim=1, index=indices).squeeze(dim=1)
  129. return self.decoder(out)
  130. def prep_data():
  131. df = pd.read_csv(DATASET_PATH, index_col=0)
  132. df.drop_duplicates(inplace=True)
  133. codes, uniques = pd.factorize(df[TARGET_COLUMN])
  134. df[TARGET_COLUMN] = codes
  135. df.dropna(inplace=True)
  136. return df, len(uniques)
  137. def process_data(batch):
  138. labels = torch.LongTensor([obj["label"] for obj in batch])
  139. tokens = []
  140. lengths = []
  141. for obj in batch:
  142. code_tokens = tokenizer.tokenize(obj["code"], truncation=True, max_length=MAX_SEQUENCE_LENGTH)
  143. token_ids = tokenizer.convert_tokens_to_ids(code_tokens)
  144. lengths.append(len(token_ids))
  145. tokens.append(torch.tensor(token_ids))
  146. tokens = nn.utils.rnn.pad_sequence(tokens, batch_first=True, padding_value=tokenizer.pad_token_id)
  147. lengths = torch.LongTensor(lengths)
  148. sorted_lengths, indices = torch.sort(lengths, descending=True)
  149. tokens = tokens[indices]
  150. with torch.no_grad():
  151. tokens = codebert_model(tokens.to(DEVICE))[0]
  152. # pack = nn.utils.rnn.pack_padded_sequence(tokens, sorted_lengths, batch_first=True)
  153. return tokens, sorted_lengths, labels[indices]
  154. def train_new_model(df_train, df_test, n_epochs, params, lr=3e-3):
  155. model = Classifier(**params)
  156. model = model.to(DEVICE)
  157. train_dataloader = torch.utils.data.DataLoader(
  158. CodeblocksDataset(df_train), batch_size=16, collate_fn=process_data, shuffle=True
  159. )
  160. test_dataloader = torch.utils.data.DataLoader(
  161. CodeblocksDataset(df_test), batch_size=16, collate_fn=process_data
  162. )
  163. optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
  164. scheduler = torch.optim.lr_scheduler.OneCycleLR(
  165. optimizer, max_lr=lr, steps_per_epoch=len(train_dataloader), epochs=n_epochs
  166. )
  167. criterion = FocalLoss()
  168. history = defaultdict(list)
  169. for epoch in range(n_epochs):
  170. train_loss, train_acc, train_f1 = train(model, DEVICE, train_dataloader, epoch, criterion, optimizer)
  171. history["train_loss"].append(train_loss)
  172. history["train_acc"].append(train_acc)
  173. history["train_f1"].append(train_f1)
  174. print("evaluating")
  175. test_loss, test_acc, test_f1 = test(model, DEVICE, test_dataloader, epoch, criterion)
  176. history["test_loss"].append(test_loss)
  177. history["test_acc"].append(test_acc)
  178. history["test_f1"].append(test_f1)
  179. scheduler.step()
  180. return model, history
  181. class Objective:
  182. def __init__(self, n_classes, df_train, df_test):
  183. self.n_classes = n_classes
  184. self.df_train = df_train
  185. self.df_test = df_test
  186. def __call__(self, trial):
  187. params = {
  188. "rnn_size": trial.suggest_int("rnn_size", *SEARCH_SPACE["rnn_size"]),
  189. "n_rnn_layers": trial.suggest_int("n_rnn_layers", *SEARCH_SPACE["n_rnn_layers"]),
  190. "lin_size": trial.suggest_int("lin_size", *SEARCH_SPACE["lin_size"]),
  191. "n_features": trial.suggest_int("n_features", *SEARCH_SPACE["n_features"]),
  192. "n_conv_layers": trial.suggest_int("n_conv_layers", *SEARCH_SPACE["n_conv_layers"]),
  193. "n_classes": self.n_classes,
  194. }
  195. model, history = train_new_model(self.df_train, self.df_test, N_EPOCHS, params)
  196. checkpoint_path = CHECKPOINT_PATH_TEMPLATE.format(trial.number)
  197. history_path = LEARNING_HISTORY_PATH_TEMPLATE.format(trial.number)
  198. torch.save(model.state_dict(), checkpoint_path)
  199. pickle.dump(history, open(history_path, "wb"))
  200. last_f1 = history["test_f1"][-1]
  201. return last_f1
  202. def select_hyperparams(df, n_classes, model_path):
  203. df_train, df_test = train_test_split(df, test_size=0.2, random_state=RANDOM_SEED)
  204. study = optuna.create_study(direction="maximize", study_name="rnn with codebert", sampler=optuna.samplers.TPESampler())
  205. objective = Objective(n_classes, df_train, df_test)
  206. study.optimize(objective, n_trials=N_TRIALS)
  207. model_params = study.best_params
  208. model_params["n_classes"] = n_classes
  209. best_checkpoint_path = CHECKPOINT_PATH_TEMPLATE.format(study.best_trial.number)
  210. best_history_path = LEARNING_HISTORY_PATH_TEMPLATE.format(study.best_trial.number)
  211. history = pickle.load(open(best_history_path, "rb"))
  212. metrics = {
  213. "test_f1_score": history["test_f1"][-1],
  214. "test_accuracy": history["test_acc"][-1],
  215. "history": history,
  216. }
  217. shutil.copy(best_checkpoint_path, model_path)
  218. return model_params, metrics
  219. if __name__ == "__main__":
  220. df, n_classes = prep_data()
  221. data_meta = {
  222. "DATASET_PATH": DATASET_PATH,
  223. "model": MODEL_DIR,
  224. "script_dir": __file__,
  225. "random_seed": RANDOM_SEED,
  226. }
  227. print("selecting hyperparameters")
  228. model_params, metrics = select_hyperparams(df, n_classes, MODEL_DIR)
  229. print("logging the results")
  230. print("hyperparams:", model_params)
  231. print("metrics:", metrics)
  232. print("finished")
Tip!

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

Comments

Loading...