-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrainer.py
More file actions
executable file
·202 lines (151 loc) · 8.05 KB
/
trainer.py
File metadata and controls
executable file
·202 lines (151 loc) · 8.05 KB
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
import torch
import gc
import os
import pandas as pd
from tqdm import tqdm
from utils.metric import get_rd
def train(args, model, train_dataloader, test_dataloader, optimizer, scheduler, device):
losses = []
epohcs = args.epochs
best_test_loss = float('inf')
best_epoch = 0
for epoch in tqdm(range(epohcs)):
torch.cuda.empty_cache()
gc.collect()
model.train()
train_loss_list = []
test_loss_list = []
print("Epoch:", epoch)
for idx, batch in enumerate(train_dataloader):
torch.cuda.empty_cache()
gc.collect()
labels = batch.pop("labels").to(device)
flattened_patches = batch.pop("flattened_patches").to(device)
attention_mask = batch.pop("attention_mask").to(device)
if args.phase == 1:
loss = model(flattened_patches = flattened_patches,
attention_mask = attention_mask,
labels=labels)
else:
loss = model.forward_phase_2(flattened_patches = flattened_patches,
attention_mask = attention_mask,
labels=labels,
batch_size = args.batch_size)
print("Loss:", loss.item())
train_loss_list.append(loss.item())
loss.backward()
optimizer.step()
optimizer.zero_grad()
scheduler.step()
train_loss = sum(train_loss_list) / len(train_dataloader)
del loss
del flattened_patches
del attention_mask
del labels
torch.cuda.empty_cache()
gc.collect()
model.eval()
for idx, batch in enumerate(test_dataloader):
labels = batch.pop("labels").to(device)
flattened_patches = batch.pop("flattened_patches").to(device)
attention_mask = batch.pop("attention_mask").to(device)
loss = model(flattened_patches = flattened_patches,
attention_mask = attention_mask,
labels=labels)
test_loss_list.append(loss.item())
del loss
del flattened_patches
del attention_mask
del labels
test_loss = sum(test_loss_list) / len(test_dataloader)
losses.append({'epoch' : epoch, 'train_loss': train_loss ,'test_loss' : test_loss})
if test_loss < best_test_loss:
best_test_loss = test_loss
best_epoch = epoch
torch.save({'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict()},
f'{args.model_save_path}/phase_{args.phase}_best_model.pth')
summary = pd.DataFrame(losses)
summary.to_csv(f'{args.model_save_path}/summary.csv')
torch.save({'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict()},
f'{args.model_save_path}/phase_{args.phase}_{epoch}_model_state_dict.pth')
print(f"Best model saved with test loss {best_test_loss} at epoch {best_epoch}")
def inference(args, model, dataset, dataloader, processor, device):
os.makedirs(args.result_path, exist_ok=True) # Ensure result path exists
if args.inference_type == 'QA':
accuracy_list = {'img': [], 'type': [], 'pred': [], 'label': []}
for idx, batch in enumerate(dataloader):
try:
print(f"Processing batch {idx + 1}/{len(dataloader)}")
labels = batch.pop("labels").to(device)
flattened_patches = batch.pop("flattened_patches").to(device)
attention_mask = batch.pop("attention_mask").to(device)
chart_type = batch.pop("type")
predictions = model.generate(flattened_patches=flattened_patches,
attention_mask=attention_mask)
pred = processor.batch_decode(predictions, skip_special_tokens=True)
label = processor.batch_decode(labels, skip_special_tokens=True)
accuracy_list['img'].append(dataset[idx]['img_name'])
accuracy_list['type'].append(chart_type[0])
accuracy_list['pred'].append(pred[0])
accuracy_list['label'].append(label[0])
except Exception as e:
print(f"Error in batch {idx + 1}: {e}")
continue # Skip problematic batches
result_df = pd.DataFrame(accuracy_list)
print("Saving QA results...")
result_df.to_csv(os.path.join(args.result_path, 'prediction.csv'), index=False)
else:
accuracy_list = {'img': [], 'pred': []}
for idx, batch in enumerate(dataloader):
try:
print(f"Processing batch {idx + 1}/{len(dataloader)}")
flattened_patches = batch.pop("flattened_patches").to(device)
attention_mask = batch.pop("attention_mask").to(device)
predictions = model.generate(flattened_patches=flattened_patches,
attention_mask=attention_mask)
pred = processor.batch_decode(predictions, skip_special_tokens=True)
accuracy_list['img'].append(dataset[idx]['img_name'])
accuracy_list['pred'].append(pred[0])
except Exception as e:
print(f"Error in batch {idx + 1}: {e}")
continue
result_df = pd.DataFrame(accuracy_list)
print("Saving OpenCQA results...")
result_df.to_csv(os.path.join(args.result_path, 'opencqa_prediction.csv'), index=False)
print("Inference complete.")
# def inference(args, model, dataset, dataloader, processor, device):
# if args.inference_type == 'QA':
# accuracy_list = {'img':[], 'type':[], 'pred':[], 'label':[]}
# for idx, batch in enumerate(dataloader):
# labels = batch.pop("labels").to(device)
# flattened_patches = batch.pop("flattened_patches").to(device)
# attention_mask = batch.pop("attention_mask").to(device)
# chart_type = batch.pop("type")
# predictions = model.generate(flattened_patches= flattened_patches,
# attention_mask=attention_mask,)
# pred = processor.batch_decode(predictions, skip_special_tokens=True)
# label = processor.batch_decode(labels, skip_special_tokens=True)
# accuracy_list['img'].append(dataset[idx]['img_name'])
# accuracy_list['type'].append(chart_type[0])
# accuracy_list['pred'].append(pred[0])
# accuracy_list['label'].append(label[0])
# result_df = pd.DataFrame(accuracy_list)
# rd_df, failed = get_rd(result_df)
# rd_df.to_csv(os.path.join(args.result_path, 'prediction.csv'))
# else:
# accuracy_list = {'img':[], 'pred':[]}
# for idx, batch in enumerate(dataloader):
# flattened_patches = batch.pop("flattened_patches").to(device)
# attention_mask = batch.pop("attention_mask").to(device)
# predictions = model.generate(flattened_patches= flattened_patches,
# attention_mask=attention_mask)
# pred = processor.batch_decode(predictions, skip_special_tokens=True)
# accuracy_list['img'].append(dataset[idx]['img_name'])
# accuracy_list['pred'].append(pred[0])
# result_df = pd.DataFrame(accuracy_list)
# result_df.to_csv(os.path.join(args.result_path, 'opencqa_prediction.csv'))