-
Notifications
You must be signed in to change notification settings - Fork 333
/
train_gather.py
297 lines (247 loc) · 12.1 KB
/
train_gather.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
Train agents to gather food
"""
import argparse
import logging as log
import time
import magent
from magent.builtin.mx_model import DeepQNetwork as RLModel
# change this line to magent.builtin.tf_model to use tensorflow
def load_config(size):
gw = magent.gridworld
cfg = gw.Config()
cfg.set({"map_width": size, "map_height": size})
cfg.set({"minimap_mode": True})
agent = cfg.register_agent_type(
name="agent",
attr={'width': 1, 'length': 1, 'hp': 3, 'speed': 3,
'view_range': gw.CircleRange(7), 'attack_range': gw.CircleRange(1),
'damage': 6, 'step_recover': 0,
'step_reward': -0.01, 'dead_penalty': -1, 'attack_penalty': -0.1,
'attack_in_group': 1})
food = cfg.register_agent_type(
name='food',
attr={'width': 1, 'length': 1, 'hp': 25, 'speed': 0,
'view_range': gw.CircleRange(1), 'attack_range': gw.CircleRange(0),
'kill_reward': 5})
g_f = cfg.add_group(food)
g_s = cfg.add_group(agent)
a = gw.AgentSymbol(g_s, index='any')
b = gw.AgentSymbol(g_f, index='any')
cfg.add_reward_rule(gw.Event(a, 'attack', b), receiver=a, value=0.5)
return cfg
def generate_map(env, map_size, food_handle, handles):
center_x, center_y = map_size // 2, map_size // 2
def add_square(pos, side, gap):
side = int(side)
for x in range(center_x - side//2, center_x + side//2 + 1, gap):
pos.append([x, center_y - side//2])
pos.append([x, center_y + side//2])
for y in range(center_y - side//2, center_y + side//2 + 1, gap):
pos.append([center_x - side//2, y])
pos.append([center_x + side//2, y])
# agent
pos = []
add_square(pos, map_size * 0.9, 3)
add_square(pos, map_size * 0.8, 4)
add_square(pos, map_size * 0.7, 6)
env.add_agents(handles[0], method="custom", pos=pos)
# food
pos = []
add_square(pos, map_size * 0.65, 10)
add_square(pos, map_size * 0.6, 10)
add_square(pos, map_size * 0.55, 10)
add_square(pos, map_size * 0.5, 4)
add_square(pos, map_size * 0.45, 3)
add_square(pos, map_size * 0.4, 1)
add_square(pos, map_size * 0.3, 1)
add_square(pos, map_size * 0.3 - 2, 1)
add_square(pos, map_size * 0.3 - 4, 1)
add_square(pos, map_size * 0.3 - 6, 1)
env.add_agents(food_handle, method="custom", pos=pos)
# legend
legend = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0,],
[1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 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, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
]
def draw(base_x, base_y, scale, data):
w, h = len(data), len(data[0])
pos = []
for i in range(w):
for j in range(h):
if data[i][j] == 1:
start_x = i * scale + base_x
start_y = j * scale + base_y
for x in range(start_x, start_x + scale):
for y in range(start_y, start_y + scale):
pos.append([y, x])
env.add_agents(food_handle, method="custom", pos=pos)
scale = 1
w, h = len(legend), len(legend[0])
offset = -3
draw(offset + map_size // 2 - w // 2 * scale, map_size // 2 - h // 2 * scale, scale, legend)
draw(offset + map_size // 2 - w // 2 * scale + len(legend), map_size // 2 - h // 2 * scale, scale, org)
def play_a_round(env, map_size, food_handle, handles, models, train_id=-1,
print_every=10, record=False, render=False, eps=None):
env.reset()
generate_map(env, map_size, food_handle, handles)
step_ct = 0
total_reward = 0
done = False
pos_reward_ct = set()
n = len(handles)
obs = [None for _ in range(n)]
ids = [None for _ in range(n)]
acts = [None for _ in range(n)]
nums = [env.get_num(handle) for handle in handles]
sample_buffer = magent.utility.EpisodesBuffer(capacity=5000)
print("===== sample =====")
print("eps %s number %s" % (eps, nums))
start_time = time.time()
while not done:
# take actions for every model
for i in range(n):
obs[i] = env.get_observation(handles[i])
ids[i] = env.get_agent_id(handles[i])
acts[i] = models[i].infer_action(obs[i], ids[i], policy='e_greedy', eps=eps)
env.set_action(handles[i], acts[i])
# simulate one step
done = env.step()
# sample
rewards = env.get_reward(handles[train_id])
step_reward = 0
if train_id != -1:
alives = env.get_alive(handles[train_id])
total_reward += sum(rewards)
sample_buffer.record_step(ids[train_id], obs[train_id], acts[train_id], rewards, alives)
step_reward = sum(rewards)
# render
if render:
env.render()
for id, r in zip(ids[0], rewards):
if r > 0.05 and id not in pos_reward_ct:
pos_reward_ct.add(id)
# clear dead agents
env.clear_dead()
# stats info
for i in range(n):
nums[i] = env.get_num(handles[i])
food_num = env.get_num(food_handle)
if step_ct % print_every == 0:
print("step %3d, train %d, num %s, reward %.2f, total_reward: %.2f, non_zero: %d" %
(step_ct, train_id, [food_num] + nums, step_reward, total_reward, len(pos_reward_ct)))
step_ct += 1
if step_ct > 350:
break
sample_time = time.time() - start_time
print("steps: %d, total time: %.2f, step average %.2f" % (step_ct, sample_time, sample_time / step_ct))
if record:
with open("reward-hunger.txt", "a") as fout:
fout.write(str(nums[0]) + "\n")
# train
total_loss = value = 0
if train_id != -1:
print("===== train =====")
start_time = time.time()
total_loss, value = models[train_id].train(sample_buffer, print_every=250)
train_time = time.time() - start_time
print("train_time %.2f" % train_time)
return total_loss, total_reward, value, len(pos_reward_ct)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--save_every", type=int, default=2)
parser.add_argument("--render_every", type=int, default=10)
parser.add_argument("--n_round", type=int, default=1500)
parser.add_argument("--render", action='store_true')
parser.add_argument("--load_from", type=int)
parser.add_argument("--train", action="store_true")
parser.add_argument("--print_every", type=int, default=100)
parser.add_argument("--map_size", type=int, default=200)
parser.add_argument("--greedy", action="store_true")
parser.add_argument("--name", type=str, default="gather")
parser.add_argument("--record", action="store_true")
parser.add_argument("--eval", action="store_true")
args = parser.parse_args()
# set logger
log.basicConfig(level=log.INFO, filename=args.name + '.log')
console = log.StreamHandler()
console.setLevel(log.INFO)
log.getLogger('').addHandler(console)
# init env
env = magent.GridWorld(load_config(size=args.map_size))
env.set_render_dir("build/render")
handles = env.get_handles()
food_handle = handles[0]
player_handles = handles[1:]
# sample eval observation set
eval_obs = None
if args.eval:
print("sample eval set...")
env.reset()
generate_map(env, args.map_size, food_handle, player_handles)
eval_obs = magent.utility.sample_observation(env, player_handles, 0, 2048, 500)
# load models
models = [
RLModel(env, player_handles[0], args.name,
batch_size=512, memory_size=2 ** 19, target_update=1000,
train_freq=4, eval_obs=eval_obs)
]
# load saved model
save_dir = "save_model"
if args.load_from is not None:
start_from = args.load_from
print("load models...")
for model in models:
model.load(save_dir, start_from)
else:
start_from = 0
# print debug info
print(args)
print('view_space', env.get_view_space(player_handles[0]))
print('feature_space', env.get_feature_space(player_handles[0]))
print('view2attack', env.get_view2attack(player_handles[0]))
if args.record:
for k in range(4, 999 + 5, 5):
eps = 0
for model in models:
model.load(save_dir, start_from)
play_a_round(env, args.map_size, food_handle, player_handles, models,
-1, record=True, render=False,
print_every=args.print_every, eps=eps)
else:
# play
start = time.time()
train_id = 0 if args.train else -1
for k in range(start_from, start_from + args.n_round):
tic = time.time()
eps = magent.utility.piecewise_decay(k, [0, 400, 1000], [1.0, 0.2, 0.05]) if not args.greedy else 0
loss, reward, value, pos_reward_ct = \
play_a_round(env, args.map_size, food_handle, player_handles, models,
train_id, record=False,
render=args.render or (k+1) % args.render_every == 0,
print_every=args.print_every, eps=eps)
log.info("round %d\t loss: %.3f\t reward: %.2f\t value: %.3f\t pos_reward_ct: %d"
% (k, loss, reward, value, pos_reward_ct))
print("round time %.2f total time %.2f\n" % (time.time() - tic, time.time() - start))
if (k + 1) % args.save_every == 0 and args.train:
print("save models...")
for model in models:
model.save(save_dir, k)