-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
179 lines (128 loc) · 5.88 KB
/
Copy pathagent.py
File metadata and controls
179 lines (128 loc) · 5.88 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
import flappy_bird_gymnasium
import gymnasium as gym
from dqn import DQN
from experience_replay import ReplayMemory
import itertools
import yaml
import torch
import torch.nn as nn
import torch.optim as optim
import os
import argparse
import random
if torch.backends.mps.is_available():
device = "mps"
elif torch.cuda.is_available():
device = "cuda"
else:
device = "cpu"
RUNS_DIR = "runs"
os.makedirs(RUNS_DIR, exist_ok=True)
class Agent:
def __init__(self, param_set):
self.param_set = param_set
with open("parameters.yaml", "r") as f:
all_param_set = yaml.safe_load(f)
params = all_param_set[param_set]
self.alpha = params["alpha"]
self.gamma = params["gamma"]
self.epsilon_init = params["epsilon_init"]
self.epsilon_min = params["epsilon_min"]
self.epsilon_decay = params["epsilon_decay"]
self.replay_memory_size = params["replay_memory_size"]
self.mini_batch_size = params["mini_batch_size"]
self.reward_threshold = params["reward_threshold"]
self.network_sync_rate = params["network_sync_rate"]
self.mini_batch_size = params["mini_batch_size"]
self.loss_fn = nn.MSELoss()
self.optimizer = None
self.LOG_FILE = os.path.join(RUNS_DIR, f"{self.param_set}.log")
self.MODEL_FILE = os.path.join(RUNS_DIR, f"{self.param_set}.pt")
def run(self, is_training=True, render=False):
env = gym.make("FlappyBird-v0", render_mode="human" if render else None)
num_states = env.observation_space.shape[0] # input dim
num_actions = env.action_space.n # output dim
policy_dqn = DQN(num_states, num_actions).to(device)
if is_training:
memory = ReplayMemory(self.replay_memory_size)
epsilon = self.epsilon_init
target_dqn = DQN(num_states, num_actions).to(device)
# copy the wt & bias vals from policy => target
target_dqn.load_state_dict(policy_dqn.state_dict())
steps = 0
self.optimizer = optim.Adam(policy_dqn.parameters(), lr=self.alpha)
best_reward = float("-inf")
else:
# best policy load
policy_dqn.load_state_dict(torch.load(self.MODEL_FILE))
policy_dqn.eval()
for episode in itertools.count():
state, _ = env.reset()
state = torch.tensor(state, dtype=torch.float, device=device)
episode_reward = 0
terminated = False
while (not terminated and episode_reward < self.reward_threshold):
if is_training and random.random() < epsilon:
action = env.action_space.sample() # explore
action = torch.tensor(action, dtype=torch.long, device=device)
else:
with torch.no_grad():
action = policy_dqn(state.unsqueeze(dim=0)).squeeze().argmax() # exploit
next_state, reward, terminated, _, _ = env.step(action.item())
episode_reward += reward
# create tensors
reward = torch.tensor(reward, dtype=torch.float, device=device)
next_state = torch.tensor(next_state, dtype=torch.float, device=device)
if is_training:
memory.append((state, action, next_state, reward, terminated))
steps += 1
state = next_state
print(f"episode={episode+1} with total reward={episode_reward} & epsilon={epsilon}")
if is_training:
# epsilon decay
epsilon = max(epsilon * self.epsilon_decay, self.epsilon_min)
if episode_reward > best_reward:
log_msg = f"best reward = {episode_reward} for episode={episode+1}"
with open(self.LOG_FILE, "a") as f:
f.write(log_msg + "\n")
torch.save(policy_dqn.state_dict(), self.MODEL_FILE)
best_reward = episode_reward
if is_training and len(memory) > self.mini_batch_size:
# get sample
mini_batch = memory.sample(self.mini_batch_size)
self.optimize(mini_batch, policy_dqn, target_dqn)
# sync the network
if steps > self.network_sync_rate:
target_dqn.load_state_dict(policy_dqn.state_dict())
steps = 0
# env.close() - manually stop
def optimize(self, mini_batch, policy_dqn, target_dqn):
# get batch of experiences
states, actions, next_states, rewards, terminations = zip(*mini_batch)
states = torch.stack(states)
actions = torch.stack(actions)
next_states = torch.stack(next_states)
rewards = torch.stack(rewards)
terminations = torch.tensor(terminations).float().to(device)
# calculate target Q-values - if terminations=true => zero
with torch.no_grad():
target_q = rewards + (1-terminations) * self.gamma * target_dqn(next_states).max(dim=1)[0]
# calculate y_pred i.e. Q-value from current policy
current_q = policy_dqn(states).gather(dim=1, index=actions.unsqueeze(dim=1)).squeeze()
# compute loss
loss = self.loss_fn(current_q, target_q)
# optimize model
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
if __name__ == "__main__":
# Parse command line inputs
parser = argparse.ArgumentParser(description='Train or test model.')
parser.add_argument('hyperparameters', help='')
parser.add_argument('--train', help='Training mode', action='store_true')
args = parser.parse_args()
dql = Agent(param_set=args.hyperparameters)
if args.train:
dql.run(is_training=True)
else:
dql.run(is_training=False, render=True)