-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrun.py
173 lines (160 loc) · 6.06 KB
/
run.py
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
import os
import gc
import time
import random
import logging
import torch
import pynvml
import argparse
import numpy as np
import pandas as pd
import multiprocessing as mp
from multiprocessing import Pool
from models.AMIO import AMIO
from trains.ATIO import ATIO
from data.load_data import MMDataLoader
from config.config_regression import ConfigRegression
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def run(args):
if not os.path.exists(args.model_save_dir):
os.makedirs(args.model_save_dir)
args.model_save_path = os.path.join(args.model_save_dir, f'{args.modelName}-{args.datasetName}-{args.train_mode}.pth')
# indicate used gpu
if len(args.gpu_ids) == 0 and torch.cuda.is_available():
# load free-most gpu
pynvml.nvmlInit()
dst_gpu_id, min_mem_used = 0, 1e16
for g_id in [0, 1]:
handle = pynvml.nvmlDeviceGetHandleByIndex(g_id)
meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
mem_used = meminfo.used
if mem_used < min_mem_used:
min_mem_used = mem_used
dst_gpu_id = g_id
print(f'Find gpu: {dst_gpu_id}, use memory: {min_mem_used}!')
logger.info(f'Find gpu: {dst_gpu_id}, with memory: {min_mem_used} left!')
args.gpu_ids.append(dst_gpu_id)
# device
using_cuda = len(args.gpu_ids) > 0 and torch.cuda.is_available()
logger.info("Let's use %d GPUs!" % len(args.gpu_ids))
device = torch.device('cuda:%d' % int(args.gpu_ids[0]) if using_cuda else 'cpu')
args.device = device
# add tmp tensor to increase the temporary consumption of GPU
tmp_tensor = torch.zeros((100, 100)).to(args.device)
# load data and models
dataloader = MMDataLoader(args)
model = AMIO(args).to(device)
del tmp_tensor
def count_parameters(model):
answer = 0
for p in model.parameters():
if p.requires_grad:
answer += p.numel()
# print(p)
return answer
logger.info(f'The model has {count_parameters(model)} trainable parameters')
atio = ATIO().getTrain(args)
# do train
atio.do_train(model, dataloader)
# load pretrained model
assert os.path.exists(args.model_save_path)
model.load_state_dict(torch.load(args.model_save_path))
model.to(device)
# do test
if args.is_tune:
# using valid dataset to tune hyper parameters
results = atio.do_test(model, dataloader['test'], mode="TEST")
else:
results = atio.do_test(model, dataloader['test'], mode="TEST")
del model
torch.cuda.empty_cache()
gc.collect()
time.sleep(5)
return results
def run_normal(args):
args.res_save_dir = os.path.join(args.res_save_dir, 'normals')
init_args = args
model_results = []
seeds = args.seeds
missing_rate = 0.0
# run results
for i, seed in enumerate(seeds):
args = init_args
# load config
config = ConfigRegression(args)
args = config.get_config()
if i == 0 and args.data_missing:
missing_rate = str(args.missing_rate[0])
setup_seed(seed)
args.seed = seed
logger.info('Start running %s...' %(args.modelName))
logger.info(args)
# runnning
args.cur_time = i+1
test_results = run(args)
# restore results
model_results.append(test_results)
criterions = list(model_results[0].keys())
# load other results
save_path = os.path.join(args.res_save_dir, \
f'{args.datasetName}-{args.train_mode}-{missing_rate}.csv')
if not os.path.exists(args.res_save_dir):
os.makedirs(args.res_save_dir)
if os.path.exists(save_path):
df = pd.read_csv(save_path)
else:
df = pd.DataFrame(columns=["Model"] + criterions)
# save results
res = [args.modelName]
for c in criterions:
values = [r[c] for r in model_results]
mean = round(np.mean(values)*100, 2)
std = round(np.std(values)*100, 2)
res.append((mean, std))
df.loc[len(df)] = res
df.to_csv(save_path, index=None)
logger.info('Results are added to %s...' %(save_path))
def set_log(args):
log_file_path = f'logs/{args.modelName}-{args.datasetName}.log'
# set logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
for ph in logger.handlers:
logger.removeHandler(ph)
# add FileHandler to log file
formatter_file = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
fh = logging.FileHandler(log_file_path)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter_file)
logger.addHandler(fh)
return logger
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--train_mode', type=str, default="regression",
help='regression')
parser.add_argument('--modelName', type=str, default='tfr_net',
help='support tfn/mult/misa/tfr_net')
parser.add_argument('--datasetName', type=str, default='mosi',
help='support mosi/sims')
parser.add_argument('--num_workers', type=int, default=0,
help='num workers of loading data')
parser.add_argument('--model_save_dir', type=str, default='results/models',
help='path to save results.')
parser.add_argument('--res_save_dir', type=str, default='results/results',
help='path to save results.')
parser.add_argument('--gpu_ids', type=list, default=[],
help='indicates the gpus will be used. If none, the most-free gpu will be used!')
parser.add_argument('--missing', type=float, default=0.0)
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
args.missing_rate = tuple([args.missing, args.missing, args.missing])
global logger; logger = set_log(args)
args.seeds = [111, 1111, 11111]
run_normal(args)