agent.py 49.7 KB
Newer Older
1
2
3
4
5
6
7
import mxnet as mx
import numpy as np
import time
import os
import sys
import util
import matplotlib.pyplot as plt
Nicola Gatto's avatar
Nicola Gatto committed
8
9
import pyprind
from cnnarch_logger import ArchLogger
10
from replay_memory import ReplayMemoryBuilder
Nicola Gatto's avatar
Nicola Gatto committed
11
12
13
14
from strategy import StrategyBuilder
from util import copy_net, get_loss_function,\
    copy_net_with_two_inputs, DdpgTrainingStats, DqnTrainingStats,\
    make_directory_if_not_exist
15
16
from mxnet import nd, gluon, autograd

Nicola Gatto's avatar
Nicola Gatto committed
17
18
19
20

class Agent(object):
    def __init__(
        self,
21
22
        environment,
        replay_memory_params,
Nicola Gatto's avatar
Nicola Gatto committed
23
        strategy_params,
24
        state_dim,
Nicola Gatto's avatar
Nicola Gatto committed
25
        action_dim,
26
27
28
29
        ctx=None,
        discount_factor=.9,
        training_episodes=50,
        train_interval=1,
Nicola Gatto's avatar
Nicola Gatto committed
30
        start_training=0,
31
        snapshot_interval=200,
Nicola Gatto's avatar
Nicola Gatto committed
32
        agent_name='Agent',
33
        max_episode_step=99999,
Nicola Gatto's avatar
Nicola Gatto committed
34
        evaluation_samples=1000,
35
36
        output_directory='model_parameters',
        verbose=True,
Nicola Gatto's avatar
Nicola Gatto committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
        target_score=None
    ):
        assert 0 < discount_factor <= 1,\
            'Discount factor must be between 0 and 1'
        assert train_interval > 0, 'Train interval must be greater 0'
        assert snapshot_interval > 0, 'Snapshot interval must be greater 0'
        assert max_episode_step > 0,\
            'Maximal steps per episode must be greater 0'
        assert training_episodes > 0, 'Trainings episode must be greater 0'
        assert replay_memory_params is not None,\
            'Replay memory parameter not set'
        assert type(state_dim) is tuple, 'State dimension is not a tuple'
        assert type(action_dim) is tuple, 'Action dimension is not a tuple'

        self._logger = ArchLogger.get_logger()
        self._ctx = mx.gpu() if ctx == 'gpu' else mx.cpu()
        self._environment = environment
        self._discount_factor = discount_factor
        self._training_episodes = training_episodes
        self._train_interval = train_interval
        self._verbose = verbose
        self._state_dim = state_dim
59
60

        replay_memory_params['state_dim'] = state_dim
Nicola Gatto's avatar
Nicola Gatto committed
61
62
        replay_memory_params['action_dim'] = action_dim
        self._replay_memory_params = replay_memory_params
63
        rm_builder = ReplayMemoryBuilder()
Nicola Gatto's avatar
Nicola Gatto committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
        self._memory = rm_builder.build_by_params(**replay_memory_params)
        self._minibatch_size = self._memory.sample_size
        self._action_dim = action_dim

        strategy_params['action_dim'] = self._action_dim
        self._strategy_params = strategy_params
        strategy_builder = StrategyBuilder()
        self._strategy = strategy_builder.build_by_params(**strategy_params)
        self._agent_name = agent_name
        self._snapshot_interval = snapshot_interval
        self._creation_time = time.time()
        self._max_episode_step = max_episode_step
        self._start_training = start_training
        self._output_directory = output_directory
        self._target_score = target_score

        self._evaluation_samples = evaluation_samples
        self._best_avg_score = -np.infty
        self._best_net = None

        self._interrupt_flag = False
        self._training_stats = None
86
87

        # Training Context
Nicola Gatto's avatar
Nicola Gatto committed
88
89
        self._current_episode = 0
        self._total_steps = 0
90

Nicola Gatto's avatar
Nicola Gatto committed
91
92
93
    @property
    def current_episode(self):
        return self._current_episode
94

Nicola Gatto's avatar
Nicola Gatto committed
95
96
97
    @property
    def environment(self):
        return self._environment
98

Nicola Gatto's avatar
Nicola Gatto committed
99
    def save_config_file(self):
100
        import json
Nicola Gatto's avatar
Nicola Gatto committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        make_directory_if_not_exist(self._output_directory)
        filename = os.path.join(self._output_directory, 'config.json')
        config = self._make_config_dict()
        with open(filename, mode='w') as fp:
            json.dump(config, fp, indent=4)

    def set_interrupt_flag(self, interrupt):
        self._interrupt_flag = interrupt

    def _interrupt_training(self):
        import pickle
        self._logger.info('Training interrupted; Store state for resuming')
        session_dir = self._get_session_dir()
        agent_session_file = os.path.join(session_dir, 'agent.p')
        logger = self._logger

Nicola Gatto's avatar
Nicola Gatto committed
117
118
        self._training_stats.save_stats(self._output_directory, episode=self._current_episode)

Nicola Gatto's avatar
Nicola Gatto committed
119
120
121
122
123
124
125
126
127
128
        self._make_pickle_ready(session_dir)

        with open(agent_session_file, 'wb') as f:
            pickle.dump(self, f, protocol=2)
        logger.info('State successfully stored')

    def _make_pickle_ready(self, session_dir):
        del self._training_stats.logger
        self._environment.close()
        self._environment = None
Nicola Gatto's avatar
Nicola Gatto committed
129
130
        self._export_net(self._best_net, 'best_net', filedir=session_dir)
        self._logger = None
