tinymind/qlearn.rs
1//! Q-learning, ported from tinymind (C++)'s `qlearn.hpp`: [`QLearner`]
2//! (`QLearner` with `DefaultLearningPolicy` and `ArgMaxPolicy`), its Q values
3//! in a [`QTable`] (`QValueTablePolicy`) or a [`QNetwork`]
4//! (`QValueNeuralNetworkPolicy`), and the [`Environment`] trait (what the C++
5//! example environments derive from `QLearningEnvironment` and supply as
6//! policies).
7//!
8//! The learner keeps a table of Q values, one per (state, action) pair, in
9//! the value type of your choice (`Q16_16`, `Q8_8`, `f32`, `f64`): a 6-state,
10//! 6-action Q16.16 table is 144 bytes. You describe the world through
11//! [`Environment`]: which actions are valid in a state, and a source of random
12//! integers for exploration. The loop that moves through the world is yours:
13//! ask the learner for an action, apply it, and report the reward and the new
14//! state.
15//!
16//! The update is tinymind (C++)'s, operation for operation:
17//!
18//! ```text
19//! Q(s, a) = (1 - lr) * Q(s, a) + lr * (reward + discount * max_a' Q(s', a'))
20//! ```
21//!
22//! for the experience's own state `s`, where the maximum runs over the actions
23//! valid in the next state `s'` (0 if there are none): the greedy value,
24//! whatever the learner explores, so the table converges to the optimal Q
25//! values. Action selection explores with probability
26//! `random_action_decision_point` percent; otherwise it takes the action with
27//! the largest Q value, as tinymind (C++)'s `ArgMaxPolicy` does (the first of
28//! equal maxima), unless every valid action has the same Q value (an unvisited
29//! state), in which case a random valid action is taken.
30//!
31//! ```
32//! use tinymind::qlearn::{Environment, Experience, QLearner};
33//! use tinymind::rand::GlibcRand;
34//! use tinymind::Q16_16;
35//!
36//! // A corridor of 4 cells; action 0 moves left, 1 moves right; cell 3 is the goal.
37//! struct Corridor(GlibcRand);
38//!
39//! impl Environment<2> for Corridor {
40//! fn valid_actions(&self, _state: usize, actions: &mut [usize; 2]) -> usize {
41//! *actions = [0, 1];
42//! 2
43//! }
44//! fn random_int(&mut self, min: usize, max: usize) -> usize {
45//! self.0.next_i32() as usize % (max + 1 - min) + min
46//! }
47//! }
48//!
49//! let rate = Q16_16::from_int(1) / Q16_16::from_int(5);
50//! let discount = Q16_16::from_int(8) / Q16_16::from_int(10);
51//! // Explore 100% of the time while learning.
52//! let mut learner =
53//! QLearner::<Q16_16, Corridor, 4, 2>::new(Corridor(GlibcRand::new(7)), rate, discount, 100);
54//! for _ in 0..200 {
55//! learner.start_new_episode();
56//! let mut state = 0;
57//! while state != 3 {
58//! let action = learner.take_action(state).unwrap();
59//! let next = if action == 0 { state.saturating_sub(1) } else { state + 1 };
60//! let reward = if next == 3 { Q16_16::ONE } else { Q16_16::ZERO };
61//! learner.update_from_experience(&Experience { state, action, reward, new_state: next });
62//! state = next;
63//! }
64//! }
65//! // Now exploit: from every cell the learner heads right.
66//! learner.set_random_action_decision_point(0);
67//! for cell in 0..3 {
68//! assert_eq!(learner.take_action(cell), Some(1));
69//! }
70//! ```
71//!
72//! # Deep Q-network
73//!
74//! [`QNetwork`] (tinymind (C++)'s `QValueNeuralNetworkPolicy`) keeps the Q
75//! values in a [`MultilayerPerceptron`] instead of a table: the network maps a
76//! state, encoded as its input vector by a function you supply, to one Q
77//! value per action, so states that look alike share what they learn. Each
78//! update trains the network on the taken action's target. The update's
79//! lookahead reads a second, target network, a copy of the online one
80//! refreshed every so many training steps, which keeps the target from
81//! chasing its own updates. It is a drop-in replacement for the table: pass
82//! it to [`QLearner::with_q_values`].
83
84use crate::activation::Activation;
85use crate::neuralnet::{InferencePerceptron, MultilayerPerceptron};
86use crate::optimizer::{Optimizer, Sgd};
87use crate::qformat::Scalar;
88
89/// The world a [`QLearner`] acts in: tinymind (C++)'s environment (the
90/// `getValidActionsForState` an example environment defines, and its random
91/// number policy's `randInt`).
92pub trait Environment<const ACTIONS: usize> {
93 /// Writes the actions valid in `state` to the front of `actions` and
94 /// returns how many there are (0 if none; values above `ACTIONS` count as
95 /// `ACTIONS`).
96 fn valid_actions(&self, state: usize, actions: &mut [usize; ACTIONS]) -> usize;
97
98 /// A uniformly distributed integer in `min..=max`, for exploration. The
99 /// learner asks for `random_int(0, 99)` to decide whether to explore and
100 /// `random_int(0, n - 1)` to pick one of `n` valid actions.
101 fn random_int(&mut self, min: usize, max: usize) -> usize;
102}
103
104/// Where a [`QLearner`] keeps its Q values: tinymind (C++)'s Q value policy.
105/// [`QTable`] is the tabular one.
106pub trait QValues<V> {
107 /// The Q value of taking `action` in `state`.
108 fn q_value(&self, state: usize, action: usize) -> V;
109 /// The Q value of the best action in the next state, used for the
110 /// update's target. A table returns [`q_value`](QValues::q_value).
111 fn future_q_value(&mut self, state: usize, action: usize) -> V;
112 /// Stores a new Q value for `action` in `state`.
113 fn set_q_value(&mut self, state: usize, action: usize, value: V);
114}
115
116/// A Q table, `values[state][action]` (tinymind (C++)'s `QValueTablePolicy`).
117/// Reading a state or action out of range gives 0 and writing one does nothing,
118/// as in the C++.
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub struct QTable<V, const STATES: usize, const ACTIONS: usize> {
121 /// The Q values, by state then action.
122 pub values: [[V; ACTIONS]; STATES],
123}
124
125impl<V: Scalar, const STATES: usize, const ACTIONS: usize> QTable<V, STATES, ACTIONS> {
126 /// A table of zeros, the C++ initial Q value.
127 pub fn new() -> Self {
128 Self::from_values([[V::ZERO; ACTIONS]; STATES])
129 }
130}
131
132impl<V, const STATES: usize, const ACTIONS: usize> QTable<V, STATES, ACTIONS> {
133 /// A table holding `values`, for example ones learned earlier.
134 pub const fn from_values(values: [[V; ACTIONS]; STATES]) -> Self {
135 Self { values }
136 }
137}
138
139impl<V: Scalar, const STATES: usize, const ACTIONS: usize> Default for QTable<V, STATES, ACTIONS> {
140 fn default() -> Self {
141 Self::new()
142 }
143}
144
145impl<V: Scalar, const STATES: usize, const ACTIONS: usize> QValues<V>
146 for QTable<V, STATES, ACTIONS>
147{
148 fn q_value(&self, state: usize, action: usize) -> V {
149 self.values
150 .get(state)
151 .and_then(|row| row.get(action))
152 .copied()
153 .unwrap_or(V::ZERO)
154 }
155
156 fn future_q_value(&mut self, state: usize, action: usize) -> V {
157 self.q_value(state, action)
158 }
159
160 fn set_q_value(&mut self, state: usize, action: usize, value: V) {
161 if let Some(q) = self
162 .values
163 .get_mut(state)
164 .and_then(|row| row.get_mut(action))
165 {
166 *q = value;
167 }
168 }
169}
170
171/// Q values from a neural network: a deep Q-network (tinymind (C++)'s
172/// `QValueNeuralNetworkPolicy`), for [`QLearner::with_q_values`].
173///
174/// The online network is a [`MultilayerPerceptron`] with `IN` inputs, `HID`
175/// hidden neurons and one output per action. `inputs` encodes a state as the
176/// network's input vector (C++ `getInputValues`; a one-hot vector for a small
177/// set of states). Reading a Q value runs the online network forward without
178/// changing it. Storing one feeds the state forward, sets the taken action's
179/// output to the new value, keeps the others as they are, and trains once,
180/// unless the value is already there. Every `target_update_interval` training
181/// steps the online weights are copied into the target network, which the
182/// learner's lookahead reads ([`QValues::future_q_value`]); it starts as a
183/// copy of the online network.
184///
185/// ```
186/// use tinymind::qlearn::{QNetwork, QValues};
187/// use tinymind::{Linear, MultilayerPerceptron, Q16_16, Tanh};
188///
189/// // Three states, one-hot encoded; two actions; four hidden neurons.
190/// fn one_hot(state: usize) -> [Q16_16; 3] {
191/// core::array::from_fn(|i| Q16_16::from_int(i32::from(i == state)))
192/// }
193/// let mut seed = 1;
194/// let net = MultilayerPerceptron::<Q16_16, Tanh, Linear, 3, 4, 2>::new(|| {
195/// seed = (seed * 7 + 3) % 17;
196/// Q16_16::from_raw((seed - 8) * 4096)
197/// });
198/// let mut q = QNetwork::new(net, one_hot, 10);
199/// let target = Q16_16::from_int(1) / Q16_16::from_int(2);
200/// let before = q.q_value(1, 0);
201/// q.set_q_value(1, 0, target);
202/// // One training step moves Q(1, 0) towards the target.
203/// let after = q.q_value(1, 0);
204/// assert!((after - target).raw().abs() < (before - target).raw().abs());
205/// ```
206pub struct QNetwork<V, H, O, const IN: usize, const HID: usize, const ACTIONS: usize, Opt = Sgd> {
207 network: MultilayerPerceptron<V, H, O, IN, HID, ACTIONS, Opt>,
208 target: InferencePerceptron<V, H, O, IN, HID, ACTIONS>,
209 inputs: fn(usize) -> [V; IN],
210 target_update_interval: usize,
211 iterations: usize,
212}
213
214impl<V, H, O, const IN: usize, const HID: usize, const ACTIONS: usize, Opt>
215 QNetwork<V, H, O, IN, HID, ACTIONS, Opt>
216where
217 V: Scalar,
218 H: Activation<V>,
219 O: Activation<V>,
220 Opt: Optimizer<V>,
221{
222 /// Q values from `network`, with `inputs` encoding each state as its
223 /// input vector, and the target network refreshed every
224 /// `target_update_interval` training steps (0 refreshes it after every
225 /// step, as 1 does, like the C++ `>=` test).
226 pub fn new(
227 network: MultilayerPerceptron<V, H, O, IN, HID, ACTIONS, Opt>,
228 inputs: fn(usize) -> [V; IN],
229 target_update_interval: usize,
230 ) -> Self {
231 let target = network.to_inference();
232 Self {
233 network,
234 target,
235 inputs,
236 target_update_interval,
237 iterations: 0,
238 }
239 }
240
241 /// The online network.
242 pub fn network(&self) -> &MultilayerPerceptron<V, H, O, IN, HID, ACTIONS, Opt> {
243 &self.network
244 }
245
246 /// The online network, to change its rates or weights.
247 pub fn network_mut(&mut self) -> &mut MultilayerPerceptron<V, H, O, IN, HID, ACTIONS, Opt> {
248 &mut self.network
249 }
250
251 /// The target network: the online weights as of the last refresh.
252 pub fn target(&self) -> &InferencePerceptron<V, H, O, IN, HID, ACTIONS> {
253 &self.target
254 }
255}
256
257impl<V, H, O, const IN: usize, const HID: usize, const ACTIONS: usize, Opt> QValues<V>
258 for QNetwork<V, H, O, IN, HID, ACTIONS, Opt>
259where
260 V: Scalar,
261 H: Activation<V>,
262 O: Activation<V>,
263 Opt: Optimizer<V>,
264{
265 /// The online network's output for `action` (0 for an action out of
266 /// range).
267 fn q_value(&self, state: usize, action: usize) -> V {
268 let outputs = self.network.evaluate(&(self.inputs)(state));
269 outputs.get(action).copied().unwrap_or(V::ZERO)
270 }
271
272 /// The target network's output for `action` (0 for an action out of
273 /// range).
274 fn future_q_value(&mut self, state: usize, action: usize) -> V {
275 let outputs = self.target.feed_forward(&(self.inputs)(state));
276 outputs.get(action).copied().unwrap_or(V::ZERO)
277 }
278
279 /// Trains the online network once towards `value` for `action`, unless
280 /// its output already equals it (an action out of range is ignored).
281 fn set_q_value(&mut self, state: usize, action: usize, value: V) {
282 self.network.feed_forward(&(self.inputs)(state));
283 let mut targets = self.network.learned_values();
284 let Some(target) = targets.get_mut(action) else {
285 return;
286 };
287 if *target != value {
288 *target = value;
289 self.network.train(&targets);
290 self.iterations += 1;
291 if self.iterations >= self.target_update_interval {
292 self.iterations = 0;
293 self.target = self.network.to_inference();
294 }
295 }
296 }
297}
298
299/// One step's outcome, reported to [`QLearner::update_from_experience`]
300/// (tinymind (C++)'s `experience_t`).
301#[derive(Clone, Copy, Debug, PartialEq)]
302pub struct Experience<V> {
303 /// The state the step started in; the update changes its Q value. A state
304 /// of `STATES` or more changes nothing (tinymind (C++)'s invalid state).
305 pub state: usize,
306 /// The action taken.
307 pub action: usize,
308 /// The reward it earned.
309 pub reward: V,
310 /// The state it led to.
311 pub new_state: usize,
312}
313
314/// A Q-learning agent over `STATES` states and `ACTIONS` actions
315/// (tinymind (C++)'s `QLearner`). It owns its [`Environment`] and its Q values (a
316/// [`QTable`] unless built with [`with_q_values`](Self::with_q_values)).
317#[derive(Clone, Debug)]
318pub struct QLearner<V, E, const STATES: usize, const ACTIONS: usize, Q = QTable<V, STATES, ACTIONS>>
319{
320 environment: E,
321 q_values: Q,
322 state: Option<usize>,
323 learning_rate: V,
324 discount_factor: V,
325 random_action_decision_point: usize,
326}
327
328impl<V: Scalar, E: Environment<ACTIONS>, const STATES: usize, const ACTIONS: usize>
329 QLearner<V, E, STATES, ACTIONS>
330{
331 /// A learner with a zeroed [`QTable`]. `learning_rate` and
332 /// `discount_factor` must be in [0, 1] and `random_action_decision_point`
333 /// (the exploration percentage) at most 100; a value outside that range
334 /// is ignored, leaving 0, as in the C++.
335 pub fn new(
336 environment: E,
337 learning_rate: V,
338 discount_factor: V,
339 random_action_decision_point: usize,
340 ) -> Self {
341 Self::with_q_values(
342 environment,
343 QTable::new(),
344 learning_rate,
345 discount_factor,
346 random_action_decision_point,
347 )
348 }
349}
350
351impl<V: Scalar, E: Environment<ACTIONS>, const STATES: usize, const ACTIONS: usize, Q: QValues<V>>
352 QLearner<V, E, STATES, ACTIONS, Q>
353{
354 /// A learner over the given Q values; otherwise as [`new`](QLearner::new).
355 pub fn with_q_values(
356 environment: E,
357 q_values: Q,
358 learning_rate: V,
359 discount_factor: V,
360 random_action_decision_point: usize,
361 ) -> Self {
362 // The C++ static_asserts.
363 const {
364 assert!(STATES > 1, "a QLearner needs at least two states");
365 assert!(ACTIONS > 1, "a QLearner needs at least two actions");
366 }
367 let mut learner = Self {
368 environment,
369 q_values,
370 state: None,
371 learning_rate: V::ZERO,
372 discount_factor: V::ZERO,
373 random_action_decision_point: 0,
374 };
375 learner.set_learning_rate(learning_rate);
376 learner.set_discount_factor(discount_factor);
377 learner.set_random_action_decision_point(random_action_decision_point);
378 learner
379 }
380
381 /// The environment.
382 pub fn environment(&self) -> &E {
383 &self.environment
384 }
385
386 /// The environment, mutably (for example to draw from its generator).
387 pub fn environment_mut(&mut self) -> &mut E {
388 &mut self.environment
389 }
390
391 /// The Q values.
392 pub fn q_values(&self) -> &Q {
393 &self.q_values
394 }
395
396 /// The Q values, mutably.
397 pub fn q_values_mut(&mut self) -> &mut Q {
398 &mut self.q_values
399 }
400
401 /// The Q value of taking `action` in `state`.
402 pub fn q_value(&self, state: usize, action: usize) -> V {
403 self.q_values.q_value(state, action)
404 }
405
406 /// Sets the Q value of taking `action` in `state`.
407 pub fn set_q_value(&mut self, state: usize, action: usize, value: V) {
408 self.q_values.set_q_value(state, action, value);
409 }
410
411 /// The learning rate.
412 pub fn learning_rate(&self) -> V {
413 self.learning_rate
414 }
415
416 /// Sets the learning rate if it is in [0, 1]; otherwise keeps the old one.
417 pub fn set_learning_rate(&mut self, rate: V) {
418 if is_in_unit_interval(rate) {
419 self.learning_rate = rate;
420 }
421 }
422
423 /// The discount factor.
424 pub fn discount_factor(&self) -> V {
425 self.discount_factor
426 }
427
428 /// Sets the discount factor if it is in [0, 1]; otherwise keeps the old
429 /// one.
430 pub fn set_discount_factor(&mut self, factor: V) {
431 if is_in_unit_interval(factor) {
432 self.discount_factor = factor;
433 }
434 }
435
436 /// How often the learner explores, in percent: 0 never, 100 always.
437 pub fn random_action_decision_point(&self) -> usize {
438 self.random_action_decision_point
439 }
440
441 /// Sets the exploration percentage if it is at most 100; otherwise keeps
442 /// the old one.
443 pub fn set_random_action_decision_point(&mut self, percent: usize) {
444 if percent <= 100 {
445 self.random_action_decision_point = percent;
446 }
447 }
448
449 /// The current state, `None` at the start of an episode.
450 pub fn state(&self) -> Option<usize> {
451 self.state
452 }
453
454 /// Sets the current state if it is below `STATES`.
455 pub fn set_state(&mut self, state: usize) {
456 if state < STATES {
457 self.state = Some(state);
458 }
459 }
460
461 /// Forgets the current state (the C++ invalid state), as at the start of
462 /// an episode.
463 pub fn start_new_episode(&mut self) {
464 self.state = None;
465 }
466
467 /// Chooses an action in `state` (exploring or exploiting), makes `state`
468 /// the current state and returns the action, or `None` if `state` has no
469 /// valid action.
470 pub fn take_action(&mut self, state: usize) -> Option<usize> {
471 let action = self.choose_action(state);
472 self.set_state(state);
473 action
474 }
475
476 /// Learns from a step: updates the Q value of `experience.action` in
477 /// `experience.state` (unless the learning rate is 0 or the state is out of
478 /// range), whatever the learner's current state, and moves to
479 /// `experience.new_state`.
480 pub fn update_from_experience(&mut self, experience: &Experience<V>) {
481 let learning_rate = self.learning_rate;
482 if learning_rate > V::ZERO && experience.state < STATES {
483 let one_minus_learning_rate = V::ONE - learning_rate;
484 let discount_factor = self.discount_factor;
485 let old_q_value = self.q_values.q_value(experience.state, experience.action);
486 let future_q_value = self.future_q_value(experience.new_state);
487 let q_value = (one_minus_learning_rate * old_q_value)
488 + (learning_rate * (experience.reward + (discount_factor * future_q_value)));
489 self.q_values
490 .set_q_value(experience.state, experience.action, q_value);
491 }
492 self.state = Some(experience.new_state);
493 }
494
495 /// max over the actions valid in `state` of their Q value, from the action
496 /// [`best_action`](Self::best_action) picks (the first valid one when all
497 /// tie, since each is then the maximum); 0 when none is valid. Never draws
498 /// from the generator.
499 fn future_q_value(&mut self, state: usize) -> V {
500 let mut buffer = [0; ACTIONS];
501 let count = self.environment.valid_actions(state, &mut buffer);
502 let valid = buffer.get(..count).unwrap_or(&buffer);
503 let Some(&first) = valid.first() else {
504 return V::ZERO;
505 };
506 let action = self.best_action(state, valid).unwrap_or(first);
507 self.q_values.future_q_value(state, action)
508 }
509
510 fn choose_action(&mut self, state: usize) -> Option<usize> {
511 let mut buffer = [0; ACTIONS];
512 let count = self.environment.valid_actions(state, &mut buffer);
513 let valid = buffer.get(..count).unwrap_or(&buffer);
514 if self.should_choose_random_action() {
515 self.random_action(valid)
516 } else {
517 match self.best_action(state, valid) {
518 Some(action) => Some(action),
519 None => self.random_action(valid),
520 }
521 }
522 }
523
524 fn should_choose_random_action(&mut self) -> bool {
525 match self.random_action_decision_point {
526 0 => false,
527 100 => true,
528 // 100 equally likely values, `point` of them below it: a random
529 // action with probability exactly point / 100.
530 point => self.environment.random_int(0, 99) < point,
531 }
532 }
533
534 fn random_action(&mut self, valid: &[usize]) -> Option<usize> {
535 match valid {
536 [] => None,
537 [action] => Some(*action),
538 _ => {
539 let index = self.environment.random_int(0, valid.len() - 1);
540 valid.get(index).copied()
541 }
542 }
543 }
544
545 /// tinymind (C++)'s `ArgMaxPolicy::selectBestActionForState`.
546 fn best_action(&self, state: usize, valid: &[usize]) -> Option<usize> {
547 match valid {
548 [] => None,
549 [action] => Some(*action),
550 [a0, a1] => {
551 let (q0, q1) = (
552 self.q_values.q_value(state, *a0),
553 self.q_values.q_value(state, *a1),
554 );
555 if q0 > q1 {
556 Some(*a0)
557 } else if q1 > q0 {
558 Some(*a1)
559 } else {
560 // A tie is no preference, as below.
561 None
562 }
563 }
564 [first, rest @ ..] => {
565 // The largest Q value, whatever its sign (the first of equal
566 // maxima). Only when every valid action ties, as in an
567 // unvisited state of a zeroed table, is there no preference:
568 // `None` makes the caller take a random action (and the
569 // update's bootstrap any of them, since each is the maximum).
570 let mut best_action = *first;
571 let mut best_q_value = self.q_values.q_value(state, best_action);
572 let mut all_tied = true;
573 for &action in rest {
574 let q_value = self.q_values.q_value(state, action);
575 if q_value != best_q_value {
576 all_tied = false;
577 }
578 if q_value > best_q_value {
579 best_q_value = q_value;
580 best_action = action;
581 }
582 }
583 if all_tied { None } else { Some(best_action) }
584 }
585 }
586 }
587}
588
589/// tinymind (C++)'s `isInUnitInterval`: `!(v < 0) && !(1 < v)`, so a float NaN
590/// passes, as in the C++.
591#[allow(clippy::neg_cmp_op_on_partial_ord)]
592fn is_in_unit_interval<V: Scalar>(value: V) -> bool {
593 !(value < V::ZERO) && !(V::ONE < value)
594}