bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Value iteration on FrozenLake

Policy iteration on FrozenLake solved FrozenLake with policy iteration. This example solves it with value iteration,

and then plays the policy it finds. The environment is the 4x4 FrozenLake from Gymnasium, made with is_slippery set to false, so every action moves the agent where it was meant to. It runs on the bitrl-rest-api server, which the example talks to over HTTP at http://0.0.0.0:8001/api, so start the server first.

Value iteration

Policy iteration alternates between evaluating a policy and improving it. Value iteration folds the two into one update. It sweeps over the states and replaces the value of each with the value of its best action,

\[V(s) \leftarrow \max_{\alpha} \sum_{s', r} p(s', r | s, \alpha) \left[ r + \gamma V(s') \right], \]

until a sweep changes no value by more than a tolerance. The policy is then read off the value function: in each state, take the action with the largest expected return. Like policy iteration, it needs the transition probabilities and rewards of the environment, which FrozenLake provides.

ValueIteration uses \(\gamma = 0.99\) and a tolerance of \(10^{-8}\). It updates the values in place, so a state later in a sweep already sees the new values of the states before it. The example runs the sweeps itself, at most 10000 of them, rather than with RLSerialAgentTrainer, so that it can write the value function after every sweep to sweeps.csv, and stops as soon as a sweep changes no value by more than the tolerance, after 7 sweeps.

What it writes

In the directory it runs from, the example writes

File What
value_iteration_frozen_lake_v1.csv the value of each state
reward_per_itr.csv for each sweep, the largest change of a value in it. ValueIteration reports it as the reward of the episode, so that the trainer keeps it
policy.csv the greedy policy, the action to take in each state

plot.py draws the value function on the grid of the lake and the largest change per sweep. play.py plays the policy in Gymnasium and draws each step. Both read the files from the directory they run in, or from the path given as their argument:

python plot.py <directory of the csv files>
python play.py <directory of the csv files>/policy.csv

play.py needs the gymnasium Python package with its toy text environments.

The results

The agent starts in the top left corner, the goal is in the bottom right, and the four cyan squares with a value of 0 are the holes. The goal itself also has a value of 0: the episode ends there, so no rewards come after it. Reaching the goal is the only reward, 1, so the value of a state is \(\gamma^{n-1}\), where \(n\) is the number of steps from it to the goal. The start is 6 steps away and has a value of \(0.99^5 \approx 0.951\).

Figure 1: The state value function.

The value function sweep by sweep, with the greedy actions of the values.

On the lake that does not slip, each sweep carries the value of the goal one more step back, so 6 sweeps reach the start and the 7th changes nothing. The GIF is made with

python examples/tools/value_gif.py sweeps.csv --gamma 0.99 --out value_iteration.gif

The policy reaches the goal in those 6 steps, the shortest path around the holes.

Figure 2: Playing FrozenLake, step 1.

Figure 3: Step 2.

Figure 4: Step 3.

Figure 5: Step 4.

Figure 6: Step 5.

Figure 7: Step 6, the goal.

The driver code

#include <fstream>
#include <tuple>
#include <vector>
namespace example_14
{
const std::string SERVER_URL = "http://0.0.0.0:8001/api";
const std::string SOLUTION_FILE = "value_iteration_frozen_lake_v1.csv";
const std::string REWARD_PER_ITR = "reward_per_itr.csv";
const std::string POLICY = "policy.csv";
// the environment to use
typedef FrozenLake<4> env_type;
// value iteration solver
typedef ValueIteration<env_type> solver_type;
} // namespace example_14
int main()
{
BITRL_LOG_INFO << "Starting agent training";
using namespace example_14;
RESTRLEnvClient server(SERVER_URL, true);
// create the environment
env_type env(server);
BITRL_LOG_INFO << "Creating environment...";
std::unordered_map<std::string, std::any> options;
options["is_slippery"] = std::any(false);
std::unordered_map<std::string, std::any> reset_options;
env.make("v1", options, reset_options);
env.reset();
BITRL_LOG_INFO << "Done...";
config.gamma = 0.99;
config.tolerance = 1.0e-8;
solver_type algorithm(config);
// the sweeps, as RLSerialAgentTrainer would run them, keeping the value
// function after every one in sweeps.csv, which examples/tools/value_gif.py
// draws
std::ofstream sweeps("sweeps.csv");
std::vector<real_t> reward;
algorithm.actions_before_training_begins(env);
for (uint_t sweep = 0; sweep < 10000; ++sweep)
{
const auto sweep_info = algorithm.on_training_episode(env, sweep);
reward.push_back(sweep_info.episode_reward);
const auto values = algorithm.value_function();
sweeps << sweep;
for (Eigen::Index s = 0; s < values.size(); ++s)
{
sweeps << "," << values[s];
}
sweeps << "\n";
if (sweep_info.stop_training)
{
break;
}
}
algorithm.actions_after_training_ends(env);
BITRL_LOG_INFO << "Done after " << reward.size() << " sweeps";
BITRL_LOG_INFO << "Saving solution to " << SOLUTION_FILE;
// save the value function into a csv file
algorithm.save(SOLUTION_FILE);
// save the reward the agent achieved per training epoch
csv_writer.open();
csv_writer.write_column_names({"epoch", "reward"});
auto epoch = static_cast<uint_t>(0);
for (auto val : reward)
{
std::tuple<uint_t, real_t> row = {epoch++, val};
csv_writer.write_row(row);
}
csv_writer.close();
// build the policy
algorithm.build_policy(env).save(POLICY);
BITRL_LOG_INFO << "Finished agent training";
return 0;
}
bitrl's logging: the logger of bitsim, bitsim/utils/logger.h, with bitrl's messages going to the logg...
#define BITRL_LOG_INFO
Definition bitrl_log.h:36
Definition frozen_lake_env.h:104
Utility class to facilitate HTTP requests between the environments REST API and C++ drivers.
Definition rest_rl_env_client.h:28
Definition rl_serial_agent_trainer.h:41
ValueIteration class.
Definition value_iteration.h:36
The CSVWriter class. Handles writing into CSV file format.
Definition csv_file_writer.h:22
int main()
Definition discounted_returns.cpp:19
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
Definition value_iteration.cpp:15
ValueIteration< env_type > solver_type
Definition value_iteration.cpp:36
const std::string POLICY
Definition value_iteration.cpp:20
const std::string SERVER_URL
Definition value_iteration.cpp:17
const std::string REWARD_PER_ITR
Definition value_iteration.cpp:19
const std::string SOLUTION_FILE
Definition value_iteration.cpp:18
FrozenLake< 4 > env_type
Definition value_iteration.cpp:33
reward
Definition play.py:49
The RLSerialTrainerConfig struct. Configuration struct for the serial RL agent trainer.
Definition rl_serial_agent_trainer.h:29
The ValueIterationConfig struct.
Definition value_iteration.h:26
real_t tolerance
Definition value_iteration.h:28
real_t gamma
Definition value_iteration.h:27