Skip to main content

Module qlearn

Module qlearn 

Source
Expand description

Q-learning, ported from tinymind (C++)’s qlearn.hpp: QLearner (QLearner with DefaultLearningPolicy and ArgMaxPolicy), its Q values in a QTable (QValueTablePolicy) or a QNetwork (QValueNeuralNetworkPolicy), and the Environment trait (what the C++ example environments derive from QLearningEnvironment and supply as policies).

The learner keeps a table of Q values, one per (state, action) pair, in the value type of your choice (Q16_16, Q8_8, f32, f64): a 6-state, 6-action Q16.16 table is 144 bytes. You describe the world through Environment: which actions are valid in a state, and a source of random integers for exploration. The loop that moves through the world is yours: ask the learner for an action, apply it, and report the reward and the new state.

The update is tinymind (C++)’s, operation for operation:

Q(s, a) = (1 - lr) * Q(s, a) + lr * (reward + discount * max_a' Q(s', a'))

for the experience’s own state s, where the maximum runs over the actions valid in the next state s' (0 if there are none): the greedy value, whatever the learner explores, so the table converges to the optimal Q values. Action selection explores with probability random_action_decision_point percent; otherwise it takes the action with the largest Q value, as tinymind (C++)’s ArgMaxPolicy does (the first of equal maxima), unless every valid action has the same Q value (an unvisited state), in which case a random valid action is taken.

use tinymind::qlearn::{Environment, Experience, QLearner};
use tinymind::rand::GlibcRand;
use tinymind::Q16_16;

// A corridor of 4 cells; action 0 moves left, 1 moves right; cell 3 is the goal.
struct Corridor(GlibcRand);

impl Environment<2> for Corridor {
    fn valid_actions(&self, _state: usize, actions: &mut [usize; 2]) -> usize {
        *actions = [0, 1];
        2
    }
    fn random_int(&mut self, min: usize, max: usize) -> usize {
        self.0.next_i32() as usize % (max + 1 - min) + min
    }
}

let rate = Q16_16::from_int(1) / Q16_16::from_int(5);
let discount = Q16_16::from_int(8) / Q16_16::from_int(10);
// Explore 100% of the time while learning.
let mut learner =
    QLearner::<Q16_16, Corridor, 4, 2>::new(Corridor(GlibcRand::new(7)), rate, discount, 100);
for _ in 0..200 {
    learner.start_new_episode();
    let mut state = 0;
    while state != 3 {
        let action = learner.take_action(state).unwrap();
        let next = if action == 0 { state.saturating_sub(1) } else { state + 1 };
        let reward = if next == 3 { Q16_16::ONE } else { Q16_16::ZERO };
        learner.update_from_experience(&Experience { state, action, reward, new_state: next });
        state = next;
    }
}
// Now exploit: from every cell the learner heads right.
learner.set_random_action_decision_point(0);
for cell in 0..3 {
    assert_eq!(learner.take_action(cell), Some(1));
}

§Deep Q-network

QNetwork (tinymind (C++)’s QValueNeuralNetworkPolicy) keeps the Q values in a MultilayerPerceptron instead of a table: the network maps a state, encoded as its input vector by a function you supply, to one Q value per action, so states that look alike share what they learn. Each update trains the network on the taken action’s target. The update’s lookahead reads a second, target network, a copy of the online one refreshed every so many training steps, which keeps the target from chasing its own updates. It is a drop-in replacement for the table: pass it to QLearner::with_q_values.

Structs§

Experience
One step’s outcome, reported to QLearner::update_from_experience (tinymind (C++)’s experience_t).
QLearner
A Q-learning agent over STATES states and ACTIONS actions (tinymind (C++)’s QLearner). It owns its Environment and its Q values (a QTable unless built with with_q_values).
QNetwork
Q values from a neural network: a deep Q-network (tinymind (C++)’s QValueNeuralNetworkPolicy), for QLearner::with_q_values.
QTable
A Q table, values[state][action] (tinymind (C++)’s QValueTablePolicy). Reading a state or action out of range gives 0 and writing one does nothing, as in the C++.

Traits§

Environment
The world a QLearner acts in: tinymind (C++)’s environment (the getValidActionsForState an example environment defines, and its random number policy’s randInt).
QValues
Where a QLearner keeps its Q values: tinymind (C++)’s Q value policy. QTable is the tabular one.