-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
174 lines (150 loc) · 5.31 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
171
172
173
174
from gym import EggnoggGym
from network import Policy, Value
import torch.optim as optim
import os
import torch
from tqdm import tqdm
from datetime import datetime
from time import sleep
from loss import PerfPolicy, PerfValue
from math import sqrt, exp, log
import sys
#params
min_I = 1e-5
max_steps = 1000
gamma = exp(log(min_I)/max_steps)
print(gamma)
path_to_chkpt = 'weights.tar'
cpu = torch.device('cpu') #pylint: disable=no-member
gpu = torch.device('cuda:0') #pylint: disable=no-member
#networks
P = Policy()
V = Value()
need_pretrained = not os.path.isfile(path_to_chkpt)
gym = EggnoggGym(need_pretrained, gpu) #network in gym.observation
#performance measures
Perf_p = PerfPolicy()
Perf_v = PerfValue()
#info
episode = 1
episode_len = []
#init save upon new start
if need_pretrained:
"""print('Initializing weights...')
torch.save({
'episode': episode,
'episode_len': episode_len,
'P_state_dict': P.state_dict(),
'V_state_dict': V.state_dict(),
'O_state_dict': gym.observation.state_dict()#,
#'optimizerP': optimizerP.state_dict(),
#'optimizerV': optimizerV.state_dict()
}, path_to_chkpt)
print('...Done')"""
#load weights
else:
checkpoint = torch.load(path_to_chkpt, map_location=cpu)
episode = checkpoint['episode']
episode_len = checkpoint['episode_len']
P.load_state_dict(checkpoint['P_state_dict'])
V.load_state_dict(checkpoint['V_state_dict'])
gym.observation.load_state_dict(checkpoint['O_state_dict'])
P.to(gpu)
V.to(gpu)
gym.observation.to(gpu)
#optimizer
optimizerP = optim.SGD(params= list(P.parameters()),
lr=1e-5)
optimizerV = optim.SGD(params=list(V.parameters())+list(gym.observation.parameters()),
lr=4e-5)
#############################################################################
#one-step actor critic
##############################################################################
"""
actions = p(gym.observation(gym.states))
obs, reward, is_terminal = gym.step(actions)
actions = p(obs)
#init noop action
actions = (torch.tensor([[.0,.0,1.0], #pylint: disable=not-callable
[.0,.0,1.0]]),
torch.tensor([[.0,.0,1.0], #pylint: disable=not-callable
[.0,.0,1.0]]),
torch.tensor([[.0], #pylint: disable=not-callable
[.0]]),
torch.tensor([[.0], #pylint: disable=not-callable
[.0]])
)"""
G_idx = 0
try:
while True:
#INITS
is_terminal = False
steps = green_reward_sum = 0
I = 1
obs = gym.observation(gym.states)
G_idx = (G_idx+1)%2
with torch.enable_grad():
while not is_terminal:
start = datetime.now()
steps += 1
actions = P(obs)
obs_new, reward, is_terminal = gym.step(actions)
if steps%max_steps == 0:
is_terminal = True
v_old = V(obs)
with torch.autograd.no_grad():
#calculate delta_t: R_t+1 + gamma*V(S#I = max(1e-5, gamma*I)b,ds_t+1) - V(S_t)
if not is_terminal:
v_new = V(obs_new)
delta = reward[G_idx] + gamma*v_new[G_idx] - v_old[G_idx].detach()
else:
delta = reward[G_idx] - v_old[G_idx]
perf_v = Perf_v(delta, v_old, G_idx)
#(-perf_v).backward() #gradient ascent
perf_p = Perf_p(delta, I, actions, gym.prev_action, G_idx)
#(-perf_p).backward() #gradient ascent
perf = -(perf_v + perf_p) #gradient ascent
perf.backward()
optimizerV.step()
optimizerP.step()
optimizerV.zero_grad()
optimizerP.zero_grad()
I *= gamma
obs = obs_new
stop = datetime.now()
"""for a in actions:
print(a)"""
print('delta:',delta.item(), '\n',
'v_old:',v_old, '\n',
'v_new:',v_new, '\n',
'steps:',steps)
"""if reward[0] > reward[1]:
print('G')
elif reward[0] == reward[1]:
print('E')
else:
print('R')"""
green_reward_sum += I*reward[0]
print('green_reward_sum:', green_reward_sum)
print('undiscounted_reward:', reward[0])
print('time/step:',stop-start)
print()
episode += 1
print(episode, steps)
episode_len.append(steps)
print('Finished')
gym.reset()
print('Saving weights...')
torch.save({
'episode': episode,
'episode_len': episode_len,
'P_state_dict': P.state_dict(),
'V_state_dict': V.state_dict(),
'O_state_dict': gym.observation.state_dict(),
'optimizerP': optimizerP.state_dict(),
'optimizerV': optimizerV.state_dict()
}, path_to_chkpt)
print('...Done')
except KeyboardInterrupt:
gym.reset()
sys.exit()