RL

Here I will discover reinforcement learning basics.

drl ai with inteligencia artificial and Development|lower


DEEP RL LEARNING

0. You  can effectively train RL models on CPU.

1. What RL frameworks we have? Stable-BaselinМ, RL Baselines3 Zoo, CleanRL, ML-Agent (for Unity) and Sample Factory 2.0

1.0. Frameworks provide scripts for training, evaluating etc.

1.1. What enviroment libraries we have? gymnasium

2.0. To start enviroment visualization on local machine is enough to env = gym.make("your_enviroment_name_here", render_mode="human"); obs, info = env.reset()

2. If you use GoogleColab it is not that easy to visualize. How to visualize enviroment in gymnasium LunarLander in GoogleColab.

!pip install swig

!apt-get install -y python-opengl > /dev/null 2>&1

!apt-get install -y xvfb

!pip install gym pyvirtualdisplay > /dev/null 2>&1

!pip install gymnasium[box2d]

!pip install gym

 

import gym

import numpy as np

import matplotlib.pyplot as plt

from IPython import display as ipythondisplay

from pyvirtualdisplay import Display

 

display = Display(visible=0, size=(400, 300))

display.start()

env = gym.make("LunarLander-v2")

env.reset(seed=42)

prev_screen = env.render(mode='rgb_array')

plt.imshow(prev_screen)

for _ in range(1000):

action = env.action_space.sample()

observation, reward, terminated, info = env.step(action)

screen = env.render(mode='rgb_array')

plt.imshow(screen)

ipythondisplay.clear_output(wait=True)

ipythondisplay.display(plt.gcf())

if terminated: # or truncated:

env.reset()

ipythondisplay.clear_output(wait=True)

env.close()

2.1. Or you can record mp3 then show it.

from stable_baselines3.common.vec_env import VecVideoRecorder, DummyVecEnv

def record_video(env_id, model, video_length=500, prefix="", video_folder="videos/"):

eval_env = DummyVecEnv([lambda: gym.make(env_id, render_mode="rgb_array")])

eval_env = VecVideoRecorder(

eval_env,

video_folder=video_folder,

record_video_trigger=lambda step: step == 0,

video_length=video_length,

name_prefix=prefix, )

obs = eval_env.reset()

for _ in range(video_length):

action, _ = model.predict(obs)

obs, _, _, _ = eval_env.step(action)

eval_env.close()

record_video("CartPole-v1", model, video_length=500, prefix="ppo-cartpole")

 

import os

os.system("Xvfb :1 -screen 0 1024x768x24 &")

os.environ['DISPLAY'] = ':1'

import base64

from pathlib import Path

from IPython import display as ipythondisplay

def show_videos(video_path="", prefix=""):

html = []

for mp4 in Path(video_path).glob("{}*.mp4".format(prefix)):

video_b64 = base64.b64encode(mp4.read_bytes())

html.append(

"""<video alt="{}" autoplay 

loop controls style="height: 400px;">

<source src="data:video/mp4;base64,{}" type="video/mp4" />

</video>""".format(mp4, video_b64.decode("ascii")) )

ipythondisplay.display(ipythondisplay.HTML(data="<br>".join(html)))

3. To train an agent.

import gymnasium as gym

from stable_baselines3 import A2C

env = gym.make("LunarLander-v3", render_mode="rgb_array")

model = A2C("MlpPolicy", env, verbose=1)

model.learn(total_timesteps=10_000)

 

vec_env = model.get_env()

obs = vec_env.reset()

acc=0

for i in range(10000):

action, _state = model.predict(obs, deterministic=True)

obs, reward, terminated, info = vec_env.step(action)

acc += reward

vec_env.render("human")

if terminated:

print(reward," ", acc)

acc = 0

3.0. To save model.save(save_dir)

3.0.1. To load loaded_model = A2C.load(save_dir, verbose=1)

3.1. Training Lunar Lander for 10000 steps gives about 25% of landings (lr=0,0007).

3.2. Training Lunar Lander for 30000 steps gives about 30% of landings.

3.3. Training Lunar Lander for 100000 steps gives about 50% of landings.

3.4. Training Lunar Lander for 500000 steps gives only about 20% of landings. // I think it is because of a wrong reward policy. I need to train the agent not on current reward but on an accumulated reward. Model understood very well how to get next reward so it keeps LunaLander's velocity slow, it is not tiltting but it landed to the wrong place. Because the current reward policy doesn't motivate the agent to appreciate value of good landing to the landing position. // Actually it doesn't has any sence, learning process takes into account long term reward during training but with discount. You can increase final reward or decrease discount.

