Integrating Dirichlet Distribution into PPO in Stable Baselines3

I’m working with the Stable Baselines3 library to train a Proximal Policy Optimization (PPO) model for a reinforcement learning project. I want to integrate a Dirichlet distribution for action selection to make the sum of elements in the action vector equal to 1 rather than applying a softmax to the default agent’s action. By default, PPO uses Gaussian distribution in sb3.

I tried to achieve this by extending the PPO class and overwriting methods to include Dirichlet sampling for action probabilities. However, this approach hasn’t worked as expected. Here’s a snippet of what I tried:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import torch
import torch.nn as nn
import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.policies import ActorCriticPolicy
import numpy as np
class DirichletActorCriticPolicy(ActorCriticPolicy):
def __init__(self, *args, alpha=None, **kwargs):
super(DirichletActorCriticPolicy, self).__init__(*args, **kwargs)
self.alpha = 0.1
def action(self, obs):
logits = self.extract_features(obs)
probs = np.exp(logits) / np.exp(logits).sum(-1, keepdims=True)
action = np.random.dirichlet(self.alpha * probs.reshape(-1, 3))
return action, None
env = ToyDirichletEnv()
model = PPO(DirichletActorCriticPolicy, env, verbose=1)
print(model.policy)
model.learn(total_timesteps=50)
</code>
<code>import torch import torch.nn as nn import gymnasium as gym from stable_baselines3 import PPO from stable_baselines3.common.policies import ActorCriticPolicy import numpy as np class DirichletActorCriticPolicy(ActorCriticPolicy): def __init__(self, *args, alpha=None, **kwargs): super(DirichletActorCriticPolicy, self).__init__(*args, **kwargs) self.alpha = 0.1 def action(self, obs): logits = self.extract_features(obs) probs = np.exp(logits) / np.exp(logits).sum(-1, keepdims=True) action = np.random.dirichlet(self.alpha * probs.reshape(-1, 3)) return action, None env = ToyDirichletEnv() model = PPO(DirichletActorCriticPolicy, env, verbose=1) print(model.policy) model.learn(total_timesteps=50) </code>
import torch
import torch.nn as nn
import gymnasium as gym
from stable_baselines3 import PPO
from stable_baselines3.common.policies import ActorCriticPolicy
import numpy as np

class DirichletActorCriticPolicy(ActorCriticPolicy):
    def __init__(self, *args, alpha=None, **kwargs):
        super(DirichletActorCriticPolicy, self).__init__(*args, **kwargs)
        self.alpha = 0.1

    def action(self, obs):
        logits = self.extract_features(obs)
        probs = np.exp(logits) / np.exp(logits).sum(-1, keepdims=True)
        action = np.random.dirichlet(self.alpha * probs.reshape(-1, 3))
        return action, None

env = ToyDirichletEnv()
model = PPO(DirichletActorCriticPolicy, env, verbose=1)
print(model.policy)
model.learn(total_timesteps=50)

For debugging, I implemented a toy environment that plots the sum of the action to check if the sum is 1.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class ToyDirichletEnv(gym.Env):
def __init__(self):
super(ToyDirichletEnv, self).__init__()
self.action_space = gym.spaces.Box(low=0, high=1, shape=(3,), dtype=np.float32)
self.observation_space = gym.spaces.Box(low=np.array([0, 0, 0, 0]), high=np.array([10]*4), dtype=np.float32)
self.position = 5
def reset(self, seed=None):
self.position = 5
return np.array([self.position]*4).astype(np.float32), {}
def step(self, action):
print('sum0(action)', sum(action))
reward = sum([el**2 for el in action])
self.position += 1
done = False
if self.position > 15:
done = True
return np.array([self.position]*4).astype(np.float32), reward, done, done, {}
def render(self, mode='human'):
print(f"Position: {self.position}")
</code>
<code>class ToyDirichletEnv(gym.Env): def __init__(self): super(ToyDirichletEnv, self).__init__() self.action_space = gym.spaces.Box(low=0, high=1, shape=(3,), dtype=np.float32) self.observation_space = gym.spaces.Box(low=np.array([0, 0, 0, 0]), high=np.array([10]*4), dtype=np.float32) self.position = 5 def reset(self, seed=None): self.position = 5 return np.array([self.position]*4).astype(np.float32), {} def step(self, action): print('sum0(action)', sum(action)) reward = sum([el**2 for el in action]) self.position += 1 done = False if self.position > 15: done = True return np.array([self.position]*4).astype(np.float32), reward, done, done, {} def render(self, mode='human'): print(f"Position: {self.position}") </code>
class ToyDirichletEnv(gym.Env):
    def __init__(self):
        super(ToyDirichletEnv, self).__init__()
        self.action_space = gym.spaces.Box(low=0, high=1, shape=(3,), dtype=np.float32)
        self.observation_space = gym.spaces.Box(low=np.array([0, 0, 0, 0]), high=np.array([10]*4), dtype=np.float32)
        self.position = 5

    def reset(self, seed=None):
        self.position = 5
        return np.array([self.position]*4).astype(np.float32), {}

    def step(self, action):
        print('sum0(action)', sum(action))
        reward = sum([el**2 for el in action])
        self.position += 1
        done = False
        if self.position > 15:
            done = True
        return np.array([self.position]*4).astype(np.float32), reward, done, done, {}

    def render(self, mode='human'):
        print(f"Position: {self.position}")

It seems that it never gets inside the method.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật