forked from cassieqiuyd/MJOLNIR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·170 lines (137 loc) · 4.88 KB
/
main.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
from __future__ import print_function, division
import os
import random
import ctypes
import setproctitle
import time
import numpy as np
import torch
import torch.multiprocessing as mp
from tensorboardX import SummaryWriter
from utils import flag_parser
from utils.class_finder import model_class, agent_class, optimizer_class
from utils.net_util import ScalarMeanTracker
from main_eval import main_eval
from runners import nonadaptivea3c_train, nonadaptivea3c_val, savn_train, savn_val
os.environ["OMP_NUM_THREADS"] = "1"
def main():
setproctitle.setproctitle("Train/Test Manager")
args = flag_parser.parse_arguments()
if args.model == "SAVN":
args.learned_loss = True
args.num_steps = 6
target = savn_val if args.eval else savn_train
else:
args.learned_loss = False
args.num_steps = 50
target = nonadaptivea3c_val if args.eval else nonadaptivea3c_train
create_shared_model = model_class(args.model)
init_agent = agent_class(args.agent_type)
optimizer_type = optimizer_class(args.optimizer)
if args.eval:
main_eval(args, create_shared_model, init_agent)
return
start_time = time.time()
local_start_time_str = time.strftime(
"%Y-%m-%d_%H:%M:%S", time.localtime(start_time)
)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
random.seed(args.seed)
if args.log_dir is not None:
tb_log_dir = args.log_dir + "/" + args.title + "-" + local_start_time_str
log_writer = SummaryWriter(log_dir=tb_log_dir)
else:
log_writer = SummaryWriter(comment=args.title)
if args.gpu_ids == -1:
args.gpu_ids = [-1]
else:
torch.cuda.manual_seed(args.seed)
mp.set_start_method("spawn")
shared_model = create_shared_model(args)
train_total_ep = 0
n_frames = 0
if shared_model is not None:
shared_model.share_memory()
optimizer = optimizer_type(
filter(lambda p: p.requires_grad, shared_model.parameters()), args
)
optimizer.share_memory()
print(shared_model)
else:
assert (
args.agent_type == "RandomNavigationAgent"
), "The model is None but agent is not random agent"
optimizer = None
processes = []
end_flag = mp.Value(ctypes.c_bool, False)
train_res_queue = mp.Queue()
for rank in range(0, args.workers):
p = mp.Process(
target=target,
args=(
rank,
args,
create_shared_model,
shared_model,
init_agent,
optimizer,
train_res_queue,
end_flag,
),
)
p.start()
processes.append(p)
time.sleep(0.1)
print("Train agents created.")
train_thin = args.train_thin
train_scalars = ScalarMeanTracker()
save_entire_model = 0
try:
while train_total_ep < args.max_ep:
train_result = train_res_queue.get()
train_scalars.add_scalars(train_result)
train_total_ep += 1
n_frames += train_result["ep_length"]
if (train_total_ep % train_thin) == 0:
log_writer.add_scalar("n_frames", n_frames, train_total_ep)
tracked_means = train_scalars.pop_and_reset()
for k in tracked_means:
log_writer.add_scalar(
k + "/train", tracked_means[k], train_total_ep
)
if (train_total_ep % args.ep_save_freq) == 0:
print(n_frames)
if not os.path.exists(args.save_model_dir):
os.makedirs(args.save_model_dir)
state_to_save = shared_model.state_dict()
save_path = os.path.join(
args.save_model_dir,
"{0}_{1}_{2}_{3}.dat".format(
args.title, n_frames, train_total_ep, local_start_time_str
),
)
torch.save(state_to_save, save_path)
save_entire_model += 1
if (save_entire_model % 5) == 0:
state = {
'epoch': train_total_ep,
'state_dict': shared_model.state_dict(),
'optimizer': optimizer.state_dict(),
}
save_model_path = os.path.join(
args.save_model_dir,
"{0}_{1}_{2}.tar".format(
args.title, train_total_ep, local_start_time_str
),
)
torch.save(state,save_model_path)
save_entire_model=0
finally:
log_writer.close()
end_flag.value = True
for p in processes:
time.sleep(0.1)
p.join()
if __name__ == "__main__":
main()