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

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

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

Comments

Loading...