メインコンテンツへスキップ
見出し画像

Gymで強化学習㉟Atariゲーム環境:実装編

    前回はAtariゲームの環境を準備しました。今回は、Atariゲーム環境を使った深層強化学習を行うためのコードを実装を紹介します。

    フレームスタックでモノクロ画像を4枚重ねたものを入力画像として扱う畳み込みを導入しています。ネットワークの定義は基本的には、DeepMind の論文に従っています。

    では、さっそく始めましょう。

    Qネットワークの定義

    今回は、画像データを状態として扱うので、Qネットワークは畳み込みニューラルネットワーク(Convolutional Neural Network、CNN)を実装します。なお、畳み込みについてはこちらでも解説しているので参考にしてください。

    また、フレームスタックによってまとめられたモノクロ画像を扱うのでフレームの数が畳み込みにおける入力チャンネルの数になります。

    DQN

    Double DQNの論文「Deep Reinforcement Learning with Double Q-learning」によると、Qネットワークの構成は、以下になっています。

    特徴量抽出

    • 入力画像:84 x 84 x 4 (縦横84ピクセルで、チャンネル数は4)

    • 畳み込み:カーネル 8 x 8、ストライド 4、出力チャンネル 32

    • 活性化 :ReLU

    • 畳み込み:カーネル 4 x 4、ストライド 2、出力チャンネル 64

    • 活性化 :ReLU

    • 畳み込み:カーネル 3 x 3、ストライド 1、出力チャンネル 64

    • 活性化 :ReLU

    行動価値計算

    • 線形層 :ニューロンの数 512

    • 活性化 :ReLU

    • 線形層 :各アクションに対してQ値を計算

    最終的に画面のサイズは 7 x 7 まで縮小されるので、アクションの数を n_actions とすると、次のような PyTorch コードで表現できます。

    qnet = nn.Sequential(
        # 第一畳み込み
        nn.Conv2d(4, 32, 8, stride=4),
        nn.ReLU(),
    
        # 第二畳み込み
        nn.Conv2d(32, 64, 4, stride=2),
        nn.ReLU(),
    
        # 第三畳み込み
        nn.Conv2d(64, 64, 3, stride=1),
        nn.ReLU(),
    
        # フラット化
        nn.Flatten(),
    
        # 第一線形層
        nn.Linear(64 * 7 * 7, hidden),
        nn.ReLU(),
    
        # 第ニ線形層
        nn.Linear(512, n_actions)
    )

    ただし、隠れ状態のサイズなどを変更できるように、次のように QNetwork を定義しました。

    # Qネットワーク
    class QNetwork(nn.Module):
        # 初期化
        def __init__(self, n_frames: int, n_actions: int, hidden_size: int):
            # モジュールの初期化
            super().__init__()
    
            # Qネットワークの構築
            n_features = 7 * 7 * hidden_size
            self.net = nn.Sequential(
                nn.Conv2d(n_frames, hidden_size//2, kernel_size=8, stride=4),
                nn.ReLU(),
                nn.Conv2d(hidden_size//2, hidden_size, kernel_size=4, stride=2),
                nn.ReLU(),
                nn.Conv2d(hidden_size, hidden_size, kernel_size=3, stride=1),
                nn.ReLU(),
                nn.Flatten(),
                nn.Linear(n_features, 512),
                nn.ReLU(),
                nn.Linear(512, n_actions) # 各行動に対してそれぞれ価値を出力
            )
    
        # フィード・フォワード(順伝播で状態から各行動の価値を出力する)
        def forward(self, x: torch.Tensor):
            return self.net(x)

    Dueling DQN

    Dueling DQNの論文「Dueling Network Architectures for Deep Reinforcement Learning」によると、Qネットワークの構成はDQNと同様な構成を使っています。ただし、Dueling DQNでは状態価値と行動アドバンテージを計算するので実装が異なります。詳しくはこちらの記事を参考にしてください。

    特徴量抽出

    • 入力画像:84 x 84 x 4 (縦横84ピクセルで、チャンネル数は4)

    • 畳み込み:カーネル 8 x 8、ストライド 4、出力チャンネル 32

    • 活性化 :ReLU

    • 畳み込み:カーネル 4 x 4、ストライド 2、出力チャンネル 64

    • 活性化 :ReLU

    • 畳み込み:カーネル 3 x 3、ストライド 1、出力チャンネル 64

    • 活性化 :ReLU

    状態価値

    • 線形層 :ニューロンの数 512

    • 活性化 :ReLU

    • 線形層 :1つの状態価値を出力

    行動アドバンテージ

    • 線形層 :ニューロンの数 512

    • 活性化 :ReLU

    • 線形層 :各アクションに対してQ値を計算

    よって、デュエリングQネットワークは次のように定義しました。

    # Dueling Qネットワーク
    class DuelingQNetwork(nn.Module):
        # 初期化
        def __init__(self, n_frames: int, n_actions: int, hidden_size: int):
            # モジュールの初期化
            super().__init__()
    
            self.feature = nn.Sequential(
                nn.Conv2d(n_frames, hidden_size//2, kernel_size=8, stride=4),
                nn.ReLU(),
                nn.Conv2d(hidden_size//2, hidden_size, kernel_size=4, stride=2),
                nn.ReLU(),
                nn.Conv2d(hidden_size, hidden_size, kernel_size=3, stride=1),
                nn.ReLU(),
                nn.Flatten()
            )
    
            n_features = 7 * 7 * hidden_size
            self.value = nn.Sequential(
                nn.Linear(n_features, 512),
                nn.ReLU(),
                nn.Linear(512, 1)
            )
    
            self.advantage = nn.Sequential(
                nn.Linear(n_features, 512),
                nn.ReLU(),
                nn.Linear(512, n_actions)
            )
    
        def forward(self, x: torch.Tensor):
            feature   = self.feature(x)
            value     = self.value(feature)
            advantage = self.advantage(feature)
            return value + advantage - advantage.mean(dim=1, keepdim=True)

    経験再生メモリ

    経験再生メモリは、以前に使ったものを流用しています。今回は、SumTreeベースの優先度管理しか使っていません。Double DQNの論文で再生メモリのサイズが 1,000,000 (100万)だったので、それを採用しました。

    また、今回は、主にDueling DQNで実験したので、その論文から以下の優先度に関するパラメータ設定を使いました。

    • アルファ:0.7

    • ベータ :0.5 to 1

    設定クラス

    いろいろな設定が可能になるようにYAMLファイルから設定を読むようにしています。そのために次のクラスを定義しました。

    # 設定クラス
    @dataclass
    class Config:
        # 環境とモデル
        type: str
        env_name: str
        device: str
        frame_skip: int # 何フレームごとに行動を決定するか
        n_frames: int   # フレームスタック数
    
        # 画像の切り出し位置(上下左右)
        image_crop: Tuple[int, int, int, int]
    
        # モデルの構造
        hidden_size: int
    
        # 訓練
        n_seeds: int
        max_steps: int
        lr: float
        batch_size: int
        weight_decay: float # L2正則化
        amsgrad: bool
        gradient_clip: float
    
        # 報酬のクリッピングと終了ペナルティ
        reward_clip: float
        reward_scale: float
        termination_penalty: float
        terminal_on_life_loss: bool
    
        # 経験再生メモリ
        memory_size: int
        priority: str
        priority_alpha: float
        priority_beta_min: float
        priority_beta_max: float
    
        # イプシロン貪欲法
        start_steps: int
        epsilon_steps: int
        epsilon_max: float
        epsilon_min: float
    
        # 割引率
        gamma: float
    
        # ターゲットネットワークの更新頻度
        target_update_steps: int
        target_update_tau: float
    
        # 評価
        test_steps: int
        test_max_episodes: int
    
        def __str__(self):
            # 設定を文字列にして返す
            return str(self.__dict__)
    
        @property
        def use_double_dqn(self):
            # Double DQNを使うかどうか
            return 'double' in self.type
        
        @property
        def use_dueling_dqn(self):
            # Dueling DQNを使うかどうか
            return 'dueling' in self.type
    
        def epsilon(self, step: int):
            # イプシロンを線形に減衰させる
            if step < self.start_steps:
                return self.epsilon_max
            elif step < self.start_steps + self.epsilon_steps:
                return self.epsilon_max - (self.epsilon_max - self.epsilon_min) * (step - self.start_steps) / self.epsilon_steps
            else:
                return self.epsilon_min
        
        def priority_beta(self, step: int):
            # 重要度サンプリングの重みを調節するベータを線形に増加させる
            return self.priority_beta_min + (self.priority_beta_max - self.priority_beta_min) * step / self.max_steps
    
        def save(self, save_path: str):
            # 設定を保存する
            with open(save_path, "w") as f:
                yaml.dump(self.__dict__, f)

    これは優先度管理の実験の時に使ったコードに多少改良を加えたものです。

    画像処理におけるフレームスキップやフレームスタックなどの設定ができるように項目を増やしています。

    カスタム AtariProcessing

    全体登場した AtariProcessing に改良を加えて画像の切り取りができるようにしたものを準備しました。

    class CustomAtariPreprocessing(gym.wrappers.AtariPreprocessing):
        def __init__(self, env, 
                     top: int, bottom: int, left: int, right: int, **kwargs):
            super().__init__(env, **kwargs)
            self.top = top
            self.bottom = bottom
            self.left = left
            self.right = right
    
        def _get_obs(self):
            if self.frame_skip > 1:  # more efficient in-place pooling
                np.maximum(self.obs_buffer[0], self.obs_buffer[1],
                           out=self.obs_buffer[0])
            assert cv2 is not None
            obs = cv2.resize(
                self.obs_buffer[0][self.top:-self.bottom, self.left:-self.right],
                (self.screen_size, self.screen_size),
                interpolation=cv2.INTER_AREA,
            )
    
            if self.scale_obs:
                obs = np.asarray(obs, dtype=np.float32) / 255.0
            else:
                obs = np.asarray(obs, dtype=np.uint8)
    
            if self.grayscale_obs and self.grayscale_newaxis:
                obs = np.expand_dims(obs, axis=-1)  # Add a channel axis
            return obs

    まず、初期設定の部分で上下左右(top, bottom, left, right)の切り取り部を指定できるようにしています。

    class CustomAtariPreprocessing(gym.wrappers.AtariPreprocessing):
        def __init__(self, env, top: int, bottom: int, left: int, right: int, **kwargs):
            super().__init__(env, **kwargs)
            self.top = top
            self.bottom = bottom
            self.left = left
            self.right = right

    また、AtariProcessing の _get_obs メソッドを上書きしています。このメソッドは、フレームスキップの最後の二つのフレームからの最大値を取り出し、パラメータによってピクセルの値を 0 から 1 に標準化したりしています。

    上書きしたメソッドは基本的には同じコードですが、画像のサイズを調節する部分だけ改良を加えています。以下は、その部分の元のコードです。

            obs = cv2.resize(
                self.obs_buffer[0],
                (self.screen_size, self.screen_size),
                interpolation=cv2.INTER_AREA,
            )

    これを次のように改造しました。

            obs = cv2.resize(
                self.obs_buffer[0][self.top:-self.bottom, self.left:-self.right],
                (self.screen_size, self.screen_size),
                interpolation=cv2.INTER_AREA,
            )
    

    self.obs_buffer[0] にはフレームスキップの最後の二つのフレームからの最大値を取り出したものが入っています。それに対して、上下左右のオフセットを指定して画像の切り取りをしています。よって、元の画像から切り取られたものが cv2.resize によってサイズ調整されています。

    下図は、AtariProcessing でグレースケール化して、84 x 84 にサイズ調整したものです。

    画像
    通常の AtariProcessing によって処理されたもの

    このように、切り取りを行わないと画面の上下左右に全く使われない領域があります。

    画像
    不要な領域

    これに対してカスタムの AtariProcessing で上下左右を切り取ってからサイズ調整した場合は、以下のようになります。

    画像
    カスタム AtariProcessing で切り取ったもの

    また、このカスタム AtariProcessing を使って環境生成を行うファンクションも定義しました。

    def make_env(config: Config,
                 no_render: bool=True,
                 is_train: bool=False) -> gym.Env:
        # 環境を作成
        env = gym.make(
            config.env_name,
            render_mode="human" if not no_render else None,
            frameskip=1, # AtariPreprocessingとの重複を避ける
        )
    
        # 環境をラップする
        # ライフが減ったときに終了するかどうかは訓練時のみ
        terminal_on_life_loss = is_train and config.terminal_on_life_loss
        if config.image_crop is not None:
            env = CustomAtariPreprocessing(env,
                scale_obs=True, # データを255で割って正規化
                terminal_on_life_loss=terminal_on_life_loss,
                **config.image_crop,
            )
        else:
            env = AtariPreprocessing(env,
                scale_obs=True, # データを255で割って正規化
                terminal_on_life_loss=terminal_on_life_loss,
                frame_skip=config.frame_skip,
            )
        env = FrameStack(env, config.n_frames) # 複数のフレームを一つの観測・状態として使う
        return env

    設定オブジェクト config で image_crop を指定した場合にカスタム AtariProcessing が使われます。

    このような改良が良い結果を出すのかどうかも実験しました。

    ソースコードの実行

    ソースコード

    import argparse
    import copy
    import cv2
    import gymnasium as gym
    import logging
    import numpy as np
    import os
    import pandas as pd
    import random
    import time
    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    import yaml
    from dataclasses import dataclass
    from gymnasium.wrappers import AtariPreprocessing, FrameStack
    from typing import List, Tuple, Union
    
    
    logging.basicConfig(level=logging.INFO, format="%(message)s")
    logger = logging.getLogger(__name__)
    
    
    # Qネットワーク
    class QNetwork(nn.Module):
        # 初期化
        def __init__(self, n_frames: int, n_actions: int, hidden_size: int):
            # モジュールの初期化
            super().__init__()
    
            # Qネットワークの構築
            n_features = 7 * 7 * hidden_size
            self.net = nn.Sequential(
                nn.Conv2d(n_frames, hidden_size//2, kernel_size=8, stride=4),
                nn.ReLU(),
                nn.Conv2d(hidden_size//2, hidden_size, kernel_size=4, stride=2),
                nn.ReLU(),
                nn.Conv2d(hidden_size, hidden_size, kernel_size=3, stride=1),
                nn.ReLU(),
                nn.Flatten(),
                nn.Linear(n_features, 512),
                nn.ReLU(),
                nn.Linear(512, n_actions) # 各行動に対してそれぞれ価値を出力
            )
    
        # フィード・フォワード(順伝播で状態から各行動の価値を出力する)
        def forward(self, x: torch.Tensor):
            return self.net(x)
    
    
    # Dueling Qネットワーク
    class DuelingQNetwork(nn.Module):
        # 初期化
        def __init__(self, n_frames: int, n_actions: int, hidden_size: int):
            # モジュールの初期化
            super().__init__()
    
            self.feature = nn.Sequential(
                nn.Conv2d(n_frames, hidden_size//2, kernel_size=8, stride=4),
                nn.ReLU(),
                nn.Conv2d(hidden_size//2, hidden_size, kernel_size=4, stride=2),
                nn.ReLU(),
                nn.Conv2d(hidden_size, hidden_size, kernel_size=3, stride=1),
                nn.ReLU(),
                nn.Flatten()
            )
    
            n_features = 7 * 7 * hidden_size
            self.value = nn.Sequential(
                nn.Linear(n_features, 512),
                nn.ReLU(),
                nn.Linear(512, 1)
            )
    
            self.advantage = nn.Sequential(
                nn.Linear(n_features, 512),
                nn.ReLU(),
                nn.Linear(512, n_actions)
            )
    
        def forward(self, x: torch.Tensor):
            feature   = self.feature(x)
            value     = self.value(feature)
            advantage = self.advantage(feature)
            return value + advantage - advantage.mean(dim=1, keepdim=True)
    
    
    # 経験再生メモリ
    class ReplayMemory:
        def __init__(self, capacity: int):
            self.capacity = capacity
            self.experiences = np.empty(capacity, dtype=object)
            self.index = 0
            self.size = 0
    
        def __len__(self) -> int:
            return self.size
    
        def add(self, *experience):
            # 現在のインデックスに経験データを保存
            self.experiences[self.index] = experience
    
            # メモリのインデックスを1つ進める
            self.index = (self.index + 1) % self.capacity
            self.size = min(self.size + 1, self.capacity)
            
        def sample(self, batch_size: int) -> np.ndarray:
            # バッチサイズ分の経験データをランダムに取得
            indices = np.random.choice(self.size, batch_size)
            return self.experiences[indices]
    
    
    # 優先度管理(NumPy使用)
    class PrioritiesWithNumPy:
        def __init__(self, capacity: int):
            # ツリーの初期化
            self.capacity = capacity
            self.priorities = np.zeros(capacity)
    
        # 優先度を更新する
        def add(self, index: int, priority: float):
            self.priorities[index] = priority
    
        def sample(self, batch_size: int) -> Tuple[np.ndarray, np.ndarray]:
            # 優先度に応じて確率分布を計算
            probabilities = self.priorities / self.priorities.sum()
    
            # バッチサイズ分の経験インデックスを確率分布に従って取得
            indices = np.random.choice(self.capacity, batch_size, p=probabilities)
            return indices, probabilities[indices]
    
        # 優先度をまとめて更新する
        def update(self, indices: np.ndarray, priorities: np.ndarray) -> float:
            # 優先度を更新する
            self.priorities[indices] = priorities
    
            # 優先度の最大値を返す
            return self.priorities.max()
    
    
    # 優先度管理(SumTree使用)
    class PrioritiesWithSumTree:
        def __init__(self, capacity: int):
            # 全ノードの初期化
            n_leafs = 1
            while n_leafs < capacity:
                n_leafs *= 2
            self.capacity = n_leafs
            self.nodes = np.zeros(2 * self.capacity - 1)
    
        # 優先度を更新する
        def add(self, index: int, priority: float):
            self._propagate(index, priority)
    
        def sample(self, batch_size: int) -> Tuple[np.ndarray, np.ndarray]:
            # 優先度の合計をバッチサイズ分の区間に分割して、各区間内から優先度をランダムに選択する
            total_priority = self.nodes[0]
            boundaries = np.linspace(0, total_priority, batch_size + 1)
            random_cumsum = np.random.uniform(boundaries[:-1], boundaries[1:])
    
            # 得られた優先度から経験データのインデックスを取得してバッチを作成する
            indices = np.array([self.index(cumsum) for cumsum in random_cumsum])
    
            # 優先度を確率に変換する
            probabilities = self.nodes[self.capacity - 1 + indices] / total_priority
            return indices, probabilities
                
        def update(self, indices: np.ndarray, priorities: np.ndarray) -> float:
            # 優先度を更新する
            for index, priority in zip(indices, priorities):
                self._propagate(index, priority)
    
            # 優先度の最大値を返す
            return self.nodes[self.capacity - 1:].max()
    
        def _propagate(self, index: int, priority: float):
            # 優先度をツリーの葉に保存
            pos = self.capacity - 1 + index
            change = priority - self.nodes[pos]
            self.nodes[pos] = priority
    
            # 値の変化をルートに到達するまで親のノードに伝播する
            pos = (pos - 1) // 2
            while pos >= 0:
                self.nodes[pos] += change
                pos = (pos - 1) // 2
    
        # 優先度に応じてインデックスを取得する
        def index(self, cumsum: float) -> int:
            # ルートから枝葉に向かって優先度を比較していく
            pos = 0
            while True:
                # 子のノードのインデックスを計算
                left  = 2 * pos + 1
                right = left + 1
    
                # 左の子のインデックスがツリーの長さを超えたら終了
                if left >= len(self.nodes):
                    break
    
                if cumsum <= self.nodes[left]:
                    # 左の子の優先度が目的の優先度より大きい場合は左の子を選択
                    pos = left
                else:
                    # 右の子を選択を選択した場合は優先度から左の子の優先度を引く
                    pos = right
                    cumsum -= self.nodes[left]
    
            # 枝葉のインデックスをデータのインデックスにして返す
            return pos - (self.capacity - 1)
        
    
    # 優先度付き経験再生メモリ
    class PrioritizedReplayMemory:
        def __init__(self,
                     priorities: Union[PrioritiesWithNumPy, PrioritiesWithSumTree],
                     alpha: float,
                     beta: float):
    
            # 経験再生メモリ
            self.capacity     = priorities.capacity # 優先度管理の容量と同じ
            self.experiences  = np.empty(priorities.capacity, dtype=object)
            self.index        = 0
            self.size         = 0
        
            # 優先度関連
            self.priorities   = priorities # 優先度管理
            self.alpha        = alpha
            self.beta         = beta
            self.max_priority = 1.0e-6
    
        def __len__(self) -> int:
            return self.size
    
        def add(self, *experience):
            # 現在のインデックスに経験データを保存
            self.experiences[self.index] = experience
            self.priorities.add(self.index, self.max_priority)
    
            # メモリのインデックスを1つ進める
            self.index = (self.index + 1) % self.capacity
            self.size = min(self.size + 1, self.capacity)
            
        def sample(self, batch_size: int) -> np.ndarray:
            # 優先度に応じて確率分布を計算
            indices, probabilities = self.priorities.sample(batch_size)
    
            # 重要度サンプリングの重みを計算
            weights = (self.size * probabilities)**(-self.beta)
            weights = weights / weights.max()
    
            # あとで使うのでインデックスと重みを保存しておく
            self.indices = indices
            self.weights = weights.astype(np.float32)
    
            return self.experiences[indices]
    
        def update(self, priorities: np.ndarray):
            # 優先度を更新する(alpha乗する)
            priorities = priorities**self.alpha
            self.max_priority = self.priorities.update(self.indices, priorities)
        
    
    # 設定クラス
    @dataclass
    class Config:
        # 環境とモデル
        type: str
        env_name: str
        device: str
        frame_skip: int # 何フレームごとに行動を決定するか
        n_frames: int   # フレームスタック数
    
        # 画像の切り出し位置(上下左右)
        image_crop: Tuple[int, int, int, int]
    
        # モデルの構造
        hidden_size: int
    
        # 訓練
        n_seeds: int
        max_steps: int
        lr: float
        batch_size: int
        weight_decay: float # L2正則化
        amsgrad: bool
        gradient_clip: float
    
        # 報酬のクリッピングと終了ペナルティ
        reward_clip: float
        reward_scale: float
        termination_penalty: float
        terminal_on_life_loss: bool
    
        # 経験再生メモリ
        memory_size: int
        priority: str
        priority_alpha: float
        priority_beta_min: float
        priority_beta_max: float
    
        # イプシロン貪欲法
        start_steps: int
        epsilon_steps: int
        epsilon_max: float
        epsilon_min: float
    
        # 割引率
        gamma: float
    
        # ターゲットネットワークの更新頻度
        target_update_steps: int
        target_update_tau: float
    
        # 評価
        test_steps: int
        test_max_episodes: int
    
        def __str__(self):
            # 設定を文字列にして返す
            return str(self.__dict__)
    
        @property
        def use_double_dqn(self):
            # Double DQNを使うかどうか
            return 'double' in self.type
        
        @property
        def use_dueling_dqn(self):
            # Dueling DQNを使うかどうか
            return 'dueling' in self.type
    
        def epsilon(self, step: int):
            # イプシロンを線形に減衰させる
            if step < self.start_steps:
                return self.epsilon_max
            elif step < self.start_steps + self.epsilon_steps:
                return self.epsilon_max - (self.epsilon_max - self.epsilon_min) * (step - self.start_steps) / self.epsilon_steps
            else:
                return self.epsilon_min
        
        def priority_beta(self, step: int):
            # 重要度サンプリングの重みを調節するベータを線形に増加させる
            return self.priority_beta_min + (self.priority_beta_max - self.priority_beta_min) * step / self.max_steps
    
        def save(self, save_path: str):
            # 設定を保存する
            with open(save_path, "w") as f:
                yaml.dump(self.__dict__, f)
    
    
    class CustomAtariPreprocessing(gym.wrappers.AtariPreprocessing):
        def __init__(self, env, top: int, bottom: int, left: int, right: int, **kwargs):
            super().__init__(env, **kwargs)
            self.top = top
            self.bottom = bottom
            self.left = left
            self.right = right
    
        def _get_obs(self):
            if self.frame_skip > 1:  # more efficient in-place pooling
                np.maximum(self.obs_buffer[0], self.obs_buffer[1], out=self.obs_buffer[0])
            assert cv2 is not None
            obs = cv2.resize(
                self.obs_buffer[0][self.top:-self.bottom, self.left:-self.right],
                (self.screen_size, self.screen_size),
                interpolation=cv2.INTER_AREA,
            )
    
            if self.scale_obs:
                obs = np.asarray(obs, dtype=np.float32) / 255.0
            else:
                obs = np.asarray(obs, dtype=np.uint8)
    
            if self.grayscale_obs and self.grayscale_newaxis:
                obs = np.expand_dims(obs, axis=-1)  # Add a channel axis
            return obs
    
    
    def make_env(config: Config, no_render: bool=True, is_train: bool=False) -> gym.Env:
        # 環境を作成
        env = gym.make(
            config.env_name,
            render_mode="human" if not no_render else None,
            frameskip=1, # AtariPreprocessingとの重複を避ける
        )
    
        # 環境をラップする
        # ライフが減ったときに終了するかどうかは訓練時のみ
        terminal_on_life_loss = is_train and config.terminal_on_life_loss
        if config.image_crop is not None:
            env = CustomAtariPreprocessing(env,
                scale_obs=True, # データを255で割って正規化
                terminal_on_life_loss=terminal_on_life_loss,
                **config.image_crop,
            )
        else:
            env = AtariPreprocessing(env,
                scale_obs=True, # データを255で割って正規化
                terminal_on_life_loss=terminal_on_life_loss,
                frame_skip=config.frame_skip,
            )
        env = FrameStack(env, config.n_frames) # 複数のフレームを一つの観測・状態として使う
        return env
    
    
    # デバイスを作成する
    def make_device(device_name: str) -> torch.device:
        if device_name != "":
            device = torch.device(device_name)
        elif torch.cuda.is_available():
            device = torch.device("cuda")
        elif torch.backends.mps.is_available():
            device = torch.device("mps")
        else:
            device = torch.device("cpu")
        return device
    
    
    # Qネットワークを作成する
    def make_q_network(env: gym.Env, config: Config) -> nn.Module:
        assert config.type in ["dqn", "double", "dueling", "dueling-double"]
    
        n_action = env.action_space.n
    
        if config.use_dueling_dqn:
            q_network = DuelingQNetwork(config.n_frames, n_action, config.hidden_size)
        else:
            q_network = QNetwork(config.n_frames, n_action, config.hidden_size)
        return q_network
    
    
    # 経験再生メモリを作成する
    def make_replay_memory(config: Config) -> Union[ReplayMemory, PrioritizedReplayMemory]:
        assert config.priority in ["none", "numpy", "numpy2", "sumtree"]
    
        if config.priority == "none":
            # 優先度なし経験再生メモリ
            memory = ReplayMemory(config.memory_size)
        else:
            # 優先度管理
            if config.priority == "numpy":
                priorities = PrioritiesWithNumPy(config.memory_size)
            elif config.priority == "sumtree":
                priorities = PrioritiesWithSumTree(config.memory_size)
            else:
                raise ValueError(f"不正な優先度管理: {config.priority}")
    
            # 優先度付き経験再生メモリ
            memory = PrioritizedReplayMemory(
                priorities,
                config.priority_alpha,
                config.priority_beta_min)
        return memory
    
    
    # 訓練
    def train(
        experiment: str,
        config: Config,
        seed: int,
        best_reward: float,
        model_save_path: str) -> Tuple[float, List[float]]:
    
        # 環境を作成する
        env = make_env(config, is_train=True)
        set_seed(env, seed)
    
        # ポリシーネットワーク
        policy_network = make_q_network(env, config)
    
        # ターゲットネットワーク
        target_network = copy.deepcopy(policy_network)
    
        # デバイスを作成する
        device = make_device(config.device)
    
        # デバイスに転送する
        policy_network.to(device)
        target_network.to(device)
    
        logger.info(f"{experiment}, シード: {seed}, Device: {device}")
    
        # 最適化器
        optimizer = torch.optim.AdamW(policy_network.parameters(),
                                      lr=config.lr,
                                      weight_decay=config.weight_decay,
                                      amsgrad=config.amsgrad)
    
        # 経験再生メモリ
        memory = make_replay_memory(config)
    
        # 環境を初期化する
        observation, info = env.reset(seed=seed)
        start_time = time.time()
    
        n_episodes = 1
        train_losses = []
        test_rewards = []
    
        # 訓練ループ
        for step in range(1, config.max_steps+1):
    
            # スタートステップに達するまではランダムに行動する。
            # その後は、イプシロン貪欲法で行動を選択する
            epsilon = config.epsilon(step)
            if np.random.rand() < epsilon:
                # ランダムに行動する
                action = env.action_space.sample()
            else:
                # ポリシーネットワークを使って行動を選択する
                with torch.no_grad():
                    state = torch.from_numpy(np.array(observation)).to(device)
                    q_values = policy_network(state.unsqueeze(0))
                    action = q_values.argmax().cpu().item()
    
            # 行動を実行して、次の状態と報酬を観測する
            next_observation, reward, terminated, truncated, info = env.step(action)
            if terminated and config.termination_penalty != 0:
                reward = config.termination_penalty # エピソードが終了したらペナルティを与える
            else:
                if config.reward_scale > 0:
                    reward *= config.reward_scale
                if config.reward_clip > 0:
                    reward = np.clip(reward, -config.reward_clip, config.reward_clip)
    
            # 経験再生メモリに保存する
            done = int(terminated)
            memory.add(observation, action, reward, next_observation, done)
            observation = next_observation
    
            # スタートステップに達したら学習する
            if step >= config.start_steps:
                # 経験再生メモリを使って学習する。
                if len(memory) >= config.batch_size:
                    # 重要度サンプリングの重みを調節するベータを更新する
                    if type(memory) == PrioritizedReplayMemory:
                        memory.beta = config.priority_beta(step)
    
                    # ポリシーネットワークを更新する
                    loss = optimize_policy_network(
                        policy_network, target_network, config.use_double_dqn,
                        memory, config.batch_size, config.gamma, config.gradient_clip,
                        optimizer, device)
                    train_losses.append(loss)
    
                    # ターゲットネットワークを更新する
                    if config.target_update_tau > 0 or step % config.target_update_steps == 0:
                        update_target_network(policy_network, target_network, config.target_update_tau)
    
                # テストを実行する
                if step % config.test_steps == 0:
                    elapsed_time = time.time() - start_time
    
                    # ポリシーネットワークを評価する
                    rewards = evaluate_policy_network(config, policy_network, seed, device)
                    test_rewards.append(rewards)
    
                    # ポリシーネットワークの性能が最も良いモデルを保存する
                    mean_reward = np.mean(rewards)
                    if mean_reward > best_reward:
                        best_reward = mean_reward
                        best_model = copy.deepcopy(policy_network).cpu()
                        torch.save(best_model.state_dict(), model_save_path)
                        best_mark = "!"
                    else:
                        best_mark = " "
    
                    # ログを出力する
                    log_message = f"Episode: {n_episodes:06d} Step: {step:07d} Epsilon: {epsilon:.5f} " \
                        f"Mean Reward: {mean_reward:7.2f}{best_mark}(Std: {np.std(rewards):6.2f}) " \
                        f"Mean Loss: {np.mean(train_losses):8.4f} Elapsed Time: {elapsed_time:6.2f} sec"
                    logger.info(log_message)
    
                    # 次回に備えて変数を初期化する
                    start_time = time.time()
                    train_losses = []
    
            # エピソードが終了したら環境を初期化する
            if terminated or truncated:
                n_episodes += 1
                observation, info = env.reset(seed=seed+n_episodes)
    
        return best_reward, np.transpose(test_rewards) # (評価テスト内のエピソード数, 評価テストの回数)    
    
    
    def optimize_policy_network(
        policy_network: nn.Module,
        target_network: nn.Module,
        use_double_dqn: bool,
        memory: Union[ReplayMemory, PrioritizedReplayMemory],
        batch_size: int,
        gamma: float,
        gradient_clip: float,
        optimizer: torch.optim.Optimizer,
        device: torch.device) -> float:
        # ポリシーネットワークを更新する
    
        # バッチを取得する
        batch = memory.sample(batch_size)
        states, actions, rewards, next_states, dones = zip(*batch)
        states      = torch.from_numpy(np.array(states,      dtype=np.float32)).to(device)
        actions     = torch.from_numpy(np.array(actions,     dtype=np.int64  )).to(device)
        rewards     = torch.from_numpy(np.array(rewards,     dtype=np.float32)).to(device)
        next_states = torch.from_numpy(np.array(next_states, dtype=np.float32)).to(device)
        dones       = torch.from_numpy(np.array(dones,       dtype=np.int64  )).to(device)
    
        # Q値を計算する
        q_values = policy_network(states)
        q_values = q_values.gather(1, actions.unsqueeze(1)).flatten()
    
        # Q値のターゲットを計算する
        with torch.no_grad():
            if use_double_dqn:
                # ポリシーネットワークを使って次の行動を選択する
                next_actions = policy_network(next_states).argmax(dim=1, keepdim=True)
    
                # ターゲットネットワークを使ってQ値を計算する
                q_next = target_network(next_states).gather(1, next_actions).flatten()
            else:
                # ターゲットネットワークを使ってQ値を計算する
                q_next = target_network(next_states).max(dim=1)[0]
        
        q_targets = rewards + gamma * (1 - dones) * q_next
    
        # 損失を計算する
        if type(memory) == PrioritizedReplayMemory:
            # 重要度サンプリングの重みを適用する
            weights = torch.from_numpy(memory.weights).to(device)
            loss = torch.mean((q_values - q_targets)**2 * weights)
        else:
            # 通常の二乗誤差を計算する
            loss = torch.mean((q_values - q_targets)**2)
    
        # ポリシーネットワークを更新する
        optimizer.zero_grad()
        loss.backward()
        if gradient_clip > 0:
            nn.utils.clip_grad_norm_(policy_network.parameters(), gradient_clip)
        optimizer.step()
    
        # 優先度を更新する
        if type(memory) == PrioritizedReplayMemory:
            td_error = (q_values - q_targets).detach().cpu().numpy().flatten()
            priorities = np.abs(td_error) + 1.0e-6
            memory.update(priorities)
    
        return loss.item()
    
    
    def update_target_network(policy_network: nn.Module, target_network: nn.Module, tau: float):
        # ターゲットネットワークを更新する
        if tau > 0:
            # ポリシーネットワークのパラメータをターゲットネットワークに少しずつコピーする
            target_state_dict = target_network.state_dict()
            policy_state_dict = policy_network.state_dict()
    
            for key in policy_state_dict:
                target_state_dict[key] = policy_state_dict[key]*tau + target_state_dict[key]*(1-tau)
    
            target_network.load_state_dict(target_state_dict)
        else:
            # ポリシーネットワークのパラメータを定期的にターゲットネットワークにコピーする
            target_network.load_state_dict(policy_network.state_dict())
    
    
    # ポリシーネットワークを評価する
    def evaluate_policy_network(
        config: Config,
        policy_network: nn.Module,
        seed: int,
        device: torch.device) -> List[float]:
    
        # 新しくGym環境を作成してシードを設定する
        env = make_env(config, is_train=False)
    
        # エピソードの報酬を記録する
        rewards = []
        for episode in range(config.test_max_episodes):
            total_reward = 0
    
            # 環境を初期化する
            observation, _ = env.reset(seed=seed+episode)
            while True:
                # ポリシーネットワークを使って行動を選択する
                with torch.no_grad():
                    state = torch.from_numpy(np.array(observation)).to(device)
                    q_values = policy_network(state.unsqueeze(0))
                    action = q_values.argmax().cpu().item()
    
                # 行動を実行して、次の状態と報酬を観測する
                observation, reward, terminated, truncated, _ = env.step(action)
                total_reward += reward
    
                if terminated or truncated:
                    break
    
            # エピソードの報酬を記録する
            rewards.append(total_reward)
    
        # エピソードの報酬の平均と標準偏差を計算する
        return rewards
    
    
    def set_seed(env, seed=0):
        # Gym環境のシードを設定する
        env.action_space.seed(seed)
        
        # NumPyなどのシードを設定する
        random.seed(seed)
        np.random.seed(seed)
    
        # PyTorchのシードを設定する
        torch.manual_seed(seed)
    
        if torch.cuda.is_available():
            # CUDAのシードを設定する
            torch.cuda.manual_seed(seed)
            torch.backends.cudnn.deterministic = True
            torch.backends.cudnn.benchmark     = False
        elif torch.backends.mps.is_available():
            # MPSのシードを設定する
            torch.mps.manual_seed(seed)
    
    
    def main():
        # 引数の設定
        parser = argparse.ArgumentParser()
        parser.add_argument("experiments_path", type=str, help="path to experiments.yml")
        parser.add_argument("experiment_name" , type=str, help="experiment in experiments.yml")
        parser.add_argument("--device"        , type=str, default="")
        args = parser.parse_args()
    
        # 設定を読み込む
        with open(args.experiments_path) as f:
            experiments = yaml.safe_load(f)
    
        assert args.experiment_name in experiments, \
               f"experiment '{args.experiment_name}' is not found in {args.experiments_path}"
    
        # ベースと実験ごとの設定をマージする
        settings = experiments["base"]
        settings.update(experiments[args.experiment_name])
        config = Config(**settings)
    
        if args.device != "":
            config.device = args.device
    
        # 実行結果を保存するディレクトリを作成する
        runs_dir = "runs-" + os.path.basename(args.experiments_path).replace(".yaml", "")
        os.makedirs(runs_dir, exist_ok=True)
    
        # 設定を保存
        config_save_path = os.path.join(runs_dir, "config." + args.experiment_name + ".yaml")
        config.save(config_save_path)
    
        # ロガーを設定する
        log_path = os.path.join(runs_dir, "run." + args.experiment_name + ".log")
        logger.addHandler(logging.FileHandler(log_path))
        logger.info(config)
    
        # 複数回実行
        test_rewards = []
        model_save_path = os.path.join(runs_dir, "model." + args.experiment_name + ".pth")
        best_reward = 0
        for seed in range(config.n_seeds):
            best_reward, rewards = train(args.experiment_name, config, seed, best_reward, model_save_path)
            test_rewards.extend(rewards)
    
        # 結果を保存する
        results_df = pd.DataFrame(test_rewards)
        results_df.columns = list(range(config.start_steps, config.max_steps+1, config.test_steps))
        
        result_save_path = os.path.join(runs_dir, "results." + args.experiment_name + ".csv")
        results_df.to_csv(result_save_path, index=False)
    
    
    if __name__ == "__main__":
        main()
    

    Python環境の設定

    また、以下の依存関係を requirements.txt ファイルにセーブしてください。

    gymnasium[atari,accept-rom-license,other]==0.28.1
    matplotlib==3.7.2
    opencv-python==4.8.0.76
    pandas==2.0.3
    tensorboard==2.13.0
    torch==2.0.1
    PyYAML==6.0

    なお、Atari のROMを使うためにはライセンスを受け入れる必要があります。これは前回に解説したので読んでいな方は必ず目を通してください。

    そして、次のようにPythonの環境を有効にしてください。

    # フォルダを作る
    mkdir atari-rl
    cd atari-rl
    
    #Pythonの環境を作る
    python3 -m venv venv
    source venv/bin/activate
    
    # Pipを最新のものにしておく
    pip install --upgrade pip
    
    # 依存関係をインストールする
    pip install -r requirements.txt

    Python環境の準備は以上となります。

    実行する際に二つのパラメータを指定する必要があります。

    usage: train.py [-h] [--device DEVICE] experiments_path experiment_name
    
    positional arguments:
      experiments_path  path to experiments.yml
      experiment_name   experiment in experiments.yml
    
    options:
      -h, --help        show this help message and exit
      --device DEVICE

    一つ目(experiments_path)は、実験するための設定ファイルのパスです。二つ目(experiment_name)は、設定ファイルの中の設定の名前です。

    以下は、設定ファイルの例です。

    base:
      # 環境とモデル
      env_name: "ALE/SpaceInvaders-v5"
      device: ""
      frame_skip: 4
      n_frames: 4
      image_crop: null
    
      # モデル
      hidden_size: 64
    
      # 訓練
      n_seeds: 1
      max_steps: 5000000
      lr: 2.5e-4 # 学習率
      batch_size: 32
      weight_decay: 0.001 # L2正則化
      amsgrad: true
      gradient_clip: 10
    
      reward_clip: 1 # 報酬のクリッピング
      reward_scale: 0 # 報酬のスケーリング
      termination_penalty: -1 # 終了ペナルティ
      terminal_on_life_loss: false # ライフが減ったら終了
    
      # 経験再生メモリ
      memory_size: 1000000
      priority: "none"
      priority_alpha: 0.7
      priority_beta_min: 0.5
      priority_beta_max: 1.0
    
      # イプシロン貪欲法
      start_steps: 50000
      epsilon_steps: 1000000
      epsilon_max: 1.0
      epsilon_min: 0.1
    
      # 割引率
      gamma: 0.99
    
      # ターゲットネットワークの更新頻度
      target_update_steps: 10000
      target_update_tau: 0.0
    
      # 評価
      test_steps: 10000
      test_max_episodes: 10
      
    dqn-none:
      type: dqn
      priority: none
    
    dqn-numpy:
      type: dqn
      priority: numpy
    
    dqn-sumtree:
      type: dqn
      priority: sumtree
    
    double-none:
      type: double
      priority: none
    
    double-numpy:
      type: double
      priority: numpy
    
    double-sumtree:
      type: double
      priority: sumtree
    
    dueling-double-none:
      type: dueling-double
      priority: none
      lr: 6.25e-5
    
    dueling-double-numpy:
      type: dueling-double
      priority: numpy
      lr: 6.25e-5
    
    dueling-double-sumtree:
      type: dueling-double
      priority: sumtree
      lr: 6.25e-5

    例えば、この設定を experiments1.yaml に保存したとします。そして、SumTree を使った Dueling DQN を使う場合は次のように指定します。

    python train.py experiments1.yaml dueling-double-sumtree

    この設定では、最大ステップ数が500万なのでかなりの時間がかかります。NVIDIAのGPUが使える環境を使った方が実行速度が速くなる。使えるデバイスは自動的に判断されます。Apple シリコンのマシンでは自動で MPS を使うようになっています。なお、NVIDIA の GPU が複数ある場合に、どのデバイスを使いたいのか指定する場合は、以下のように行います。

    python train.py experiments1.yaml dueling-double-sumtree --device cuda:1

    デバイス名が、cuda:0 と cuda:1 となっていることを想定して cuda:1 を指定したい場合は上記のように指定します。

    ちなみに、Double DQNの論文によると最大ステップ数は、5,000万なので、この設定ではその10分の1となっています。

    上述の設定ファイルでいくつかの言及しておきたい点があります。

    乱数シード

    • n_seeds は、1に設定してあります。

    • よって、シートは0のみで実験します。

    • こうする理由は、最大ステップ数が多いので時間がいくらあっても足りないからです。

    学習率

      lr: 2.5e-4 # 学習率
    • デフォルトの学習率(lr)は、2.5e-4 です。これはダブルDQNの論文に従っています。

    • ただし、Dueling DQN に関しては、6.25e-5とより小さくなっています。これは、Dueling DQNの論文に従っています。

    例えば、dueling-double-sumtree の設定を見てください。

    dueling-double-sumtree:
      type: dueling-double
      priority: sumtree
      lr: 6.25e-5

    なお、小さい理由は、Dueling DQNのQネットワークの方がパラメータ数が多いので、小さい学習率を使うことで全体としてのパラメータ変更が大きな影響を与えすぎないようにしているためと考えられます。

    経験再生メモリ

      # 経験再生メモリ
      memory_size: 1000000
      priority: "none"
      priority_alpha: 0.7
      priority_beta_min: 0.5
      priority_beta_max: 1.0
    • 経験再生メモリのサイズは、100万です。

    • デフォルトでは優先度管理なしですが、実際にはSumTreeベースの優先度を使って実験しています。

    • 前述したようにアルファは、0.7を指定しています。また、ベータは、0.5 から 1.0 へと上昇するようになっています。

    勾配クリップ

      gradient_clip: 10
    • 勾配のクリップは10に設定されています。これはDueling DQNの論文に従いました。

    報酬クリッピング・スケーリング

      reward_clip: 1 # 報酬のクリッピング
      reward_scale: 0 # 報酬のスケーリング
    • 報酬のクリッピングは、DQNの論文に従い、最大が1になるように設定しています。Space Invaders では、UFOを倒すと200ポイントなのでそのままだと勾配にも大きすぎる影響があるからです。ただし、この設定だと普通のエイリアンを倒すのと区別がないのでUFOであるシグナルとしては弱すぎる可能性があります。

    • 報酬補スケーリングは、私が独自で追加した機能です。例えば、0.05 などと指定すると報酬を 5% に(つまり、95%オフ)にします。こうするとUFOの報酬は普通のエイリアンより相対的には大きくなり、しかも勾配に対する影響も抑えられる、という予測のもと追加しました。

    終了ペナルティ

    
      termination_penalty: -1 # 終了ペナルティ
      terminal_on_life_loss: false # ライフが減ったら終了
    • termination_penaltyは、エピソード終了時にペナルティとして与える値を設定しています。

    • terminal_on_life_lossは、AttariProcessing の設定です。true を指定するとゲーム終了ではなくライフが減ったら終了となります。なお、termination_penalty を使う場合は、terminal_on_life_loss が true だとライフが減った時にエピソード終了となりペナルティが与えられます。

    イプシロン

      # イプシロン貪欲法
      start_steps: 50000
      epsilon_steps: 1000000
      epsilon_max: 1.0
      epsilon_min: 0.1
    • イプシロンは、最初の5万ステップは、低減なしとなっています。

    • 5万ステップ以降の100万ステップ(つまり、105万ステップまで)は、最大値のエプシロンから最小値のエプシロンへとステップごとにステップごとに低減していきます。

    • 最小値に到達するとそのまま固定となります。

    ターゲットの更新頻度

      # ターゲットネットワークの更新頻度
      target_update_steps: 10000
      target_update_tau: 0.0
    • ターゲットネットワークの更新方法は、デフォルトで 10,000(1万)ステップに一回、ポリシーネットワークをコピーするようになっています。これは、Double DQNの論文に従っています。

    • なお、target_update_tau を指定すると一定の割合で毎回更新します(ソフト更新)。


    以上です。

    次回予告

    今回は、Atariゲーム環境における DQN、Double DQN、Dueling DQN の実装を紹介しました。次回は、いくつかの実験を通して異なる設定による影響を観察します。

    お楽しみに!

    (続く)

     
     
    「わかりやすく、具体的に」AIとサイエンスの情報を発信

    あなたへのおすすめ