Agent.ftl 34.8 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

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
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
        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._logger = None
        self._environment.close()
        self._environment = None
        self._save_net(self._best_net, 'best_net', session_dir)
        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):
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        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

    def _save_parameters(self, net, episode=None, filename='dqn-agent-params'):
        assert self._output_directory
        assert isinstance(net, gluon.HybridBlock)
        make_directory_if_not_exist(self._output_directory)

        if(episode is not None):
            self._logger.info(
                'Saving model parameters after episode %d' % episode)
            filename = filename + '-ep{}'.format(episode)
        else:
            self._logger.info('Saving model parameters')
        self._save_net(net, filename)

    def _save_net(self, net, filename, filedir=None):
        filedir = self._output_directory if filedir is None else filedir
276
277
        filename = os.path.join(filedir, filename)
        net.save_parameters(filename + '.params')
278
        net.export(filename, epoch=0)
Nicola Gatto's avatar
Nicola Gatto committed
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
372
373
374
375

    def save_best_network(self, path, epoch=0):
        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)
376
377
        self._save_net(self._actor, 'current_actor')

Nicola Gatto's avatar
Nicola Gatto committed
378
379
380
381
382
383
384
385
        self._save_net(self._actor, 'actor', session_dir)
        self._actor = None
        self._save_net(self._critic, 'critic', session_dir)
        self._critic = None
        self._save_net(self._actor_target, 'actor_target', session_dir)
        self._actor_target = None
        self._save_net(self._critic_target, 'critic_target', session_dir)
        self._critic_target = None
386
387

    @classmethod
Nicola Gatto's avatar
Nicola Gatto committed
388
    def resume_from_session(cls, session_dir, actor, critic, environment):
389
390
391
392
393
394
395
        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
396
397
398
399
400
401
        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')
402
403
404

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

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

Nicola Gatto's avatar
Nicola Gatto committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
        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'])
426

Nicola Gatto's avatar
Nicola Gatto committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440
        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')
441
442
443

        return agent

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

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

Nicola Gatto's avatar
Nicola Gatto committed
451
452
    def save_parameters(self, episode):
        self._save_parameters(self._actor, episode=episode)
453

Nicola Gatto's avatar
Nicola Gatto committed
454
455
456
457
458
    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
459

Nicola Gatto's avatar
Nicola Gatto committed
460
461
462
463
464
465
466
        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)
467

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

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

Nicola Gatto's avatar
Nicola Gatto committed
475
476
477
478
479
480
481
        # 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)
482

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

Nicola Gatto's avatar
Nicola Gatto committed
489
490
491
492
493
494
495
496
            # 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
497

Nicola Gatto's avatar
Nicola Gatto committed
498
499
500
501
502
503
504
505
506
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
            # 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))

                # 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():
                        actor_qvalues = tmp_critic(states, self._actor(states))
                        # For maximizing qvalues we have to multiply with -1
                        # as we use a minimizer
                        actor_loss = -1 * actor_qvalues
                    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 +=\
                        np.sum(actor_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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
                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)
            self._strategy.decay(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.save_best_network(os.path.join(self._output_directory, 'best'))
        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
621

Nicola Gatto's avatar
Nicola Gatto committed
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
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
    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)


class DqnAgent(Agent):
    def __init__(
        self,
        qnet,
        environment,
        replay_memory_params,
        strategy_params,
        state_dim,
        action_dim,
        ctx=None,
        discount_factor=.9,
        loss_function='euclidean',
        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
693

Nicola Gatto's avatar
Nicola Gatto committed
694
695
696
        # Initialize best network
        self._best_net = copy_net(self._qnet, self._state_dim, self._ctx)
        self._best_avg_score = -np.infty
697

Nicola Gatto's avatar
Nicola Gatto committed
698
        self._training_stats = None
699

Nicola Gatto's avatar
Nicola Gatto committed
700
701
702
703
704
    @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')
705

Nicola Gatto's avatar
Nicola Gatto committed
706
707
708
709
710
711
        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')
712

Nicola Gatto's avatar
Nicola Gatto committed
713
714
715
716
717
        for file in files.values():
            if not os.path.exists(file):
                raise ValueError(
                    'Session directory is not complete: {} is missing'
                    .format(file))
718

Nicola Gatto's avatar
Nicola Gatto committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
        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)
743
        self._save_net(self._qnet, 'current_qnet')
Nicola Gatto's avatar
Nicola Gatto committed
744
745
746
747
        self._save_net(self._qnet, 'qnet', session_dir)
        self._qnet = None
        self._save_net(self._target_qnet, 'target_net', session_dir)
        self._target_qnet = None
748
749

    def get_q_values(self, state, with_best=False):
Nicola Gatto's avatar
Nicola Gatto committed
750
751
        return self.get_batch_q_values(
            nd.array([state], ctx=self._ctx), with_best=with_best)[0]
752
753

    def get_batch_q_values(self, state_batch, with_best=False):
Nicola Gatto's avatar
Nicola Gatto committed
754
755
        return self._best_net(state_batch)\
            if with_best else self._qnet(state_batch)
756
757
758
759

    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
760
        return action
761

Nicola Gatto's avatar
Nicola Gatto committed
762
763
764
765
766
    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)
767
        else:
