Basic Reinforcement Learning
interacting with the environment
no use for isolated brains
- phylogentic driver for the development of
biological cognitive systems
:: active manipulation of the outside world
- State internal, of agents
Action of agents
:: internal state transitions, of agent
:: external changes, of environment
Reward benefits agents receive
- often: combined state (internal/external), of system
applications
- Large Language Model (LLM) alignment
RL from Human Feedback (RLHF): foundational for generative AI
- robotics and autonomous driving
- gaming and strategic decision-making
- ...
Markov Decision Process (MDP)
determinstic
- $S\ $ state
$A\ $ action
$$
S' = S(A)
$$
- action $A$ in state $S$ leads deterministically to state $S'$
stochastic
- e.g., environmental randomess impacts the outcome of
an action
$$
P(S'∣S,A) \quad\qquad
1 = \sum_{S'} P(S'∣S,A)
$$
- probability to reach state $S'$ when taking action $A$
in state $S$
stochastic policies
- $\big\{A(S_t)\big\}$ set of
actions available in state $ S_t$
:: time $t$
- policy
has two meanings
:: probability to select $\ A_t\in\big\{A(S_t)\big\}$
:: probability to explore $\ A_t\in\big\{A(S_t)\big\}$
- exploration
find out more before deciding which action to take
:: e.g. Monte Carlo tree search
- $P(A_t∣S_t)$
conditional transition probability, to
select $\ A_t\ $ given $\ S_t$
→ to be optimized
$$
1 = \sum_{A_t\,\in\,\tilde{A}_t} P(A_t|S_t)
\quad\qquad
P(A_t∣S_t)\ge0
$$
- normalization: always take an action
:: doing nothing is an action
- same object, different notation
:: policy
$$\pi(a|s) = P(A_t=a|S_t=s)
$$
blind walker, a game
$$
\fbox{$\phantom{\big|}0\phantom{\big|}$}\to
\fbox{$\phantom{\big|}1\phantom{\big|}$}\to
\fbox{$\phantom{\big|}\color{red}L\phantom{\big|}$}\to
\fbox{$\phantom{\big|}2\phantom{\big|}$}\to
\fbox{$\phantom{\big|}\color{green}W\phantom{\big|}$}\to
\fbox{$\phantom{\big|}0\phantom{\big|}$}
$$
| $\fbox{$\phantom{\big|}0\phantom{\big|}$}$
| starting position |
| $\fbox{$\phantom{\big|}\color{green}W\phantom{\big|}$}$
| game ends with a win; reward 1 |
| $\fbox{$\phantom{\big|}\color{red}L\phantom{\big|}$}$
| game ends with a loss; reward 0 |
- allowed actions: one/two to the right
:: could go on forever
- stationary policy (blind agents)
:: same policy for all game positions (states)
$$
\pi(1|S_t) = \alpha,
\quad\qquad
\pi(2|S_t) = \beta
\quad\qquad
\beta = 1-\alpha,
$$
time evolution
| time
| state
| probability
| reward
|
| $t=0$
| $\fbox{$\phantom{\big|}0\phantom{\big|}$}$
| $p=1$
|
|
| $t=1$
| $\fbox{$\phantom{\big|}1\phantom{\big|}$}$
| $p=\alpha$
|
|
| $t=2$
| $\fbox{$\phantom{\big|}2\phantom{\big|}$}$
| $p=\alpha\beta$
|
|
| $t=3$
| $\fbox{$\phantom{\big|}0\phantom{\big|}$}$
| $p=\alpha\beta^2$
| $R=1$, with probabiliy $\ \alpha^2\beta$
|
- if game stops when reaching starting position again
$$ R \to \alpha^2\beta
\quad\qquad \alpha_{\rm opt} \to \frac{2}{3} \approx 0.667
\quad\qquad R_{\rm opt} \to \frac{4}{27} \approx 0.148
$$
- if game may continue forever
$$ R_{\rm tot}
= \alpha^2\beta\, \sum_{n=0}^\infty (\alpha\beta^2)^n
= \frac{\alpha^2\beta}{1-\alpha\beta^2}
\quad\qquad \alpha_{\rm opt} \approx 0.639
\quad\qquad R_{\rm opt} \approx 0.161
$$
value ↔ future rewards
value
- sum of discounted future rewards $\ R_t$,
given a policy $\ \pi=\pi(a|s)$
- value of state $\ S$
$$
V^\pi(S) = \sum_{t=0}^\infty \gamma^t \langle R_{t+1}\rangle_{\pi}
$$
- $\gamma\in[0,1]$ discounting factor
$\langle\dots\rangle_\pi$ policy average
- reward (Sutton & Barton notation, arrival based)
:: for transitioning to next state
:: not for being at a given state
:: $R_1$ first reward, not $R_0$
→ used here
- arrival based vs. action-based notation
$R_{t+1}\mid_{\rm arrival\ based} \,=\,
R_{t}\mid_{\rm action\ based}$
Q-value
- here: only determistic MDP
:: generalize for stochastic MDP
- action $A$ in state $S$ leads to $S'$,
yielding reward $\ R(S,A)$
:: Q-value
$$Q^\pi(S,A)= R(S,A) + \gamma V^\pi(S')$$
- for a given first action $A$
→ add reward plus discounted value of next state
$$
V^\pi(S) = \sum_{A\in \{A(S)\}} \pi(A|S)\, Q^\pi(S,A)
$$
- Bellman equation
:: for deterministic MDP
- look ahead on step
:: what happens when I select $A$?
Bellman equation
generic Bellman equation
- for stochastic Markov decision processes
$$
V^{\pi }(S)=\sum _{A}\pi (A\mid S)
\sum _{S^{\prime }}P(S^{\prime }\mid S,A)
\left[R(S,A,S^{\prime })+\gamma V^{\pi }(S^{\prime })\right]
$$
- take action $A$ in state $S$
with probability $\ \pi (A\mid S)$
- reach state $S'$
with probability $\ P(S^{\prime }\mid S,A)$
- receive reward $\ R(S,A,S^{\prime })$
temporal difference learning (TDL)
- board game
value likelihood to win
policy move selection
and/or exploration
- many learning protocols
:: optimize both policy and values
REINFORCE: only policy
TDL: only values
basic temporal difference learning
- in state $S$, action $A$ has been taken,
leading to state $S'$ (deterministic MDP),
the reward $R=R(S,A)$ has been received
- values $V(S)$ are only estimates,
Bellman equation not yet satisfied
→ how to improve the values?
- temporal difference
:: between new and current estimate
$$
\delta(S,A) = \big[ R(S,A)+\gamma V(S') \big] - V(S)
$$
$$
\begin{array}{rcl}
V(S) &\to& V(S) + \alpha\delta(S,A) \\
&= & (1-\alpha)V(S) +
\alpha \big[ R(S,A)+\gamma V(S') \big]
\end{array}
$$
- for a specific action $\ A$
many simulations → policy average
→ Bellman equation
:: policy not specified
- look one step ahead
state action reward state action (SARSA)
- simulation
$(S_0,A_0)\,\to\, (S_1,A_1)\,\to\ (S_2,A_2)\,\to\,\dots $
- apply TDL to Q-values
best Q-value ↔ best action
$$
Q^{\rm new}(S_t,A_t) \ =\ (1-\alpha)Q(S_t,A_t) +
\alpha\left[R_{t+1} + \gamma\, Q(S_{t+1}, A_{t+1})\right]
$$
- two actions
$A_t\ $ executed in the simulation
$A_{t+1}\ $ selected, but not (yet) taken
- second action allows to estimate $Q(S_{t+1}, A_{t+1})$
:: used in the next step
- all actions sampled from a given policy
- on policy
SARAS is based on the same policy
that would be used for inference
Q-learning
$$
Q^{\rm new}(S_t, A_t) \ =\
(1 - \alpha) Q(S_t,A_t) + \alpha \,
\left[R_{t+1} + \gamma \, Q^{\rm best}(S_{t+1})\right]
$$
- off-policy selection of second action
e.g., greedy
$$
Q^{\rm best}(S_{t+1}) =\max_{A'} Q(S_{t+1},A')
$$
- two actions
$A_t\ $ executed in the simulation
$A_{t+1}\ $ not used in the simulation (modulo a coincidence)
- off policy
Q-learing is not fully based on the policy
used for inference
RL-learning leads to training datasets, the
distribution of states visited, changing with time,
which may lead to catastrophic forgetting and/or instabilities
Q-learning code
$$
\fbox{$\phantom{\big|}0\phantom{\big|}$}\to
\fbox{$\phantom{\big|}1\phantom{\big|}$}\to
\fbox{$\phantom{\big|}2\phantom{\big|}$}\to
\fbox{$\phantom{\big|}\color{red}L\phantom{\big|}$}\to
\fbox{$\phantom{\big|}4\phantom{\big|}$}\to
\fbox{$\phantom{\big|}\color{green}W\phantom{\big|}$}\to
\fbox{$\phantom{\big|}0\phantom{\big|}$}
$$
- walker
not blind → local strategy optimization
small state/action space → lookup tables for Q possible
-
np.random.choice() random item from list
-
np.argmax() index from largest item
- normally exploration only during training
-
Open Spiel RL framework for games (Google/Deepmind)
#!/usr/bin/env python3
#
# Q learning for walker (not blind)
#
# based on
# https://www.geeksforgeeks.org/q-learning-in-python/
import numpy as np
# environment
n_states = 6 # number of states in a linear world
n_actions = 2 # number of possible moves (distances)
goal_state = 5 # game ends with a win
loss_state = 3 # game ends with a loss
# initialize Q-table with zeros
Q_table = np.zeros((n_states, n_actions))
# parameters
learning_rate = 0.8
discount_factor = 0.95
exploration_prob = 0.2
nEpochs = 5000
# allowed starting positions
start_pos = set(range(n_states)) # range to set
start_pos.remove(loss_state) # remove loss/win states
start_pos.remove(goal_state)
#
# Q-learning from random starting state
#
for epoch in range(nEpochs):
current_state = np.random.choice(list(start_pos))
game_length = 0 # currently not used
while (current_state!=goal_state) and \
(current_state!=loss_state):
game_length += 1
#
if np.random.rand() < exploration_prob: # epsilon-greedy strategy
action = np.random.randint(0, n_actions) # exploring
else:
action = np.argmax(Q_table[current_state]) # exploiting
# determine next state, periodic boundaries
next_state = (current_state + 1 + action)%n_states
# reward is \pm 1 for goal/loss state, 0 otherwise
reward = 0.0
if (next_state==goal_state):
reward = 1.0
if (next_state==loss_state):
reward = -1.0
# updating Q-table
Q_table[current_state, action] += learning_rate * \
( reward + discount_factor*np.max(Q_table[next_state]) -
Q_table[current_state, action] )
current_state = next_state # move to next state
#
# printing
#
print("expected dicounted rewards Q(S,A)")
print("state, Q-table")
for iS in range(n_states):
print(f'{iS:5d} ', end = "")
for iA in range(n_actions):
QQ = Q_table[iS][iA]
print(f'{QQ:7.3f} ', end = "")
#
if (iS==loss_state):
print(" loss", end = "")
if (iS==goal_state):
print(" win", end = "")
print()
Alpha zero
»$\,$supplementary material$\,$«
game of Go
- number of configurations
$3^{19\cdot19} \approx 1.7\cdot10^{172} $
- (all) game states are new
→ lookup tables not possible
estimator needs to able to generalize
- 2017
AlphaGo zero (Goggle DeepMind)
: self-play ($5\cdot10^6$ games)
- deep neural net generates estimates for
- value of a new configuration: probability to win
- policy to explore an yet untested move
- Monte Carlo tree search uses combination of
- exploitation maximize probability to win (value)
- exploration trying out something new (policy)
- 1600 Monte Carlo tree search (MCTS) steps
→ two kinds of policies
- prior generated by deep net
- posterior generated by MCTS
- next move selected
most explored configuration
- not: configuration most likely to win!
- "supervised RL"
store entire game → error backpropagation
Alpha zero cheat sheet
intermezzo: neural scaling laws
scarce recourses
- compute
(total training time, in FLOPS)
- size
(total number of adjustable parameters)
- data (total amount)
(Hoffmann, et al, 2022)
- optimal parameter combination
:: empirical
compute $\ \sim\ $ (size)$^2$
- (very) large compute needed
- prefactor for small models
→ optimal scaling for production model
:: essential for large language models (LLM)
Alpha Zero Elo scaling
Elo ranking
- probability that A beats B
$\displaystyle
P(A\!\to\!B) = \frac{1}{1+10^{-(E_A-E_B)/400}}
$
societies of game playing agents
$$
P(A\!\to\!B) \approx \frac{N_A}{N_A+N_B}
$$
$$
\mathrm{Elo} \ \approx \ \log(N)\cdot\sigma\left(
\beta\log\left(\frac{\sqrt{C}}{N}\right)\right),
\quad\qquad
\mathrm{time} \propto (\mathrm{resources})^2
$$
- $\sigma()$ sigmoidal
- brain size / learning scaling?
:: brain size limitation?