Nicola Gatto's avatar
Nicola Gatto committed
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
        self._best_net = None

    def _make_config_dict(self):
        config = dict()
        config['state_dim'] = self._state_dim
        config['action_dim'] = self._action_dim
        config['ctx'] = str(self._ctx)
        config['discount_factor'] = self._discount_factor
        config['strategy_params'] = self._strategy_params
        config['replay_memory_params'] = self._replay_memory_params
        config['training_episodes'] = self._training_episodes
        config['start_training'] = self._start_training
        config['evaluation_samples'] = self._evaluation_samples
        config['train_interval'] = self._train_interval
        config['snapshot_interval'] = self._snapshot_interval
        config['agent_name'] = self._agent_name
        config['max_episode_step'] = self._max_episode_step
        config['output_directory'] = self._output_directory
        config['verbose'] = self._verbose
        config['target_score'] = self._target_score
        return config

    def _adjust_optimizer_params(self, optimizer_params):
        if 'weight_decay' in optimizer_params:
            optimizer_params['wd'] = optimizer_params['weight_decay']
            del optimizer_params['weight_decay']
        if 'learning_rate_decay' in optimizer_params:
            min_learning_rate = 1e-8
            if 'learning_rate_minimum' in optimizer_params:
                min_learning_rate = optimizer_params['learning_rate_minimum']
                del optimizer_params['learning_rate_minimum']
            optimizer_params['lr_scheduler'] = mx.lr_scheduler.FactorScheduler(
                optimizer_params['step_size'],
                factor=optimizer_params['learning_rate_decay'],
                stop_factor_lr=min_learning_rate)
            del optimizer_params['step_size']
            del optimizer_params['learning_rate_decay']

        return optimizer_params

    def _sample_from_memory(self):
        states, actions, rewards, next_states, terminals\
            = self._memory.sample(batch_size=self._minibatch_size)
        states = nd.array(states, ctx=self._ctx)
        actions = nd.array(actions, ctx=self._ctx)
        rewards = nd.array(rewards, ctx=self._ctx)
        next_states = nd.array(next_states, ctx=self._ctx)
        terminals = nd.array(terminals, ctx=self._ctx)
        return states, actions, rewards, next_states, terminals

    def evaluate(self, target=None, sample_games=100, verbose=True):
Nicola Gatto's avatar
Nicola Gatto committed
182
183
184
        if sample_games <= 0:
            return 0

Nicola Gatto's avatar
Nicola Gatto committed
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
        target = self._target_score if target is None else target
        if target:
            target_achieved = 0
        total_reward = 0

        self._logger.info('Sampling from {} games...'.format(sample_games))
        for g in pyprind.prog_bar(range(sample_games)):
            state = self._environment.reset()
            step = 0
            game_reward = 0
            terminal = False
            while not terminal and (step < self._max_episode_step):
                action = self.get_next_action(state)
                state, reward, terminal, _ = self._environment.step(action)
                game_reward += reward
                step += 1

            if verbose:
                info = 'Game %d: Reward %f' % (g, game_reward)
                self._logger.debug(info)
            if target:
                if game_reward >= target:
                    target_achieved += 1
            total_reward += game_reward

        avg_reward = float(total_reward)/float(sample_games)
        info = 'Avg. Reward: %f' % avg_reward
        if target:
            target_achieved_ratio = int(
                (float(target_achieved)/float(sample_games))*100)
            info += '; Target Achieved in %d%% of games'\
                % (target_achieved_ratio)

        if verbose:
            self._logger.info(info)
        return avg_reward

    def _do_snapshot_if_in_interval(self, episode):
        do_snapshot =\
            (episode != 0 and (episode % self._snapshot_interval == 0))
        if do_snapshot:
            self.save_parameters(episode=episode)
            self._evaluate()

    def _evaluate(self, verbose=True):
        avg_reward = self.evaluate(
            sample_games=self._evaluation_samples, verbose=False)
        info = 'Evaluation -> Average Reward in {} games: {}'.format(
            self._evaluation_samples, avg_reward)

        if self._best_avg_score is None or self._best_avg_score <= avg_reward:
            self._save_current_as_best_net()
            self._best_avg_score = avg_reward
        if verbose:
            self._logger.info(info)

    def _is_target_reached(self, avg_reward):
        return self._target_score is not None\
            and avg_reward > self._target_score

    def _do_training(self):
        return (self._total_steps % self._train_interval == 0) and\
            (self._memory.is_sample_possible(self._minibatch_size)) and\
            (self._current_episode >= self._start_training)

    def _check_interrupt_routine(self):
        if self._interrupt_flag:
            self._interrupt_flag = False
            self._interrupt_training()
            return True
        return False

    def _is_target_reached(self, avg_reward):
        return self._target_score is not None\
            and avg_reward > self._target_score

Nicola Gatto's avatar
Nicola Gatto committed
261
    def _export_net(self, net, filename, filedir=None, episode=None):
Nicola Gatto's avatar
Nicola Gatto committed
262
263
264
        assert self._output_directory
        assert isinstance(net, gluon.HybridBlock)
        make_directory_if_not_exist(self._output_directory)
Nicola Gatto's avatar
Nicola Gatto committed
265
266
        filedir = self._output_directory if filedir is None else filedir
        filename = os.path.join(filedir, filename)
Nicola Gatto's avatar
Nicola Gatto committed
267

Nicola Gatto's avatar
Nicola Gatto committed
268
        if episode is not None:
Nicola Gatto's avatar
Nicola Gatto committed
269
270
            filename = filename + '-ep{}'.format(episode)

Nicola Gatto's avatar
Nicola Gatto committed
271
        net.export(filename, epoch=0)
Nicola Gatto's avatar
Nicola Gatto committed
272
        net.save_parameters(filename + '.params')
Nicola Gatto's avatar
Nicola Gatto committed
273

Nicola Gatto's avatar
Nicola Gatto committed
274
275
276
    def export_best_network(self, path=None, epoch=0):
        path = os.path.join(self._output_directory, 'best_network')\
            if path is None else path
Nicola Gatto's avatar
Nicola Gatto committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
        self._logger.info(
            'Saving best network with average reward of {}'.format(
                self._best_avg_score))
        self._best_net.export(path, epoch=epoch)

    def _get_session_dir(self):
        session_dir = os.path.join(
            self._output_directory, '.interrupted_session')
        make_directory_if_not_exist(session_dir)
        return session_dir

    def _save_current_as_best_net(self):
        raise NotImplementedError

    def get_next_action(self, state):
        raise NotImplementedError

    def save_parameters(self, episode):
        raise NotImplementedError

    def train(self, episodes=None):
        raise NotImplementedError