3.5. How to modify stable-baselines3 learning process?

3.5.1. Try to create wrapper and modify step() function there.

class MyMonitorWrapper(gym.Wrapper):

def __init__(self, env):

super().__init__(env)

def reset(self, **kwargs):

obs = self.env.reset(**kwargs)

return obs

def step(self, action):

obs, reward, terminated, truncated, info = self.env.step(action)

self.rew += reward

return obs, self.rew, terminated, truncated, info

wr_env = MyMonitorWrapper(gym.make("LunarLander-v3", render_mode="rgb_array"))

model = A2C("MlpPolicy", wr_env, verbose=1)

model.learn(total_timesteps=90_000)

3.5.1. Using accumulated reward for learning shows bad results. Try to experiment with policies.

3.5.2. Try to use MlpLstmPolicy with my accumulated reward. model = A2C("MlpLstmPolicy", wr_env, verbose=1) // Error is rised

3.5.3. Try to increase learning rate model = A2C("MlpPolicy", wr_env, verbose=1, learning_rate=0.007)

3.5.4. Try DDPG. from stable_baselines3 import DDPG // Doesn't suit for discrete actions like Lunar

3.5.5. Try to use initial reward with different lr to see if the overtrainig will happened again. Too big lr= 0.007 gives bad results, landing speed is too fast but it somehow solves problem with side bias.

3.5.5. lr= 0.001 with 200K training steps is quite good about 70% of landings.

3.5.6. 300K steps, lr=0.002, A2C. // Lander just flying.

3.5.7. Try gae_lambda=0.5, model = A2C("MlpPolicy", wr_env, verbose=1, learning_rate=0.002, gae_lambda=0.5) // 50%

3.5.8. Decrease gamma=0.8, model = A2C("MlpPolicy", wr_env, verbose=1, learning_rate=0.002, gae_lambda=0.5, gamma=0.8) // 60% but it moving fast and bouncing.

3.5.9. Decrease gamma=0.6, model = A2C("MlpPolicy", wr_env, verbose=1, learning_rate=0.002, gae_lambda=0.5, gamma=0.6) // 40% even faster and more bouncing.

3.5.10. Decrease gamma=0.9, model = A2C("MlpPolicy", wr_env, verbose=1, learning_rate=0.002, gae_lambda=0.5, gamma=0.9) // Flying

3.5.11. Actually then more gamma value then less discount S=R(j)+gamma*R(j+1)+gamma^2*R(j+3)+... That is why it usually 0.99

3.5.7. Try to increase landing reward from 100 to 300 and pin reward from 10 to 30. It gives about 70% with only 50K training steps. And very slow and precise landing.

3.5.8. Try to increase training steps to 100K (lr=0.001) // Doesn't move towards land at all just flying. Maybe I have to Increase reward for landing.

3.5.9. Try to increase landing reward from 300 to 500 and pin reward from 30 to 50. // Problem solved and accuracy around 80%. Landing is very smooth.

3.5.9. Increase steps to 150K. // Flying

3.5.10. Little bit increase landing reward from 500 to 600 and pin reward from 50 to 60. // Very good 90%

3.5.11. Increase steps to 200K. // Flying

3.5.10. Little bit increase landing reward from 600 to 700 and pin reward from 60 to 70. // Flying

4. While you are training RL it is good idea to start with small training amount and see if the model on that seed evolving in a right direction from the begining and if you find that seed increase amount of training steps.

5. Train with RL-Baselines3-Zoo rl_zoo3.train where yml file is placed. // In any folder just use parameter -c

$ python -m rl_zoo3.train --algo dqn  --env SpaceInvadersNoFrameskip-v4 -f logs/ -c dqn.yml

5.1. How to make mp3 file for RL-Baselines3-Zoo // $ python -m rl_zoo3.record_video --algo dqn --env SpaceInvadersNoFrameskip-v4 -n 1000 -f logs/

5.1.1 Get AssertionError: The rl-trained-agents/dqn folder was not found // -f logs/ $ python -m rl_zoo3.record_video --algo dqn --env SpaceInvadersNoFrameskip-v4 -n 1000 -f logs/

5.1.2. Set seed. $ python -m rl_zoo3.train --algo dqn  --env SpaceInvadersNoFrameskip-v4 -f logs/ -c dqn.yml --seed 777

