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

attention_rnn_train.py 8.5 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
  1. import argparse
  2. import os
  3. import pickle
  4. import shutil
  5. from collections import defaultdict
  6. import numpy as np
  7. import optuna
  8. import pandas as pd
  9. from sklearn.model_selection import train_test_split
  10. from transformers import AutoTokenizer, AutoModel
  11. from common.nn_tools import *
  12. os.environ["CUDA_VISIBLE_DEVICES"] = "3"
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument("GRAPH_VER", help="version of the graph you want regex to label your CSV with", type=str)
  15. parser.add_argument("DATASET_PATH", help="path to your input CSV", type=str)
  16. args = parser.parse_args()
  17. GRAPH_VER = args.GRAPH_VER
  18. DATASET_PATH = args.DATASET_PATH
  19. MODEL_DIR = "../models/rnn_codebert_graph_v{}.pt".format(GRAPH_VER)
  20. CHECKPOINT_PATH_TEMPLATE = "../checkpoints/rnn_codebert_trial{}.pt"
  21. LEARNING_HISTORY_PATH_TEMPLATE = "../checkpoints/rnn_codebert_history_trial{}.pickle"
  22. DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  23. EMBEDDING_SIZE = 768
  24. MAX_SEQUENCE_LENGTH = 512 # this is required by transformers for some reason
  25. RANDOM_SEED = 42
  26. N_EPOCHS = 50
  27. N_TRIALS = 30
  28. torch.manual_seed(RANDOM_SEED)
  29. tokenizer = AutoTokenizer.from_pretrained("microsoft/codebert-base")
  30. codebert_model = AutoModel.from_pretrained("microsoft/codebert-base").to(DEVICE)
  31. EXPERIMENT_DATA_PATH = ".."
  32. CODE_COLUMN = "code_block"
  33. TARGET_COLUMN = "graph_vertex_id"
  34. SEARCH_SPACE = {
  35. "rnn_size": (32, 256),
  36. "rnn_layers": (1, 4),
  37. "lin_size": (16, 256),
  38. }
  39. class CodeblocksDataset(torch.utils.data.Dataset):
  40. def __init__(self, data):
  41. super(CodeblocksDataset, self).__init__()
  42. self.data = data
  43. def __len__(self):
  44. return self.data.shape[0]
  45. def __getitem__(self, idx):
  46. return {
  47. "code": self.data.iloc[idx][CODE_COLUMN],
  48. "label": self.data.iloc[idx][TARGET_COLUMN]
  49. }
  50. class Attention(nn.Module):
  51. def __init__(self, feature_dim, step_dim, bias=True, **kwargs):
  52. super(Attention, self).__init__(**kwargs)
  53. self.supports_masking = True
  54. self.bias = bias
  55. self.feature_dim = feature_dim
  56. self.step_dim = step_dim
  57. self.features_dim = 0
  58. weight = torch.zeros(feature_dim, 1)
  59. nn.init.kaiming_uniform_(weight)
  60. self.weight = nn.Parameter(weight)
  61. if bias:
  62. self.b = nn.Parameter(torch.zeros(step_dim))
  63. def forward(self, x, mask=None):
  64. feature_dim = self.feature_dim
  65. step_dim = self.step_dim
  66. eij = torch.mm(
  67. x.contiguous().view(-1, feature_dim),
  68. self.weight
  69. ).view(-1, step_dim)
  70. if self.bias:
  71. eij = eij + self.b
  72. eij = torch.tanh(eij)
  73. a = torch.exp(eij)
  74. if mask is not None:
  75. a = a * mask
  76. a = a / (torch.sum(a, 1, keepdim=True) + 1e-10)
  77. weighted_input = x * torch.unsqueeze(a, -1)
  78. return torch.sum(weighted_input, 1)
  79. class Classifier(nn.Module):
  80. def __init__(self, rnn_size, rnn_layers, lin_size, n_classes):
  81. super(Classifier, self).__init__()
  82. self.rnn = nn.LSTM(
  83. EMBEDDING_SIZE, rnn_size, num_layers=rnn_layers,
  84. batch_first=True, dropout=0.25, bidirectional=True
  85. )
  86. self.attention = Attention(2 * rnn_size, MAX_SEQUENCE_LENGTH)
  87. self.decoder = nn.Sequential(
  88. nn.Linear(2 * rnn_size, lin_size),
  89. nn.GELU(),
  90. nn.Dropout(0.25),
  91. nn.Linear(lin_size, n_classes)
  92. )
  93. size = 0
  94. for p in self.parameters():
  95. size += p.nelement()
  96. print("Total param size: {}".format(size))
  97. def forward(self, data):
  98. x, lengths = data
  99. # initial shape (batch_size, time, features)
  100. x = nn.utils.rnn.pack_padded_sequence(x, lengths.to("cpu"), batch_first=True)
  101. out, _ = self.rnn(x)
  102. out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first=True, total_length=MAX_SEQUENCE_LENGTH)
  103. mask = (
  104. torch.arange(MAX_SEQUENCE_LENGTH).expand(lengths.size(0), MAX_SEQUENCE_LENGTH).to(DEVICE) < lengths.unsqueeze(1)
  105. )
  106. out = self.attention(out, mask)
  107. return self.decoder(out)
  108. def prep_data():
  109. df = pd.read_csv(DATASET_PATH, index_col=0)
  110. df.drop_duplicates(inplace=True)
  111. codes, uniques = pd.factorize(df[TARGET_COLUMN])
  112. df[TARGET_COLUMN] = codes
  113. df.dropna(inplace=True)
  114. return df, len(uniques)
  115. def process_data(batch):
  116. labels = torch.LongTensor([obj["label"] for obj in batch])
  117. tokens = []
  118. lengths = []
  119. for obj in batch:
  120. code_tokens = tokenizer.tokenize(obj["code"], truncation=True, max_length=MAX_SEQUENCE_LENGTH)
  121. token_ids = tokenizer.convert_tokens_to_ids(code_tokens)
  122. lengths.append(len(token_ids))
  123. tokens.append(torch.tensor(token_ids))
  124. tokens = nn.utils.rnn.pad_sequence(tokens, batch_first=True, padding_value=tokenizer.pad_token_id)
  125. lengths = torch.LongTensor(lengths)
  126. sorted_lengths, indices = torch.sort(lengths, descending=True)
  127. tokens = tokens[indices]
  128. with torch.no_grad():
  129. tokens = codebert_model(tokens.to(DEVICE))[0]
  130. # pack = nn.utils.rnn.pack_padded_sequence(tokens, sorted_lengths, batch_first=True)
  131. return (tokens, sorted_lengths), labels[indices]
  132. def train_new_model(df_train, df_test, n_epochs, params, lr=3e-1):
  133. model = Classifier(**params)
  134. model = model.to(DEVICE)
  135. train_dataloader = torch.utils.data.DataLoader(
  136. CodeblocksDataset(df_train), batch_size=16, collate_fn=process_data, shuffle=True
  137. )
  138. test_dataloader = torch.utils.data.DataLoader(
  139. CodeblocksDataset(df_test), batch_size=16, collate_fn=process_data
  140. )
  141. optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
  142. scheduler = torch.optim.lr_scheduler.OneCycleLR(
  143. optimizer, max_lr=lr, steps_per_epoch=len(train_dataloader), epochs=n_epochs
  144. )
  145. criterion = FocalLoss()
  146. history = defaultdict(list)
  147. for epoch in range(n_epochs):
  148. train_loss, train_acc, train_f1 = train(model, DEVICE, train_dataloader, epoch, criterion, optimizer)
  149. history["train_loss"].append(train_loss)
  150. history["train_acc"].append(train_acc)
  151. history["train_f1"].append(train_f1)
  152. print("evaluating")
  153. test_loss, test_acc, test_f1 = test(model, DEVICE, test_dataloader, epoch, criterion)
  154. history["test_loss"].append(test_loss)
  155. history["test_acc"].append(test_acc)
  156. history["test_f1"].append(test_f1)
  157. scheduler.step()
  158. return model, history
  159. class Objective:
  160. def __init__(self, n_classes, df_train, df_test):
  161. self.n_classes = n_classes
  162. self.df_train = df_train
  163. self.df_test = df_test
  164. def __call__(self, trial):
  165. params = {
  166. "rnn_size": trial.suggest_int("rnn_size", *SEARCH_SPACE["rnn_size"]),
  167. "rnn_layers": trial.suggest_int("rnn_layers", *SEARCH_SPACE["rnn_layers"]),
  168. "lin_size": trial.suggest_int("lin_size", *SEARCH_SPACE["lin_size"]),
  169. "n_classes": self.n_classes,
  170. }
  171. model, history = train_new_model(self.df_train, self.df_test, N_EPOCHS, params)
  172. checkpoint_path = CHECKPOINT_PATH_TEMPLATE.format(trial.number)
  173. history_path = LEARNING_HISTORY_PATH_TEMPLATE.format(trial.number)
  174. torch.save(model.state_dict(), checkpoint_path)
  175. pickle.dump(history, open(history_path, "wb"))
  176. best_f1 = np.array(history["test_f1"]).max()
  177. return best_f1
  178. def select_hyperparams(df, n_classes, model_path):
  179. df_train, df_test = train_test_split(df, test_size=0.2, random_state=RANDOM_SEED)
  180. study = optuna.create_study(direction="maximize", study_name="rnn with codebert", sampler=optuna.samplers.TPESampler())
  181. objective = Objective(n_classes, df_train, df_test)
  182. study.optimize(objective, n_trials=N_TRIALS)
  183. model_params = study.best_params
  184. model_params["n_classes"] = n_classes
  185. best_checkpoint_path = CHECKPOINT_PATH_TEMPLATE.format(study.best_trial.number)
  186. best_history_path = LEARNING_HISTORY_PATH_TEMPLATE.format(study.best_trial.number)
  187. history = pickle.load(open(best_history_path, "rb"))
  188. shutil.copy(best_checkpoint_path, model_path)
  189. return model_params, history
  190. if __name__ == "__main__":
  191. df, n_classes = prep_data()
  192. data_meta = {
  193. "DATASET_PATH": DATASET_PATH,
  194. "model": MODEL_DIR,
  195. "script_dir": __file__,
  196. "random_seed": RANDOM_SEED,
  197. }
  198. print("selecting hyperparameters")
  199. model_params, history = select_hyperparams(df, n_classes, MODEL_DIR)
  200. print("hyperparams:", model_params)
  201. print("history", history)
  202. print("finished")
Tip!

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

Comments

Loading...