class DdpgAgent(Agent):
    def __init__(
        self,
        actor,
        critic,
        environment,
        replay_memory_params,
        strategy_params,
        state_dim,
        action_dim,
        soft_target_update_rate=.001,
        actor_optimizer='adam',
        actor_optimizer_params={'learning_rate': 0.0001},
        critic_optimizer='adam',
        critic_optimizer_params={'learning_rate': 0.001},
        ctx=None,
        discount_factor=.9,
        training_episodes=50,
        start_training=20,
        train_interval=1,
        snapshot_interval=200,
        agent_name='DdpgAgent',
        max_episode_step=9999,
        evaluation_samples=100,
        output_directory='model_parameters',
        verbose=True,
        target_score=None
    ):
        super(DdpgAgent, self).__init__(
            environment=environment, replay_memory_params=replay_memory_params,
            strategy_params=strategy_params, state_dim=state_dim,
            action_dim=action_dim, ctx=ctx, discount_factor=discount_factor,
            training_episodes=training_episodes, start_training=start_training,
            train_interval=train_interval,
            snapshot_interval=snapshot_interval, agent_name=agent_name,
            max_episode_step=max_episode_step,
            output_directory=output_directory, verbose=verbose,
            target_score=target_score, evaluation_samples=evaluation_samples)
        assert critic is not None, 'Critic not set'
        assert actor is not None, 'Actor is not set'
        assert soft_target_update_rate > 0,\
            'Target update must be greater zero'
        assert actor_optimizer is not None, 'No actor optimizer set'
        assert critic_optimizer is not None, 'No critic optimizer set'

        self._actor = actor
        self._critic = critic

        self._actor_target = self._copy_actor()
        self._critic_target = self._copy_critic()

        self._actor_optimizer = actor_optimizer
        self._actor_optimizer_params = self._adjust_optimizer_params(
            actor_optimizer_params)

        self._critic_optimizer = critic_optimizer
        self._critic_optimizer_params = self._adjust_optimizer_params(
            critic_optimizer_params)

        self._soft_target_update_rate = soft_target_update_rate

        self._logger.info(
            'Agent created with following parameters: {}'.format(
                self._make_config_dict()))

        self._best_net = self._copy_actor()

        self._training_stats = DdpgTrainingStats(self._training_episodes)

    def _make_pickle_ready(self, session_dir):
        super(DdpgAgent, self)._make_pickle_ready(session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
372
        self._export_net(self._actor, 'current_actor')
Nicola Gatto's avatar
Nicola Gatto committed
373

Nicola Gatto's avatar
Nicola Gatto committed
374
        self._export_net(self._actor, 'actor', filedir=session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
375
        self._actor = None
Nicola Gatto's avatar
Nicola Gatto committed
376
        self._export_net(self._critic, 'critic', filedir=session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
377
        self._critic = None
Nicola Gatto's avatar
Nicola Gatto committed
378
379
        self._export_net(
            self._actor_target, 'actor_target', filedir=session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
380
        self._actor_target = None
Nicola Gatto's avatar
Nicola Gatto committed
381
382
        self._export_net(
            self._critic_target, 'critic_target', filedir=session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
383
        self._critic_target = None
384
385

    @classmethod
Nicola Gatto's avatar
Nicola Gatto committed
386
    def resume_from_session(cls, session_dir, actor, critic, environment):
387
388
389
390
391
392
393
        import pickle
        if not os.path.exists(session_dir):
            raise ValueError('Session directory does not exist')

        files = dict()
        files['agent'] = os.path.join(session_dir, 'agent.p')
        files['best_net_params'] = os.path.join(session_dir, 'best_net.params')
Nicola Gatto's avatar
Nicola Gatto committed
394
395
396
397
398
399
        files['actor_net_params'] = os.path.join(session_dir, 'actor.params')
        files['actor_target_net_params'] = os.path.join(
            session_dir, 'actor_target.params')
        files['critic_net_params'] = os.path.join(session_dir, 'critic.params')
        files['critic_target_net_params'] = os.path.join(
            session_dir, 'critic_target.params')
400
401
402

        for file in files.values():
            if not os.path.exists(file):
Nicola Gatto's avatar
Nicola Gatto committed
403
404
405
                raise ValueError(
                    'Session directory is not complete: {} is missing'
                    .format(file))
406
407
408
409

        with open(files['agent'], 'rb') as f:
            agent = pickle.load(f)

Nicola Gatto's avatar
Nicola Gatto committed
410
411
412
413
414
415
416
417
418
419
420
421
422
423
        agent._environment = environment

        agent._actor = actor
        agent._actor.load_parameters(files['actor_net_params'], agent._ctx)
        agent._actor.hybridize()
        agent._actor(nd.random_normal(
            shape=((1,) + agent._state_dim), ctx=agent._ctx))

        agent._best_net = copy_net(agent._actor, agent._state_dim, agent._ctx)
        agent._best_net.load_parameters(files['best_net_params'], agent._ctx)

        agent._actor_target = copy_net(
            agent._actor, agent._state_dim, agent._ctx)
        agent._actor_target.load_parameters(files['actor_target_net_params'])
424

Nicola Gatto's avatar
Nicola Gatto committed
425
426
427
428
429
430
431
432
433
434
435
436
437
438
        agent._critic = critic
        agent._critic.load_parameters(files['critic_net_params'], agent._ctx)
        agent._critic.hybridize()
        agent._critic(
            nd.random_normal(shape=((1,) + agent._state_dim), ctx=agent._ctx),
            nd.random_normal(shape=((1,) + agent._action_dim), ctx=agent._ctx))

        agent._critic_target = copy_net_with_two_inputs(
            agent._critic, agent._state_dim, agent._action_dim, agent._ctx)
        agent._critic_target.load_parameters(files['critic_target_net_params'])

        agent._logger = ArchLogger.get_logger()
        agent._training_stats.logger = ArchLogger.get_logger()
        agent._logger.info('Agent was retrieved; Training can be continued')
439
440
441

        return agent

Nicola Gatto's avatar
Nicola Gatto committed
442
443
    def _save_current_as_best_net(self):
        self._best_net = self._copy_actor()
444

Nicola Gatto's avatar
Nicola Gatto committed
445
446
447
    def get_next_action(self, state):
        action = self._actor(nd.array([state], ctx=self._ctx))
        return action[0].asnumpy()
448

Nicola Gatto's avatar
Nicola Gatto committed
449
    def save_parameters(self, episode):
Nicola Gatto's avatar
Nicola Gatto committed
450
451
        self._export_net(
            self._actor, self._agent_name + '_actor', episode=episode)
452

Nicola Gatto's avatar
Nicola Gatto committed
453
454
455
456
457
    def train(self, episodes=None):
        self.save_config_file()
        self._logger.info("--- Start DDPG training ---")
        episodes = \
            episodes if episodes is not None else self._training_episodes
458

Nicola Gatto's avatar
Nicola Gatto committed
459
460
461
462
463
464
465
        resume = (self._current_episode > 0)
        if resume:
            self._logger.info("Training session resumed")
            self._logger.info(
                "Starting from episode {}".format(self._current_episode))
        else:
            self._training_stats = DdpgTrainingStats(episodes)
466

Nicola Gatto's avatar
Nicola Gatto committed
467
468
469
            # Initialize target Q' and mu'
            self._actor_target = self._copy_actor()
            self._critic_target = self._copy_critic()
470

Nicola Gatto's avatar
Nicola Gatto committed
471
472
        # Initialize l2 loss for critic network
        l2_loss = gluon.loss.L2Loss()
473

Nicola Gatto's avatar
Nicola Gatto committed
474
475
476
477
478
479
480
        # Initialize critic and actor trainer
        trainer_actor = gluon.Trainer(
            self._actor.collect_params(), self._actor_optimizer,
            self._actor_optimizer_params)
        trainer_critic = gluon.Trainer(
            self._critic.collect_params(), self._critic_optimizer,
            self._critic_optimizer_params)
481

Nicola Gatto's avatar
Nicola Gatto committed
482
483
484
485
486
        # For episode=1..n
        while self._current_episode < episodes:
            # Check interrupt flag
            if self._check_interrupt_routine():
                return False
487

Nicola Gatto's avatar
Nicola Gatto committed
488
489
490
491
492
493
494
495
            # Initialize new episode
            step = 0
            episode_reward = 0
            start = time.time()
            episode_critic_loss = 0
            episode_actor_loss = 0
            episode_avg_q_value = 0
            training_steps = 0
496

Nicola Gatto's avatar
Nicola Gatto committed
497
498
499
500
501
502
503
504
505
            # Get initialial observation state s
            state = self._environment.reset()

            # For step=1..T
            while step < self._max_episode_step:
                # Select an action a = mu(s) + N(step) according to current
                #  actor and exploration noise N according to strategy
                action = self._strategy.select_action(
                    self.get_next_action(state))
Nicola Gatto's avatar
Nicola Gatto committed
506
                self._strategy.decay(self._current_episode)
Nicola Gatto's avatar
Nicola Gatto committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549

                # Execute action a and observe reward r and next state ns
                next_state, reward, terminal, _ = \
                    self._environment.step(action)

                self._logger.debug(
                    'Applied action {} with reward {}'.format(action, reward))

                # Store transition (s,a,r,ns) in replay buffer
                self._memory.append(
                    state, action, reward, next_state, terminal)

                if self._do_training():
                    # Sample random minibatch of b transitions
                    # (s_i, a_i, r_i, s_(i+1)) from replay buffer
                    states, actions, rewards, next_states, terminals =\
                         self._sample_from_memory()

                    actor_target_actions = self._actor_target(next_states)
                    critic_target_qvalues = self._critic_target(
                        next_states, actor_target_actions)

                    rewards = rewards.reshape(self._minibatch_size, 1)
                    terminals = terminals.reshape(self._minibatch_size, 1)

                    # y = r_i + discount * Q'(s_(i+1), mu'(s_(i+1)))
                    y = rewards + (1.0 - terminals) * self._discount_factor\
                        * critic_target_qvalues

                    # Train the critic network
                    with autograd.record():
                        qvalues = self._critic(states, actions)
                        critic_loss = l2_loss(qvalues, y)
                    critic_loss.backward()
                    trainer_critic.step(self._minibatch_size)

                    # Train the actor network
                    # Temporary critic so that gluon trainer does not mess
                    # with critic parameters
                    tmp_critic = self._copy_critic()
                    with autograd.record():
                        # For maximizing qvalues we have to multiply with -1
                        # as we use a minimizer
Nicola Gatto's avatar
Nicola Gatto committed
550
551
                        actor_loss = -tmp_critic(
                            states, self._actor(states)).mean()
Nicola Gatto's avatar
Nicola Gatto committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
                    actor_loss.backward()
                    trainer_actor.step(self._minibatch_size)

                    # Update target networks:
                    self._actor_target = self._soft_update(
                        self._actor, self._actor_target,
                        self._soft_target_update_rate)
                    self._critic_target = self._soft_update(
                        self._critic, self._critic_target,
                        self._soft_target_update_rate)

                    # Update statistics
                    episode_critic_loss +=\
                        np.sum(critic_loss.asnumpy()) / self._minibatch_size
                    episode_actor_loss +=\
                        np.sum(actor_loss.asnumpy()) / self._minibatch_size
                    episode_avg_q_value +=\
Nicola Gatto's avatar
Nicola Gatto committed
569
                        np.sum(qvalues.asnumpy()) / self._minibatch_size
570

Nicola Gatto's avatar
Nicola Gatto committed
571
                    training_steps += 1
572

Nicola Gatto's avatar
Nicola Gatto committed
573
574
575
576
                episode_reward += reward
                step += 1
                self._total_steps += 1
                state = next_state
577

Nicola Gatto's avatar
Nicola Gatto committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
                if terminal:
                    # Reset the strategy
                    self._strategy.reset()
                    break

            # Log the episode results
            episode_actor_loss = 0 if training_steps == 0\
                else (episode_actor_loss / training_steps)
            episode_critic_loss = 0 if training_steps == 0\
                else (episode_critic_loss / training_steps)
            episode_avg_q_value = 0 if training_steps == 0\
                else (episode_avg_q_value / training_steps)

            avg_reward = self._training_stats.log_episode(
                self._current_episode, start, training_steps,
                episode_actor_loss, episode_critic_loss, episode_avg_q_value,
                self._strategy.cur_eps, episode_reward)

            self._do_snapshot_if_in_interval(self._current_episode)

            if self._is_target_reached(avg_reward):
                self._logger.info(
                    'Target score is reached in average; Training is stopped')
                break

            self._current_episode += 1

        self._evaluate()
        self.save_parameters(episode=self._current_episode)
Nicola Gatto's avatar
Nicola Gatto committed
607
        self.export_best_network()
Nicola Gatto's avatar
Nicola Gatto committed
608
609
610
611
612
613
614
615
616
617
618
619
        self._training_stats.save_stats(self._output_directory)
        self._logger.info('--------- Training finished ---------')
        return True

    def _make_config_dict(self):
        config = super(DdpgAgent, self)._make_config_dict()
        config['soft_target_update_rate'] = self._soft_target_update_rate
        config['actor_optimizer'] = self._actor_optimizer
        config['actor_optimizer_params'] = self._actor_optimizer_params
        config['critic_optimizer'] = self._critic_optimizer
        config['critic_optimizer_params'] = self._critic_optimizer_params
        return config
620

Nicola Gatto's avatar
Nicola Gatto committed
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
    def _soft_update(self, net, target, tau):
        net_params = [p.data() for _, p in net.collect_params().items()]
        for i, (_, p) in enumerate(target.collect_params().items()):
            target_params = p.data()
            p.set_data((1.0 - tau) * target_params + tau * net_params[i])
        return target

    def _copy_actor(self):
        assert self._actor is not None
        assert self._ctx is not None
        assert type(self._state_dim) is tuple
        return copy_net(self._actor, self._state_dim, ctx=self._ctx)

    def _copy_critic(self):
        assert self._critic is not None
        assert self._ctx is not None
        assert type(self._state_dim) is tuple
        assert type(self._action_dim) is tuple
        return copy_net_with_two_inputs(
            self._critic, self._state_dim, self._action_dim, ctx=self._ctx)


Nicola Gatto's avatar
Nicola Gatto committed
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
class TwinDelayedDdpgAgent(DdpgAgent):
    def __init__(
        self,
        actor,
        critic,
        environment,
        replay_memory_params,
        strategy_params,
        state_dim,
        action_dim,
        soft_target_update_rate=.001,
        actor_optimizer='adam',
        actor_optimizer_params={'learning_rate': 0.0001},
        critic_optimizer='adam',
        critic_optimizer_params={'learning_rate': 0.001},
        ctx=None,
        discount_factor=.9,
        training_episodes=50,
        start_training=20,
        train_interval=1,
        snapshot_interval=200,
        agent_name='DdpgAgent',
        max_episode_step=9999,
        evaluation_samples=100,
        output_directory='model_parameters',
        verbose=True,
        target_score=None,
        policy_noise=0.2,
        noise_clip=0.5,
        policy_delay=2
    ):
        super(TwinDelayedDdpgAgent, self).__init__(
            environment=environment, replay_memory_params=replay_memory_params,
            strategy_params=strategy_params, state_dim=state_dim,
            action_dim=action_dim, ctx=ctx, discount_factor=discount_factor,
            training_episodes=training_episodes, start_training=start_training,
            train_interval=train_interval,
            snapshot_interval=snapshot_interval, agent_name=agent_name,
            max_episode_step=max_episode_step,
            output_directory=output_directory, verbose=verbose,
            target_score=target_score, evaluation_samples=evaluation_samples,
            critic=critic, soft_target_update_rate=soft_target_update_rate,
            actor=actor, actor_optimizer=actor_optimizer,
            actor_optimizer_params=actor_optimizer_params,
            critic_optimizer=critic_optimizer,
            critic_optimizer_params=critic_optimizer_params)

        self._policy_noise = policy_noise
        self._noise_clip = noise_clip
        self._policy_delay = policy_delay

        self._critic2 = self._critic.__class__()
        self._critic2.collect_params().initialize(
            mx.init.Normal(), ctx=self._ctx)
        self._critic2.hybridize()
        self._critic2(nd.ones((1,) + state_dim, ctx=self._ctx),
                      nd.ones((1,) + action_dim, ctx=self._ctx))

        self._critic2_target = self._copy_critic2()

        self._critic2_optimizer = critic_optimizer
        self._critic2_optimizer_params = self._adjust_optimizer_params(
            critic_optimizer_params)

    def _make_pickle_ready(self, session_dir):
        super(TwinDelayedDdpgAgent, self)._make_pickle_ready(session_dir)
        self._export_net(self._critic2, 'critic2', filedir=session_dir)
        self._critic2 = None
        self._export_net(
            self._critic2_target, 'critic2_target', filedir=session_dir)
        self._critic2_target = None

    @classmethod
    def resume_from_session(cls, session_dir, actor, critic, environment):
        import pickle
        if not os.path.exists(session_dir):
            raise ValueError('Session directory does not exist')

        files = dict()
        files['agent'] = os.path.join(session_dir, 'agent.p')
        files['best_net_params'] = os.path.join(session_dir, 'best_net.params')
        files['actor_net_params'] = os.path.join(session_dir, 'actor.params')
        files['actor_target_net_params'] = os.path.join(
            session_dir, 'actor_target.params')
        files['critic_net_params'] = os.path.join(session_dir, 'critic.params')
        files['critic_target_net_params'] = os.path.join(
            session_dir, 'critic_target.params')
        files['critic2_net_params'] = os.path.join(
            session_dir, 'critic2.params')
        files['critic2_target_net_params'] = os.path.join(
            session_dir, 'critic2_target.params')

        for file in files.values():
            if not os.path.exists(file):
                raise ValueError(
                    'Session directory is not complete: {} is missing'
                    .format(file))

        with open(files['agent'], 'rb') as f:
            agent = pickle.load(f)

        agent._environment = environment

        agent._actor = actor
        agent._actor.load_parameters(files['actor_net_params'], agent._ctx)
        agent._actor.hybridize()
        agent._actor(nd.random_normal(
            shape=((1,) + agent._state_dim), ctx=agent._ctx))

        agent._best_net = copy_net(agent._actor, agent._state_dim, agent._ctx)
        agent._best_net.load_parameters(files['best_net_params'], agent._ctx)

        agent._actor_target = copy_net(
            agent._actor, agent._state_dim, agent._ctx)
        agent._actor_target.load_parameters(files['actor_target_net_params'])

        agent._critic = critic
        agent._critic.load_parameters(files['critic_net_params'], agent._ctx)
        agent._critic.hybridize()
        agent._critic(
            nd.random_normal(shape=((1,) + agent._state_dim), ctx=agent._ctx),
            nd.random_normal(shape=((1,) + agent._action_dim), ctx=agent._ctx))

        agent._critic_target = copy_net_with_two_inputs(
            agent._critic, agent._state_dim, agent._action_dim, agent._ctx)
        agent._critic_target.load_parameters(files['critic_target_net_params'])

        agent._critic2 = copy_net_with_two_inputs(
            agent._critic, agent._state_dim, agent._action_dim, agent._ctx)
        agent._critic2.load_parameters(files['critic2_net_params'], agent._ctx)
        agent._critic2.hybridize()
        agent._critic2(
            nd.random_normal(shape=((1,) + agent._state_dim), ctx=agent._ctx),
            nd.random_normal(shape=((1,) + agent._action_dim), ctx=agent._ctx))

        agent._critic2_target = copy_net_with_two_inputs(
            agent._critic2, agent._state_dim, agent._action_dim, agent._ctx)
        agent._critic2_target.load_parameters(
            files['critic2_target_net_params'])

        agent._logger = ArchLogger.get_logger()
        agent._training_stats.logger = ArchLogger.get_logger()
        agent._logger.info('Agent was retrieved; Training can be continued')

        return agent

    def _copy_critic2(self):
        assert self._critic2 is not None
        assert self._ctx is not None
        assert type(self._state_dim) is tuple
        assert type(self._action_dim) is tuple
        return copy_net_with_two_inputs(
            self._critic2, self._state_dim, self._action_dim, ctx=self._ctx)

    def train(self, episodes=None):
        self.save_config_file()
        self._logger.info("--- Start TwinDelayedDDPG training ---")
        episodes = \
            episodes if episodes is not None else self._training_episodes

        resume = (self._current_episode > 0)
        if resume:
            self._logger.info("Training session resumed")
            self._logger.info(
                "Starting from episode {}".format(self._current_episode))
        else:
            self._training_stats = DdpgTrainingStats(episodes)

            # Initialize target Q1' and Q2' and mu'
            self._actor_target = self._copy_actor()
            self._critic_target = self._copy_critic()
            self._critic2_target = self._copy_critic2()

        # Initialize l2 loss for critic network
        l2_loss = gluon.loss.L2Loss()

        # Initialize critic and actor trainer
        trainer_actor = gluon.Trainer(
            self._actor.collect_params(), self._actor_optimizer,
            self._actor_optimizer_params)
        trainer_critic = gluon.Trainer(
            self._critic.collect_params(), self._critic_optimizer,
            self._critic_optimizer_params)
        trainer_critic2 = gluon.Trainer(
            self._critic2.collect_params(), self._critic2_optimizer,
            self._critic2_optimizer_params)

        # For episode=1..n
        while self._current_episode < episodes:
            # Check interrupt flag
            if self._check_interrupt_routine():
                return False

            # Initialize new episode
            step = 0
            episode_reward = 0
            start = time.time()
            episode_critic_loss = 0
            episode_actor_loss = 0
            episode_avg_q_value = 0
            training_steps = 0
            actor_updates = 0

            # Get initialial observation state s
            state = self._environment.reset()

            # For step=1..T
            while step < self._max_episode_step:
                # Select an action a = mu(s) + N(step) according to current
                #  actor and exploration noise N according to strategy
                action = self._strategy.select_action(
                    self.get_next_action(state))
                self._strategy.decay(self._current_episode)

                # Execute action a and observe reward r and next state ns
                next_state, reward, terminal, _ = \
                    self._environment.step(action)

                self._logger.debug(
                    'Applied action {} with reward {}'.format(action, reward))

                # Store transition (s,a,r,ns) in replay buffer
                self._memory.append(
                    state, action, reward, next_state, terminal)

                if self._do_training():
                    # Sample random minibatch of b transitions
                    # (s_i, a_i, r_i, s_(i+1)) from replay buffer
                    states, actions, rewards, next_states, terminals =\
                         self._sample_from_memory()

                    clipped_noise = nd.array(
                        np.clip(
                            np.random.normal(
                                loc=0, scale=self._policy_noise,
                                size=self._minibatch_size
                            ).reshape(self._minibatch_size, 1),
                            -self._noise_clip,
                            self._noise_clip
                        ),
                        ctx=self._ctx
                    )
                    target_action = np.clip(
                        self._actor_target(next_states) + clipped_noise,
                        self._strategy._action_low,
                        self._strategy._action_high)

                    rewards = rewards.reshape(self._minibatch_size, 1)
                    terminals = terminals.reshape(self._minibatch_size, 1)

                    target_qvalues1 = self._critic_target(next_states,
                                                          target_action)
                    target_qvalues2 = self._critic2_target(next_states,
                                                           target_action)
                    target_qvalues = nd.minimum(target_qvalues1,
                                                target_qvalues2)
                    y = rewards + (1 - terminals) * self._discount_factor\
                        * target_qvalues

                    with autograd.record():
                        qvalues1 = self._critic(states, actions)
                        critic1_loss = l2_loss(qvalues1, y)
                    critic1_loss.backward()
                    trainer_critic.step(self._minibatch_size)

                    with autograd.record():
                        qvalues2 = self._critic2(states, actions)
                        critic2_loss = l2_loss(qvalues2, y)
                    critic2_loss.backward()
                    trainer_critic2.step(self._minibatch_size)

                    critic_loss = (critic1_loss.mean() + critic2_loss.mean())/2

                    if self._total_steps % self._policy_delay == 0:
                        tmp_critic = self._copy_critic()
                        with autograd.record():
                            actor_loss = -tmp_critic(
                                states, self._actor(states)).mean()
                        actor_loss.backward()
                        trainer_actor.step(self._minibatch_size)

                        # Update target networks:
                        self._actor_target = self._soft_update(
                            self._actor, self._actor_target,
                            self._soft_target_update_rate)
                        self._critic_target = self._soft_update(
                            self._critic, self._critic_target,
                            self._soft_target_update_rate)
                        self._critic2_target = self._soft_update(
                            self._critic2, self._critic2_target,
                            self._soft_target_update_rate)

                        actor_updates = actor_updates + 1
                    else:
                        actor_loss = nd.array([0], ctx=self._ctx)

                    # Update statistics
                    episode_critic_loss +=\
                        np.sum(critic_loss.asnumpy()) / self._minibatch_size
                    episode_actor_loss += 0 if actor_updates == 0 else\
                        np.sum(actor_loss.asnumpy()[0])
                    episode_avg_q_value +=\
                        np.sum(target_qvalues.asnumpy()) / self._minibatch_size

                    training_steps += 1

                episode_reward += reward
                step += 1
                self._total_steps += 1
                state = next_state

                if terminal:
                    # Reset the strategy
                    self._strategy.reset()
                    break

            # Log the episode results
            episode_actor_loss = 0 if actor_updates == 0\
                else (episode_actor_loss / actor_updates)
            episode_critic_loss = 0 if training_steps == 0\
                else (episode_critic_loss / training_steps)
            episode_avg_q_value = 0 if actor_updates == 0\
                else (episode_avg_q_value / training_steps)

            avg_reward = self._training_stats.log_episode(
                self._current_episode, start, training_steps,
                episode_actor_loss, episode_critic_loss, episode_avg_q_value,
                self._strategy.cur_eps, episode_reward)

            self._do_snapshot_if_in_interval(self._current_episode)

            if self._is_target_reached(avg_reward):
                self._logger.info(
                    'Target score is reached in average; Training is stopped')
                break

            self._current_episode += 1

        self._evaluate()
        self.save_parameters(episode=self._current_episode)
        self.export_best_network()
        self._training_stats.save_stats(self._output_directory)
        self._logger.info('--------- Training finished ---------')
        return True

        def _make_config_dict(self):
            config = super(TwinDelayedDdpgAgent, self)._make_config_dict()
            config['policy_noise'] = self._policy_noise
            config['noise_clip'] = self._noise_clip
            config['policy_delay'] = self._policy_delay
            return config


Nicola Gatto's avatar
Nicola Gatto committed
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
class DqnAgent(Agent):
    def __init__(
        self,
        qnet,
        environment,
        replay_memory_params,
        strategy_params,
        state_dim,
        action_dim,
        ctx=None,
        discount_factor=.9,
Nicola Gatto's avatar
Nicola Gatto committed
1007
        loss_function='l2',
Nicola Gatto's avatar
Nicola Gatto committed
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
        optimizer='rmsprop',
        optimizer_params={'learning_rate': 0.09},
        training_episodes=50,
        start_training=0,
        train_interval=1,
        use_fix_target=False,
        double_dqn=False,
        target_update_interval=10,
        snapshot_interval=200,
        evaluation_samples=100,
        agent_name='Dqn_agent',
        max_episode_step=99999,
        output_directory='model_parameters',
        verbose=True,
        target_score=None
    ):
        super(DqnAgent, self).__init__(
            environment=environment, replay_memory_params=replay_memory_params,
            strategy_params=strategy_params, state_dim=state_dim,
            action_dim=action_dim, ctx=ctx, discount_factor=discount_factor,
            training_episodes=training_episodes, start_training=start_training,
            train_interval=train_interval,
            snapshot_interval=snapshot_interval, agent_name=agent_name,
            max_episode_step=max_episode_step,
            output_directory=output_directory, verbose=verbose,
            target_score=target_score, evaluation_samples=evaluation_samples)

        self._qnet = qnet
        self._target_update_interval = target_update_interval
        self._target_qnet = copy_net(
            self._qnet, self._state_dim, ctx=self._ctx)
        self._loss_function_str = loss_function
        self._loss_function = get_loss_function(loss_function)
        self._optimizer = optimizer
        self._optimizer_params = optimizer_params
        self._double_dqn = double_dqn
        self._use_fix_target = use_fix_target
1045

Nicola Gatto's avatar
Nicola Gatto committed
1046
1047
1048
1049
1050
1051
1052
1053
        # Build memory buffer for discrete actions
        replay_memory_params['state_dim'] = state_dim
        replay_memory_params['action_dim'] = (1,)
        self._replay_memory_params = replay_memory_params
        rm_builder = ReplayMemoryBuilder()
        self._memory = rm_builder.build_by_params(**replay_memory_params)
        self._minibatch_size = self._memory.sample_size

Nicola Gatto's avatar
Nicola Gatto committed
1054
1055
1056
        # Initialize best network
        self._best_net = copy_net(self._qnet, self._state_dim, self._ctx)
        self._best_avg_score = -np.infty
1057

Nicola Gatto's avatar
Nicola Gatto committed
1058
        self._training_stats = None
1059

Nicola Gatto's avatar
Nicola Gatto committed
1060
1061
1062
1063
1064
    @classmethod
    def resume_from_session(cls, session_dir, net, environment):
        import pickle
        if not os.path.exists(session_dir):
            raise ValueError('Session directory does not exist')
1065

Nicola Gatto's avatar
Nicola Gatto committed
1066
1067
1068
1069
1070
1071
        files = dict()
        files['agent'] = os.path.join(session_dir, 'agent.p')
        files['best_net_params'] = os.path.join(session_dir, 'best_net.params')
        files['q_net_params'] = os.path.join(session_dir, 'qnet.params')
        files['target_net_params'] = os.path.join(
            session_dir, 'target_net.params')
1072

Nicola Gatto's avatar
Nicola Gatto committed
1073
1074
1075
1076
1077
        for file in files.values():
            if not os.path.exists(file):
                raise ValueError(
                    'Session directory is not complete: {} is missing'
                    .format(file))
1078

Nicola Gatto's avatar
Nicola Gatto committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
        with open(files['agent'], 'rb') as f:
            agent = pickle.load(f)

        agent._environment = environment
        agent._qnet = net
        agent._qnet.load_parameters(files['q_net_params'], agent._ctx)
        agent._qnet.hybridize()
        agent._qnet(nd.random_normal(
            shape=((1,) + agent._state_dim), ctx=agent._ctx))
        agent._best_net = copy_net(agent._qnet, agent._state_dim, agent._ctx)
        agent._best_net.load_parameters(files['best_net_params'], agent._ctx)
        agent._target_qnet = copy_net(
            agent._qnet, agent._state_dim, agent._ctx)
        agent._target_qnet.load_parameters(
            files['target_net_params'], agent._ctx)

        agent._logger = ArchLogger.get_logger()
        agent._training_stats.logger = agent._logger
        agent._logger.info('Agent was retrieved; Training can be continued')

        return agent

    def _make_pickle_ready(self, session_dir):
        super(DqnAgent, self)._make_pickle_ready(session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
1103
1104
        self._export_net(self._qnet, 'current_qnet')
        self._export_net(self._qnet, 'qnet', filedir=session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
1105
        self._qnet = None
Nicola Gatto's avatar
Nicola Gatto committed
1106
        self._export_net(self._target_qnet, 'target_net', filedir=session_dir)
Nicola Gatto's avatar
Nicola Gatto committed
1107
        self._target_qnet = None
1108
1109

    def get_q_values(self, state, with_best=False):
Nicola Gatto's avatar
Nicola Gatto committed
1110
1111
        return self.get_batch_q_values(
            nd.array([state], ctx=self._ctx), with_best=with_best)[0]
1112
1113

    def get_batch_q_values(self, state_batch, with_best=False):
Nicola Gatto's avatar
Nicola Gatto committed
1114
1115
        return self._best_net(state_batch)\
            if with_best else self._qnet(state_batch)
1116
1117
1118
1119

    def get_next_action(self, state, with_best=False):
        q_values = self.get_q_values(state, with_best=with_best)
        action = q_values.asnumpy().argmax()
Nicola Gatto's avatar
Nicola Gatto committed
1120
        return action
1121

Nicola Gatto's avatar
Nicola Gatto committed
1122
1123
1124
1125
1126
    def __determine_target_q_values(
        self, states, actions, rewards, next_states, terminals
    ):
        if self._use_fix_target:
            q_max_val = self._target_qnet(next_states)
1127
        else:
Nicola Gatto's avatar
Nicola Gatto committed
1128
            q_max_val = self._qnet(next_states)
1129

Nicola Gatto's avatar
Nicola Gatto committed
1130
1131
1132
1133
1134
        if self._double_dqn:
            q_values_next_states = self._qnet(next_states)
            target_rewards = rewards + nd.choose_element_0index(
                q_max_val, nd.argmax_channel(q_values_next_states))\
                * (1.0 - terminals) * self._discount_factor
1135
        else:
Nicola Gatto's avatar
Nicola Gatto committed
1136
1137
1138
            target_rewards = rewards + nd.choose_element_0index(
                q_max_val, nd.argmax_channel(q_max_val))\
                * (1.0 - terminals) * self._discount_factor
1139

Nicola Gatto's avatar
Nicola Gatto committed
1140
        target_qval = self._qnet(states)
1141
1142
1143
1144
1145
1146
        for t in range(target_rewards.shape[0]):
            target_qval[t][actions[t]] = target_rewards[t]

        return target_qval

    def __train_q_net_step(self, trainer):
Nicola Gatto's avatar
Nicola Gatto committed
1147
1148
1149
1150
        states, actions, rewards, next_states, terminals =\
            self._sample_from_memory()
        target_qval = self.__determine_target_q_values(
            states, actions, rewards, next_states, terminals)
1151
        with autograd.record():
Nicola Gatto's avatar
Nicola Gatto committed
1152
1153
            q_values = self._qnet(states)
            loss = self._loss_function(q_values, target_qval)
1154
        loss.backward()
Nicola Gatto's avatar
Nicola Gatto committed
1155
        trainer.step(self._minibatch_size)
1156
1157
1158
        return loss

    def __do_target_update_if_in_interval(self, total_steps):
Nicola Gatto's avatar
Nicola Gatto committed
1159
1160
1161
        do_target_update = (
            self._use_fix_target and
            (total_steps % self._target_update_interval == 0))
1162
        if do_target_update:
Nicola Gatto's avatar
Nicola Gatto committed
1163
1164
1165
1166
            self._logger.info(
                'Target network is updated after {} steps'.format(total_steps))
            self._target_qnet = copy_net(
                self._qnet, self._state_dim, self._ctx)
1167
1168

    def train(self, episodes=None):
Nicola Gatto's avatar
Nicola Gatto committed
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
        self.save_config_file()
        self._logger.info("--- Start training ---")
        trainer = gluon.Trainer(
            self._qnet.collect_params(),
            self._optimizer,
            self._adjust_optimizer_params(self._optimizer_params))
        episodes = episodes if episodes is not None\
            else self._training_episodes

        resume = (self._current_episode > 0)
1179
        if resume:
Nicola Gatto's avatar
Nicola Gatto committed
1180
1181
1182
            self._logger.info("Training session resumed")
            self._logger.info("Starting from episode {}".format(
                self._current_episode))
1183
        else:
Nicola Gatto's avatar
Nicola Gatto committed
1184
            self._training_stats = DqnTrainingStats(episodes)
1185

Nicola Gatto's avatar
Nicola Gatto committed
1186
1187
1188
1189
        # Implementation Deep Q Learning described by
        # Mnih et. al. in Playing Atari with Deep Reinforcement Learning
        while self._current_episode < episodes:
            if self._check_interrupt_routine():
1190
1191
1192
1193
1194
                return False

            step = 0
            episode_reward = 0
            start = time.time()
Nicola Gatto's avatar
Nicola Gatto committed
1195
            state = self._environment.reset()
1196
1197
            episode_loss = 0
            training_steps = 0
Nicola Gatto's avatar
Nicola Gatto committed
1198
1199
1200
1201
            while step < self._max_episode_step:
                # 1. Choose an action based on current game state and policy
                q_values = self._qnet(nd.array([state], ctx=self._ctx))
                action = self._strategy.select_action(q_values[0])
Nicola Gatto's avatar
Nicola Gatto committed
1202
                self._strategy.decay(self._current_episode)
1203

Nicola Gatto's avatar
Nicola Gatto committed
1204
1205
1206
                # 2. Play the game for a single step
                next_state, reward, terminal, _ =\
                    self._environment.step(action)
1207

Nicola Gatto's avatar
Nicola Gatto committed
1208
1209
                # 3. Store transition in replay memory
                self._memory.append(
Nicola Gatto's avatar
Nicola Gatto committed
1210
                    state, [action], reward, next_state, terminal)
1211

Nicola Gatto's avatar
Nicola Gatto committed
1212
1213
                # 4. Train the network if in interval
                if self._do_training():
1214
1215
                    loss = self.__train_q_net_step(trainer)
                    training_steps += 1
Nicola Gatto's avatar
Nicola Gatto committed
1216
1217
                    episode_loss +=\
                        np.sum(loss.asnumpy()) / self._minibatch_size
1218
1219

                # Update target network if in interval
Nicola Gatto's avatar
Nicola Gatto committed
1220
                self.__do_target_update_if_in_interval(self._total_steps)
1221
1222

                step += 1
Nicola Gatto's avatar
Nicola Gatto committed
1223
                self._total_steps += 1
1224
1225
1226
1227
                episode_reward += reward
                state = next_state

                if terminal:
Nicola Gatto's avatar
Nicola Gatto committed
1228
                    self._strategy.reset()
1229
1230
                    break

Nicola Gatto's avatar
Nicola Gatto committed
1231
            self._do_snapshot_if_in_interval(self._current_episode)
1232

Nicola Gatto's avatar
Nicola Gatto committed
1233
1234
1235
1236
1237
            episode_loss = (episode_loss / training_steps)\
                if training_steps > 0 else 0
            avg_reward = self._training_stats.log_episode(
                self._current_episode, start, training_steps,
                episode_loss, self._strategy.cur_eps, episode_reward)
1238

Nicola Gatto's avatar
Nicola Gatto committed
1239
1240
1241
            if self._is_target_reached(avg_reward):
                self._logger.info(
                    'Target score is reached in average; Training is stopped')
1242
1243
                break

Nicola Gatto's avatar
Nicola Gatto committed
1244
            self._current_episode += 1
1245

Nicola Gatto's avatar
Nicola Gatto committed
1246
1247
        self._evaluate()
        self.save_parameters(episode=self._current_episode)
Nicola Gatto's avatar
Nicola Gatto committed
1248
        self.export_best_network()
Nicola Gatto's avatar
Nicola Gatto committed
1249
1250
1251
        self._training_stats.save_stats(self._output_directory)
        self._logger.info('--------- Training finished ---------')
        return True
1252

Nicola Gatto's avatar
Nicola Gatto committed
1253
1254
1255
1256
1257
1258
1259
1260
    def _make_config_dict(self):
        config = super(DqnAgent, self)._make_config_dict()
        config['optimizer'] = self._optimizer
        config['optimizer_params'] = self._optimizer_params
        config['loss_function'] = self._loss_function_str
        config['use_fix_target'] = self._use_fix_target
        config['double_dqn'] = self._double_dqn
        config['target_update_interval'] = self._target_update_interval
1261
1262
        return config

Nicola Gatto's avatar
Nicola Gatto committed
1263
    def save_parameters(self, episode):
Nicola Gatto's avatar
Nicola Gatto committed
1264
1265
        self._export_net(
            self._qnet, self._agent_name + '_qnet', episode=episode)
Nicola Gatto's avatar
Nicola Gatto committed
1266
1267
1268

    def _save_current_as_best_net(self):
        self._best_net = copy_net(
Nicola Gatto's avatar
Nicola Gatto committed
1269
            self._qnet, self._state_dim, ctx=self._ctx)