atari_agent.py 6.1 KB
Newer Older
H
Hongsheng Zeng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import numpy as np
import paddle.fluid as fluid
B
Bo Zhou 已提交
17 18 19
import parl
from parl import layers
from parl.utils import machine_info
H
Hongsheng Zeng 已提交
20
from parl.utils.scheduler import PiecewiseScheduler, LinearDecayScheduler
H
Hongsheng Zeng 已提交
21 22


B
Bo Zhou 已提交
23
class AtariAgent(parl.Agent):
24
    def __init__(self, algorithm, config):
B
Bo Zhou 已提交
25 26 27
        """

        Args:
28 29
            algorithm (`parl.Algorithm`): algorithm to be used in this agent.
            config (dict): config file describing the training hyper-parameters(see a2c_config.py)
B
Bo Zhou 已提交
30 31
        """

32
        self.obs_shape = config['obs_shape']
H
Hongsheng Zeng 已提交
33 34
        super(AtariAgent, self).__init__(algorithm)

H
Hongsheng Zeng 已提交
35 36
        self.lr_scheduler = LinearDecayScheduler(config['start_lr'],
                                                 config['max_sample_steps'])
H
Hongsheng Zeng 已提交
37

B
Bo Zhou 已提交
38
        self.entropy_coeff_scheduler = PiecewiseScheduler(
39
            config['entropy_coeff_scheduler'])
H
Hongsheng Zeng 已提交
40 41 42 43 44 45 46 47 48

    def build_program(self):
        self.sample_program = fluid.Program()
        self.predict_program = fluid.Program()
        self.value_program = fluid.Program()
        self.learn_program = fluid.Program()

        with fluid.program_guard(self.sample_program):
            obs = layers.data(
B
Bo Zhou 已提交
49
                name='obs', shape=self.obs_shape, dtype='float32')
H
Hongsheng Zeng 已提交
50 51 52 53 54
            sample_actions, values = self.alg.sample(obs)
            self.sample_outputs = [sample_actions, values]

        with fluid.program_guard(self.predict_program):
            obs = layers.data(
B
Bo Zhou 已提交
55
                name='obs', shape=self.obs_shape, dtype='float32')
H
Hongsheng Zeng 已提交
56 57 58 59
            self.predict_actions = self.alg.predict(obs)

        with fluid.program_guard(self.value_program):
            obs = layers.data(
B
Bo Zhou 已提交
60
                name='obs', shape=self.obs_shape, dtype='float32')
H
Hongsheng Zeng 已提交
61 62 63 64
            self.values = self.alg.value(obs)

        with fluid.program_guard(self.learn_program):
            obs = layers.data(
B
Bo Zhou 已提交
65
                name='obs', shape=self.obs_shape, dtype='float32')
H
Hongsheng Zeng 已提交
66 67 68 69 70 71 72 73
            actions = layers.data(name='actions', shape=[], dtype='int64')
            advantages = layers.data(
                name='advantages', shape=[], dtype='float32')
            target_values = layers.data(
                name='target_values', shape=[], dtype='float32')
            lr = layers.data(
                name='lr', shape=[1], dtype='float32', append_batch_size=False)
            entropy_coeff = layers.data(
74 75 76 77
                name='entropy_coeff',
                shape=[1],
                dtype='float32',
                append_batch_size=False)
H
Hongsheng Zeng 已提交
78 79 80

            total_loss, pi_loss, vf_loss, entropy = self.alg.learn(
                obs, actions, advantages, target_values, lr, entropy_coeff)
81 82
            self.learn_outputs = [total_loss, pi_loss, vf_loss, entropy]
        self.learn_program = parl.compile(self.learn_program, total_loss)
H
Hongsheng Zeng 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

    def sample(self, obs_np):
        """
        Args:
            obs_np: a numpy float32 array of shape ([B] + observation_space).
                    Format of image input should be NCHW format.

        Returns:
            sample_ids: a numpy int64 array of shape [B]
            values: a numpy float32 array of shape [B]
        """
        obs_np = obs_np.astype('float32')

        sample_actions, values = self.fluid_executor.run(
            self.sample_program,
            feed={'obs': obs_np},
            fetch_list=self.sample_outputs)
        return sample_actions, values

    def predict(self, obs_np):
        """
        Args:
            obs_np: a numpy float32 array of shape ([B] + observation_space).
                    Format of image input should be NCHW format.

        Returns:
            sample_ids: a numpy int64 array of shape [B]
        """
        obs_np = obs_np.astype('float32')

        predict_actions = self.fluid_executor.run(
            self.predict_program,
            feed={'obs': obs_np},
            fetch_list=[self.predict_actions])[0]
        return predict_actions

    def value(self, obs_np):
        """
        Args:
            obs_np: a numpy float32 array of shape ([B] + observation_space).
                    Format of image input should be NCHW format.

        Returns:
            values: a numpy float32 array of shape [B]
        """
        obs_np = obs_np.astype('float32')

        values = self.fluid_executor.run(
            self.value_program, feed={'obs': obs_np},
            fetch_list=[self.values])[0]
        return values

    def learn(self, obs_np, actions_np, advantages_np, target_values_np):
        """
        Args:
            obs_np: a numpy float32 array of shape ([B] + observation_space).
                    Format of image input should be NCHW format.
            actions_np: a numpy int64 array of shape [B]
            advantages_np: a numpy float32 array of shape [B]
            target_values_np: a numpy float32 array of shape [B]
        """

        obs_np = obs_np.astype('float32')
        actions_np = actions_np.astype('int64')
        advantages_np = advantages_np.astype('float32')
        target_values_np = target_values_np.astype('float32')

H
Hongsheng Zeng 已提交
150
        lr = self.lr_scheduler.step(step_num=obs_np.shape[0])
H
Hongsheng Zeng 已提交
151 152
        entropy_coeff = self.entropy_coeff_scheduler.step()

153 154
        total_loss, pi_loss, vf_loss, entropy = self.fluid_executor.run(
            self.learn_program,
H
Hongsheng Zeng 已提交
155 156 157 158 159 160 161 162 163 164
            feed={
                'obs': obs_np,
                'actions': actions_np,
                'advantages': advantages_np,
                'target_values': target_values_np,
                'lr': np.array([lr], dtype='float32'),
                'entropy_coeff': np.array([entropy_coeff], dtype='float32')
            },
            fetch_list=self.learn_outputs)
        return total_loss, pi_loss, vf_loss, entropy, lr, entropy_coeff