Nicola Gatto's avatar
Nicola Gatto committed
768
            q_max_val = self._qnet(next_states)
769

Nicola Gatto's avatar
Nicola Gatto committed
770
771
772
773
774
        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
775
        else:
Nicola Gatto's avatar
Nicola Gatto committed
776
777
778
            target_rewards = rewards + nd.choose_element_0index(
                q_max_val, nd.argmax_channel(q_max_val))\
                * (1.0 - terminals) * self._discount_factor
779

Nicola Gatto's avatar
Nicola Gatto committed
780
        target_qval = self._qnet(states)
781
782
783
784
785
786
        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
787
788
789
790
        states, actions, rewards, next_states, terminals =\
            self._sample_from_memory()
        target_qval = self.__determine_target_q_values(
            states, actions, rewards, next_states, terminals)
791
        with autograd.record():
Nicola Gatto's avatar
Nicola Gatto committed
792
793
            q_values = self._qnet(states)
            loss = self._loss_function(q_values, target_qval)
794
        loss.backward()
Nicola Gatto's avatar
Nicola Gatto committed
795
        trainer.step(self._minibatch_size)
796
797
798
        return loss

    def __do_target_update_if_in_interval(self, total_steps):
Nicola Gatto's avatar
Nicola Gatto committed
799
800
801
        do_target_update = (
            self._use_fix_target and
            (total_steps % self._target_update_interval == 0))
802
        if do_target_update:
Nicola Gatto's avatar
Nicola Gatto committed
803
804
805
806
            self._logger.info(
                'Target network is updated after {} steps'.format(total_steps))
            self._target_qnet = copy_net(
                self._qnet, self._state_dim, self._ctx)
807
808

    def train(self, episodes=None):
Nicola Gatto's avatar
Nicola Gatto committed
809
810
811
812
813
814
815
816
817
818
        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)
819
        if resume:
Nicola Gatto's avatar
Nicola Gatto committed
820
821
822
            self._logger.info("Training session resumed")
            self._logger.info("Starting from episode {}".format(
                self._current_episode))
823
        else:
Nicola Gatto's avatar
Nicola Gatto committed
824
            self._training_stats = DqnTrainingStats(episodes)
825

Nicola Gatto's avatar
Nicola Gatto committed
826
827
828
829
        # 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():
830
831
832
833
834
                return False

            step = 0
            episode_reward = 0
            start = time.time()
Nicola Gatto's avatar
Nicola Gatto committed
835
            state = self._environment.reset()
836
837
            episode_loss = 0
            training_steps = 0
Nicola Gatto's avatar
Nicola Gatto committed
838
839
840
841
            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])
842

Nicola Gatto's avatar
Nicola Gatto committed
843
844
845
                # 2. Play the game for a single step
                next_state, reward, terminal, _ =\
                    self._environment.step(action)
846

Nicola Gatto's avatar
Nicola Gatto committed
847
848
849
                # 3. Store transition in replay memory
                self._memory.append(
                    state, action, reward, next_state, terminal)
850

Nicola Gatto's avatar
Nicola Gatto committed
851
852
                # 4. Train the network if in interval
                if self._do_training():
853
854
                    loss = self.__train_q_net_step(trainer)
                    training_steps += 1
Nicola Gatto's avatar
Nicola Gatto committed
855
856
                    episode_loss +=\
                        np.sum(loss.asnumpy()) / self._minibatch_size
857
858

                # Update target network if in interval
Nicola Gatto's avatar
Nicola Gatto committed
859
                self.__do_target_update_if_in_interval(self._total_steps)
860
861

                step += 1
Nicola Gatto's avatar
Nicola Gatto committed
862
                self._total_steps += 1
863
864
865
866
                episode_reward += reward
                state = next_state

                if terminal:
Nicola Gatto's avatar
Nicola Gatto committed
867
                    self._strategy.reset()
868
869
                    break

Nicola Gatto's avatar
Nicola Gatto committed
870
            self._do_snapshot_if_in_interval(self._current_episode)
871

Nicola Gatto's avatar
Nicola Gatto committed
872
873
874
875
876
            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)
877

Nicola Gatto's avatar
Nicola Gatto committed
878
            self._strategy.decay(self._current_episode)
879

Nicola Gatto's avatar
Nicola Gatto committed
880
881
882
            if self._is_target_reached(avg_reward):
                self._logger.info(
                    'Target score is reached in average; Training is stopped')
883
884
                break

Nicola Gatto's avatar
Nicola Gatto committed
885
            self._current_episode += 1
886

Nicola Gatto's avatar
Nicola Gatto committed
887
888
889
890
891
892
        self._evaluate()
        self.save_parameters(episode=self._current_episode)
        self.save_best_network(os.path.join(self._output_directory, 'best'))
        self._training_stats.save_stats(self._output_directory)
        self._logger.info('--------- Training finished ---------')
        return True
893

Nicola Gatto's avatar
Nicola Gatto committed
894
895
896
897
898
899
900
901
    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
902
903
        return config

Nicola Gatto's avatar
Nicola Gatto committed
904
905
906
907
908
909
    def save_parameters(self, episode):
        self._save_parameters(self._qnet, episode=episode)

    def _save_current_as_best_net(self):
        self._best_net = copy_net(
            self._qnet, (1,) + self._state_dim, ctx=self._ctx)