ML-AGENTS

Installation

6. If you have a problem with using Unity's $ mlagents-learn like command not found in /usr/bash/ apparently the problem is your python version. Use virtualenv with python which ml-agent supports.

6.1. Check which Python version required by ML-Agents. Today it is 3.10.12.

7. $ git clone --branch release_22 https://github.com/Unity-Technologies/ml-agents.git and unpack.

!git clone --depth 1 https://github.com/Unity-Technologies/ml-agents

 

7.1. Actually you have to install this package com.unity.ml-agents with Unity interface Window - > Package Manager -> +.

7.2. Move to ml-agents folder.

7.3. Install from your virtual environment

pip install ./ml-agents-envs

pip install ./ml-agents

7.4. ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/lib/python3.10/site-packages/gym_notices'

7.5. Try $ pip3 install ./ml-agents-envs --user // Doesn't wors in virtual environment

7.6. Change permisions of venv $ sudo chmod -R a+rwx ~/venv-mlagent2 // Works

8. Got error ModuleNotFoundError: No module named '_ctypes' 

8.1. Try $ sudo apt-get install libffi-dev then reinstall python. // Helped.

9. To train $ mlagents-learn ./trainer_config.yaml --run-id hb_01

9.1. Error mlagents.trainers.exception.TrainerConfigError: The option default was specified in your YAML file, but is invalid.

9.2. yaml should have structure like below:

behaviors:

Hummingbird:

trainer_type: ppo

hyperparameters:

batch_size: 2048

buffer_size: 20480

learning_rate: 0.0003

beta: 0.005

epsilon: 0.2

lambd: 0.95

num_epoch: 3

learning_rate_schedule: linear

network_settings:

normalize: false

hidden_units: 256 #128

num_layers: 2

vis_encode_type: simple

memory:

        sequence_length: 64

        memory_size: 128

reward_signals:

extrinsic:

        gamma: 0.99

        strength: 1.0

keep_checkpoints: 5

max_steps: 2000000

time_horizon: 128

summary_freq: 10000

threaded: true

10. MLagent cannot connect to Unity. Error mlagents_envs.exception.UnityTimeOutException: The Unity environment took too long to respond. Make sure that :

The environment does not need user interaction to launch

The Agents' Behavior Parameters > Behavior Type is set to "Default"

The environment and the Python interface have compatible versions.

If you're running on a headless server without graphics support, turn off display by either passing --no-graphics option or build your Unity executable as server build.

10.1. I think it is because of incompatibility. I have to try latest Unity version with latest ML agents version.

 

 

Try to add reward for keeping LunarLander under the landing pod.

 

KAGGLE CONECT X COMPETITION

1. I want to build an RL agent which will beat heuristic agents and supervised trained agents.

2. Initially I started to train PPO model on heurisctic agent and get very good results within 800k training steps but I lost this model because didn't figured out how to submit an agent and how to use training for first and second player at the same time.

3. Then I started from scratch and started to train on "random" agent then on "negamax". I've trained about 1M steps but got really bad results. I think training on "random" is a bad idea bcs agent doesn't learn how to counter play in case of 3 items line (random unable to finish the line). 

3.1. Try to train only on heuristic opponent and increase learning_rate and decrease gae_lambda.

for param_group in model.policy.optimizer.param_groups:

    param_group['lr'] = 0.0003  # Replace with your desired learning rate

model.gae_lambda = 0.92  # Replace with your desired GAE lambda

3.2. Change of parameters doesn't help. NN seems to be stucked. I will start from scratch and will train 800K only on heurisctic agent with gamma=0.9, gae_lambda = 0.8, learning_rate=0.007

3.3. If model stuck try to set positive reward for action unlike reccomendations to make negative reward for each additional action. Maybe it is good to have positive when your model just started to learn and have bad results. But when your model is good enough you could change to negative.

4. Use punish in reward function for invalid moves. The most important thing is to build reward function. I've made a mistake when made punishment for invalid move less then punishment for loss. So my agent learned to make invalid move to escape loss.

4.1. I changed rewards and increased exploration parameter ent_coef // but it doesn't help.

4.2. Try to decrease n_steps = 512 or less. Be sure (n_steps * n_envs) % batch_size == 0. 

4.3. I've started new training from scratch. It was impossible to fix this bad habbit.

 

 

Create pool of opponents.