-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathstream_sarsa_minatar.py
141 lines (128 loc) · 6.64 KB
/
stream_sarsa_minatar.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
import os, pickle, argparse
import torch
import numpy as np
import torch.nn as nn
import gymnasium as gym
from optim import ObGD as Optimizer
import torch.nn.functional as F
from normalization_wrappers import NormalizeObservation, ScaleReward
from sparse_init import sparse_init
def linear_schedule(start_e: float, end_e: float, duration: int, t: int):
slope = (end_e - start_e) / duration
return max(slope * t + start_e, end_e)
class LayerNormalization(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input):
return F.layer_norm(input, input.size())
def extra_repr(self) -> str:
return "Layer Normalization"
def initialize_weights(m):
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
sparse_init(m.weight, sparsity=0.9)
m.bias.data.fill_(0.0)
class StreamSARSA(nn.Module):
def __init__(self, n_channels=4, n_actions=3, hidden_size=128, lr=1.0, epsilon_target=0.01, epsilon_start=1.0, exploration_fraction=0.1, total_steps=1_000_000, gamma=0.99, lamda=0.8, kappa_value=2.0):
super(StreamSARSA, self).__init__()
self.n_actions = n_actions
self.gamma = gamma
self.epsilon_start = epsilon_start
self.epsilon_target = epsilon_target
self.epsilon = epsilon_start
self.exploration_fraction = exploration_fraction
self.total_steps = total_steps
self.time_step = 0
self.network = nn.Sequential(
nn.Conv2d(n_channels, 16, 3, stride=1),
LayerNormalization(),
nn.LeakyReLU(),
nn.Flatten(start_dim=0),
nn.Linear(1024, hidden_size),
LayerNormalization(),
nn.LeakyReLU(),
nn.Linear(hidden_size, n_actions)
)
self.apply(initialize_weights)
self.optimizer = Optimizer(list(self.parameters()), lr=lr, gamma=gamma, lamda=lamda, kappa=kappa_value)
def q(self, x):
x = torch.moveaxis(x, -1, 0)
return self.network(x)
def sample_action(self, s):
self.time_step += 1
self.epsilon = linear_schedule(self.epsilon_start, self.epsilon_target, self.exploration_fraction * self.total_steps, self.time_step)
if isinstance(s, np.ndarray):
s = torch.tensor(np.array(s), dtype=torch.float)
if np.random.rand() < self.epsilon:
return np.random.randint(0, self.n_actions)
else:
q_values = self.q(s)
return torch.argmax(q_values, dim=-1)
def update_params(self, s, a, r, s_prime, a_prime, done, overshooting_info=False):
done_mask = 0 if done else 1
s, a, r, s_prime, a_prime, done_mask = torch.tensor(np.array(s), dtype=torch.float), torch.tensor([a], dtype=torch.int).squeeze(0), \
torch.tensor(np.array(r)), torch.tensor(np.array(s_prime), dtype=torch.float), \
torch.tensor([a_prime], dtype=torch.int).squeeze(0), torch.tensor(np.array(done_mask), dtype=torch.float)
q_sa = self.q(s)[a]
q_s_prime_a_prime = self.q(s_prime)[a_prime]
td_target = r + self.gamma * q_s_prime_a_prime * done_mask
delta = td_target - q_sa
q_output = -q_sa
self.optimizer.zero_grad()
q_output.backward()
self.optimizer.step(delta.item(), reset=done)
if overshooting_info:
q_s_prime_a_prime = self.q(s_prime)[a_prime]
td_target = r + self.gamma * q_s_prime_a_prime * done_mask
delta_bar = td_target - self.q(s)[a]
if torch.sign(delta_bar * delta).item() == -1:
print("Overshooting Detected!")
def main(env_name, seed, lr, gamma, lamda, total_steps, epsilon_target, epsilon_start, exploration_fraction, kappa_value, debug, overshooting_info, render=False):
torch.manual_seed(seed); np.random.seed(seed)
env = gym.make(env_name, render_mode='human') if render else gym.make(env_name)
env = gym.wrappers.RecordEpisodeStatistics(env)
env = NormalizeObservation(env)
env = ScaleReward(env, gamma=gamma)
agent = StreamSARSA(n_channels=env.observation_space.shape[-1], n_actions=env.action_space.n, lr=lr, gamma=gamma, lamda=lamda, epsilon_target=epsilon_target, epsilon_start=epsilon_start, exploration_fraction=exploration_fraction, kappa_value=kappa_value)
if debug:
print("seed: {}".format(seed), "env: {}".format(env.spec.id))
returns, term_time_steps = [], []
s, _ = env.reset(seed=seed)
episode_num = 1
a = agent.sample_action(s)
for t in range(1, total_steps+1):
s_prime, r, terminated, truncated, info = env.step(a)
a_prime = agent.sample_action(s_prime)
agent.update_params(s, a, r, s_prime, a_prime, terminated or truncated, overshooting_info)
s = s_prime
a = a_prime
if terminated or truncated:
if debug:
print("Episodic Return: {}, Time Step {}, Episode Number {}, Epsilon {}".format(info['episode']['r'][0], t, episode_num, agent.epsilon))
returns.append(info['episode']['r'][0])
term_time_steps.append(t)
terminated, truncated = False, False
s, _ = env.reset()
episode_num += 1
env.close()
save_dir = "data_stream_sarsa_{}_lr{}_gamma{}_lamda{}".format(env.spec.id, lr, gamma, lamda)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
with open(os.path.join(save_dir, "seed_{}.pkl".format(seed)), "wb") as f:
pickle.dump((returns, term_time_steps, env_name), f)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Stream SARSA(λ)')
parser.add_argument('--env_name', type=str, default='MinAtar/Breakout-v1')
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--lr', type=float, default=1.0)
parser.add_argument('--gamma', type=float, default=0.99)
parser.add_argument('--lamda', type=float, default=0.8)
parser.add_argument('--epsilon_target', type=float, default=0.01)
parser.add_argument('--epsilon_start', type=float, default=1.0)
parser.add_argument('--exploration_fraction', type=float, default=0.05)
parser.add_argument('--kappa_value', type=float, default=2.0)
parser.add_argument('--total_steps', type=int, default=10_000_000)
parser.add_argument('--debug', action='store_true')
parser.add_argument('--overshooting_info', action='store_true')
parser.add_argument('--render', action='store_true')
args = parser.parse_args()
main(args.env_name, args.seed, args.lr, args.gamma, args.lamda, args.total_steps, args.epsilon_target, args.epsilon_start, args.exploration_fraction, args.kappa_value, args.debug, args.overshooting_info, args.render)