Deck 09 opens by situating reinforcement learning inside this course: "RL is a natural topic for this course, at this stage; technically, it is very related to modelling (DTMC) and simulation." The derivation is a staircase of three questions:
Recall the DTMC of chapter 10, section 3: a couple ⟨S, →⟩ where → ⊆ S × [0,1] × S — a directed graph whose edges carry probabilities, with two sanity conditions (deadlock or total probability 1; at most one arc between two states). The DTMC "describes the probabilistic evolution of a system" while abstracting away duration (a tick) and, crucially, the cause of non-determinism — which "can be due to observation of different outcomes of an unknown phenomenon", "the existence of an internal component taking decisions probabilistically", or "an external cause out of system's control".
To capture the cause, the DTMC is evolved in two steps. First: "add a notion of 'action' performed by an external entity (agent), whose outcome can be probabilistic" — a DTMC with actions, a triple ⟨S, A, →⟩ with → ⊆ S × A × [0,1] × S, whose sanity condition is per-action: for every state and action, either deadlock or outgoing probability 1. This "unveils non-determinism" into two components: "cause 1: non-determinism due to a 'trackable' decision (action); cause 2: non-determinism due to unknow effect of the decision (probability)". The whole system then "naturally splits in two parts": the environment — "the entity receiving the decision and accordingly 'change state' probabilistically" — and the agent — "the entity taking the decision". Note the deck's precision: "the automaton only models the environment response, actually".
Second: "add a notion of numerical reward, which the agent could use to decide". Rewards "are typically numerical values associated to each arrow of the automaton, whose cumulation the agent wants to maximise". The result is the Markov Decision Process:
MDP = ⟨S, A, R, →⟩ where → ⊆ S × A × [0,1] × R × S a,p,r
write S −−−→ S′
with the same sanity conditions per state-action pair (deadlock or probability 1, at most one arc labelled a from S to S′). "Essentially: DTMCs + rewarded actions."
With rewards on the arrows, the natural question is: "what is the 'policy' that creates most cumulative reward?" A policy is "a selection of which action to take at each state". The deck's running example is a two-state automaton: from S1, the agent can send (with 99% probability reaching a success state with reward rs, and 1% reaching a failure state with reward rf) or wait (reward rw, staying). The problem: "given rf, rs, rw, whether it is more convenient in S1 to send or just wait".
Two readings fix the reasoning. "Because of the markov property this cannot depend on the past (e.g. whether it is the first or second time we are taking the decision)" — the decision in S1 is the same every time. And the expected returns are computable by recursion: "e.g.: always waiting gives k·rw after k choices; e.g.: sending has 99% probability to give rs, and 1% to give rf plus the reward we can get in k−1 choices, recursively". The widget below lets you play the trade-off; the point is that "MDPs are aimed at computing those estimates and corresponding policies" — the optimality problem of the MDP.
Be able to derive, from the recursion, the per-step expected reward of "send" (0.99·rs + 0.01·rf) and compare it with rw — and to say why the Markov property makes the choice history-independent. This one-line derivation is the seed of everything else: the value functions of section 5 are just this recursion written for arbitrary policies, and the Bellman equations of section 6 solve it exactly.
The step from MDP to RL is about knowledge. An MDP "allows one to compute how much reward a policy is expected to achieve, taking as input the probabilistic behaviour of the environment"; reinforcement learning is, technically, "the problem of learning what to do so as to maximize a numerical reward signal" — "learning means that the learner discovers (and tracks) by exploration the effect of actions, and recalls it for the future". RL "derives policies possibly starting with incomplete (or absent) knowledge about the behaviour of the environment and expected long-time reward of a state/action".
RL is the third category of machine learning — "other than supervised/unsupervised learning" — with key features: "closed-loop, no pre-instructions, consequences of actions are in future". The scenario is "a learning agent interacting with the environment to achieve a goal: the agent senses the environment, takes actions, and has the goal of obtaining reward". The examples of the deck are worth keeping: learning to play chess or videogames; "an adaptive controller of an actuator that adjusts its parameters"; "a mobile robot deciding to go recharging or continue its task in next room"; "a drone learning not to crash into others"; "a device learning which neighbours to stop trusting" — the last one already smells of aggregate computing.
The agent-environment interface fixes the symbols: time is discrete steps t = 0, 1, 2, 3, ...; the agent receives a representation of the environment state St ∈ S and decides to execute an action At ∈ A(St); one time step later it receives a reward Rt+1 ∈ R and a state St+1. Agent decisions are framed as a policy πt that can be probabilistic: πt(a|s) is the probability to execute action a at state s. "Hence the MDP (state, actions, rewards) just models the environment."
The interface is "an element of design": steps "need not be fixed-length... just successive stages"; actions "can be low-level controls, or high-level decisions"; states "can be complete sensor readings, high-level descriptions, mere beliefs, intentions, or memory of past"; "the agent/environment boundary is flexible: what the agent can control is considered outside"; and "reward is typically considered as coming from outside the learner". The key modelling problem: "apply a proper abstraction such that the number of states and actions are reasonably limited to avoid state-explosion problems" and "the obtained policy is a good one for the problem at hand".
What is the objective? The reward hypothesis is "a key of RL": "all is meant by goals/purposes/success can be well thought of as the maximization of the expected value of the cumulative sum of a received scalar signal (reward)". The deck's examples show how flexible the encoding is: to learn to walk, "give rewards proportional to distance reached"; to escape quickly, "give −1 each time escape is not achieved"; to collect, "give +1 each time an item is collected"; "not to fall on holes, give −1000 each time it falls"; to win a board game, "give +1 on winning, −1 on losing, 0 in any other case".
Tasks split into two kinds: episodic — "if agent/environment interaction breaks in subsequences that restart in the same way" — and continuing — "if agent/environment interaction is long life". The return of an episode is the cumulative reward to be maximised: with an episode written as the sequence S0, A1, R1, S1, A2, R2, S2, ..., the return expected at time t is
G_t = Σ_{k=0}^{T} γ^k R_{t+k+1} with 0 ≤ γ ≤ 1
The parameter γ is the discount rate: "it measures the relative value we give to future rewards. γ = 0 means the agent is myopic: it cares of present and does not value future. With episodic tasks, one could even choose γ = 1. With continuing tasks, γ < 1." (Without discounting, an infinite continuing task could accumulate infinite return — the reason γ < 1 keeps the sum finite.)
Gt = Σ γkRt+k+1 weights future rewards by γ, whose value separates myopic (0) from farsighted (towards 1) agents, and episodic from continuing tasks.The lecture now formalises the problem. Inputs: the structure of states and actions S, A; the environment dynamics (without the Markov hypothesis) Pr{Rt+1 = r, St+1 = s′ | S0, A0, R1, ..., St, At}; the initial state S0; the discount factor γ and episode length T. A policy π "gives a distribution over episodes"; each episode e has probability pe and return Ge = R1 + γR2 + γ²R3 + ... + γT−1RT; a policy's overall return is Ee[Ge] = Σe p(e)Ge. "RL: find the policy that probabilistically gives the highest return."
States should "summarise the past compactly, so that we never need to know past states — namely: the markov property". With it, the general dynamics collapses to p(s′, r|s, a) := Pr{Rt+1 = r, St+1 = s′ | St, At} — "from state s with action a move to s′ and receive reward r". From this single function everything is derived:
r(s, a) = E[Rt+1 | St=s, At=a] = Σr,s′ p(s′, r|s, a)·r;p(s′|s, a) = Σr p(s′, r|s, a);rπ(s) = Σa π(a|s) r(s, a).The collector robot example instantiates it: "state represents how much energy the robot has left"; rewards rwait, rsearch measure items collected while waiting/searching; "−3 stands for cost for retrieving an inactive robot and recharging"; α, β describe the energy cost of searching. "If used online, rwait, rsearch are observed; if used offline, they could hide a random variable over the collected items." The expected rewards: r(high, wait) = rwait, r(high, search) = rsearch[(1−α) + α] (the two outcomes of searching weighted by their probabilities), and for a purely non-deterministic policy rπ(high) = r(high, wait)/2 + r(high, search)/2.
To estimate long-term return, the lecture introduces the two value functions. Under policy π:
state-value: v_π(s) = E_π[ G_t | S_t = s ] = E_π[ Σ_{k=0}^∞ γ^k R_{t+k+1} | S_t = s ]
action-value: q_π(s,a) = E_π[ G_t | S_t = s, A_t = a ]
"One can easily be derived from the other", and both "can be: computed (exactly or with approximation), learnt from experience, e.g. by Monte-Carlo methods".
p(s′, r|s, a); the expected rewards r(s, a) and rπ(s) follow. The value functions vπ and qπ turn "long-term return" into a computable quantity — the bridge to the Bellman equations.The Bellman equation is "the recursive definition of vπ (qπ is similar)":
v_π(s) = Σ_a π(a|s) Σ_{s′,r} p(s′, r|s, a) [ r + γ·v_π(s′) ]
Read as the deck does: "for each triple a, s′, r compute probability π(a|s)p(s′, r|s, a), weigh the quantity in brackets by this probability, and sum all possibilities". The value of a state is the expected immediate reward plus the discounted value of wherever you land — one equation per state.
The grid example fixes the intuition: a robot wandering a field, moving left-right-up-down, "reward typically 0; reward is −1 when trying to move out of area (but won't move); in two cases, moving everywhere causes a jump and exceptional reward", with γ = 0.9. Computing the state-value function for a purely non-deterministic policy "is a system of n equations in n variables, where n is cardinality of S (25 above)"; "existence of unique solution is guaranteed, but it is costly to compute". The TryQMatrix facade of section 9 uses exactly this 5×5 grid with rewards +10 at (1,0) and +5 at (3,0), jumps to (1,4) and (3,2), γ = 0.9.
Optimality: "a policy is better than another (π ≥ π′) if its expected value is ≥ in all states"; "greater v (or q) induces better π"; "optimal policies π* are such that v*(s) = maxπ vπ(s) and q*(s, a) = maxπ qπ(s, a)". The Bellman optimality equation — replace the policy average by the max — "is a system of N non-linear equations and N unknowns... it provably has a unique solution". Once v* is known, "π is easily found by greedy action selection: namely, deterministically going to the directions increasing v*"; "knowing q* below makes policy identification even easier". The greedy policy is the optimal one: "always choose the action that produces immediate highest return (v* or q*); if there are two such actions, it could possibly be non-deterministic".
The honest caveat of the lecture: "unfortunately, computing q* or v* quickly becomes untractable (in space and time); they should be approximated, or computed partially (by exploring subparts of s, a); additionally p is not always fully known — or even not existing, due to non-markov environments." This is the door to learning (section 7).
Every algorithm in this chapter is a way of computing the same recursion: dynamic programming iterates it from the known model; Monte Carlo estimates its expectation from sampled episodes; temporal-difference methods (and Q-learning) combine both, updating one state from the current estimate of the next. Even the DQN of section 10 is the same recursion with the value table replaced by a neural network.
The lecture surveys the three families of solution techniques, ordered by how much of the model they need:
∀s: vk+1(s) = maxa Σs′,r p(s′, r|s, a)[r + γvk(s′)]; "by the Bellman theorem, transition from vk to vk+1 is an improvement, hence there's convergence". "Can give good results in time, but is still impractical with many states." The deck notes updates can be asynchronous — "somehow making it resemble a stabilising 'field computation' over v, as in 'Bellman gradients'" — a first echo of chapter 14.αqold + (1−α)qnew. MC without exploring start: stick to an initial state but "be sure that all states will eventually be traversed: π should never give less than ε > 0 probability to any available action" — e.g. super-impose a non-deterministic policy giving ε to all actions.Q-learning is the algorithm the course actually implements. Its update is one line:
Q(S_t, A_t) := (1 − α)·Q(S_t, A_t) + α·[ R_{t+1} + γ·max_a Q(S_{t+1}, a) ]
The procedure: "initialize Q arbitrarily, and put 0 on terminal state; for each episode, starting from a Q₀: 1. choose A from S using a policy from Q that is explorative (e.g. ε-greedy); 2. take action A and observe R, S′ (the simulated/actual step is here!); 3. update Q; 4. S := S′; 5. end episode when S is terminal". The design space: "define your environment interface: S, A (properly abstract!); define your environment dynamics: S, A → S′, R (MDP, or external 'oracle'); define q-learning parameters: Q₀, α, γ, πεQ".
Note the "simulated/actual step is here!": Q-learning does not care where the experience comes from — an MDP model, a simulator like Alchemist, or the real world. That is what makes it the bridge between this chapter and chapter 12.
Methodologically, the deck separates two uses, and their combination:
Be able to read the update Q(St,At) := (1−α)Q(St,At) + α[Rt+1 + γ maxaQ(St+1,a)] as a one-step Bellman backup: the old estimate is pulled a fraction α towards the sampled target R + γ·(best next estimate). Be able to explain why it is off-policy (the update uses the greedy action at St+1, not the one the behaviour policy actually took) and why exploration is mandatory (all pairs s, a "in principle need to be updated, to explore").
The lecture develops a small Scala prototype — "possible with simple algorithms, like q-learning; gives much more confidence on the inner mechanisms; allows more informative explorations; will allow to combine with other owned technologies (scafi, that is)". The structure: model.QRL — "a family trait with definitions and template methods" (Environment, Policy, System, VFunction, Q, LearningProcess); model.QRLImpl — "a family trait with objects and case classes, providing implementations"; examples.TryQMatrix — "a facade to play with grid-like examples".
Read the first part of the API: an Environment is just a function from (state, action) to (reward, state); an MDP implements it by drawing from a weighted list of transitions — the "simulated/actual step" abstraction of section 8; a System wraps the environment with an initial state, a terminal predicate and a run producing a lazy list of (action, state) pairs.
trait QRL:
type State
type Action
type Reward = Double
type Probability = Double
given random: scala.util.Random = new scala.util.Random()
trait Environment extends ((State, Action) => (Reward, State))
trait MDP extends Environment:
def transitions(s: State): Set[(Action, Probability, Reward, State)]
override def apply(s: State, a: Action): (Reward, State) =
draw(cumulative(transitions(s).collect {
case (`a`, p, r, s) => (p, (r, s))
}.toList))
type Policy = State => Action
trait System:
def environment: Environment
def initial: State
def terminal: State => Boolean
def run(p: Policy): LazyList[(Action, State)]
Then the Q-function and the learning process. Q is an updatable table: bestPolicy is the greedy actions.maxBy(this(s, _)); epsPolicy draws a uniform action with probability ε; vFunction is the state value max over actions — the bridge between the table and the value functions of section 5:
trait Q extends ((State, Action) => Reward):
def actions: Set[Action]
def update(s: State, a: Action, v: Reward): Q
def bestPolicy: Policy = s => actions.maxBy(this(s, _))
def epsPolicy(f: Probability): Policy = _ match
case _ if Stochastics.drawFiltered(_ < f) => Stochastics.uniformDraw(actions)
case s => bestPolicy(s)
def vFunction: State => Reward = s => actions.map(this(s, _)).max
trait LearningProcess:
def system: System
def gamma: Double
def alpha: Double
def epsilon: Double
def q0: Q
def updateQ(s: State, qf: Q): (State, Q)
def learn(episodes: Int, episodeLength: Int, qf: Q): Q
The implementation is the deck's own QRLImpl.QLearning — the update of section 8 transcribed line by line, with a tail-recursive episode runner:
case class QLearning(
override val system: QSystem,
override val gamma: Double,
override val alpha: Double,
override val epsilon: Double,
override val q0: Q) extends LearningProcess:
override def updateQ(s: State, qf: Q): (State, Q) =
val a = qf.epsPolicy(epsilon)(s)
val (r, s2) = system.environment(s, a)
val vr = (1 - alpha) * qf(s, a) + alpha * (r + gamma * qf.vFunction(s2))
val qf2 = qf.update(s, a, vr)
(s2, qf2)
@tailrec
final override def learn(episodes: Int, length: Int, qf: Q): Q =
@tailrec
def runSingleEpisode(in: (State, Q), episodeLength: Int): (State, Q) =
if episodeLength == 0 || system.terminal(in._1) then in
else runSingleEpisode(updateQ(in._1, in._2), episodeLength - 1)
episodes match
case 0 => qf
case e => learn(e - 1, length, runSingleEpisode((system.initial, qf), length)._2)
The facade wires the grid example — the one of section 6 — with rewards and jumps as partial functions, and prints the v-function and the greedy policy after learning:
object TryQMatrix extends App:
import u09.model.QMatrix.Move.*
import u09.model.QMatrix.*
val rl: QMatrix.Facade = Facade(
width = 5, height = 5,
initial = (0, 0),
terminal = { case _ => false },
reward = { case ((1, 0), _) => 10; case ((3, 0), _) => 5; case _ => 0 },
jumps = { case ((1, 0), _) => (1, 4); case ((3, 0), _) => (3, 2) },
gamma = 0.9, alpha = 0.5, epsilon = 0.3, v0 = 1)
val q0 = rl.qFunction
println(rl.show(q0.vFunction, "%2.2f"))
val q1 = rl.makeLearningInstance().learn(10000, 100, q0)
println(rl.show(q1.vFunction, "%2.2f"))
println(rl.show(s => q1.bestPolicy(s).toString, "%7s"))
The deck's results — the v-table printed by learn(10000, 100, q0) — and the parameter lesson:
22.0 24.4 22.0 19.4 17.5
19.8 22.0 19.8 17.8 16.0
17.8 19.8 17.8 16.0 14.4
16.0 17.8 16.0 14.4 13.0
14.4 16.0 14.4 13.0 11.7
> < < < <
> ^ < < <
> ^ < < <
> ^ < < <
> ^ < < <
parameters: exploration is key here — ε = 0.3, α = 0.5, γ = 0.9
it creates the optimal policy rather quickly (in 50 episodes of length 50)
optimal v-table requires much more episodes
The v-table is consistent with Bellman optimality, which is a good way to validate your own runs: v(1,0) = 10 + γ·v(1,4) = 10 + 0.9·16.0 = 24.4 (the reward is received on any action taken from (1,0), which jumps to (1,4)); v(3,0) = 5 + 0.9·v(3,2) = 5 + 0.9·16.0 = 19.4; v(0,0) = 0 + 0.9·v(1,0) = 0.9·24.4 ≈ 22.0 (move right into the reward cell); v(2,0) = 0.9·24.4 ≈ 22.0 (move left). The policy arrows are noisier: with ε = 0.3 the learned greedy policy comes from a finite run, so ties and near-ties flip between runs — the shape (everything pointing towards the two reward cells) is what is stable.
The advanced deck (Aguzzi, "Advanced Topics in Reinforcement Learning") starts from the three walls that tabular RL hits: large state spaces ("the number of states grows combinatorially with the problem size"; "memory issue: we cannot explicitly store all states and their values; data issue: many states are rarely or never visited during training; learning issue: no chance to generalize if each state is treated as an isolated entry in a table"), continuous action spaces ("no enumeration: we cannot compute and compare a value for every possible action; no argmax by search: selecting the best action is now an optimization problem"), and generalisation ("ability to perform well on unseen states, tasks, or environments... memorizing trajectories or opponent behaviors is not enough"). The numbers of the deck make it visceral: Go has ~10170 possible states against ~1080 atoms in the universe; chess has ~1044 states, "total space required ∼ 1034 terabytes".
Deep Reinforcement Learning (DRL) is "the use of deep neural networks to approximate the value function / policy", with three key features matching the three walls: "value function approximation (instead of tables) — handle large state space; policy gradient (instead of Q-Learning) — handle continuous action space; deep neural networks — handle generalization (representation learning)". The value-based vs policy-based split: value-based algorithms "learn a value function, typically V(s) or Q(s,a); the policy is obtained indirectly by choosing the action with the highest estimated value: a* = arg maxa Q(s, a)" — great for discrete actions, does not transfer to continuous actions; policy-based algorithms "learn directly a parametrized policy π(a|s)... typically through policy-gradient methods" (REINFORCE, PPO) — "the method optimizes the decision rule itself, rather than estimating values first and extracting a policy afterwards".
Deep Q-Learning is "Q-Learning, but the Q-table is replaced by a neural approximator": Q(s, a, θ) ≈ Q*(s, a). The naive version is unstable, for two reasons:
L(θ) = E[(ynaive − Q(s,a,θ))²] with ynaive = r + γ maxa′ Q(s′, a′, θ)).The two stabilisations are the heart of DQN (Mnih et al., 2013):
y = r + γ maxa′ Q(s′, a′, θ−) with the frozen θ−, train the online network on L(θ) = E[(y − Q(s,a,θ))²], and every C steps copy θ− ← θ. "The target is fixed for C steps, so the prediction network is no longer chasing a target that moves at every update."Exploration uses ε-greedy with decay: the behaviour policy (with probability ε a random action, otherwise greedy w.r.t. Q(s,a,θ)) is decoupled from the target policy ("the update still pushes the network toward the greedy policy induced by Q"); "high ε early on broadens state-action coverage while the Q-function is still inaccurate; then ε is reduced, often down to a small floor εmin, to shift from exploration to exploitation". This works precisely because "DQN is off-policy: it can learn from replayed transitions collected with older behaviour policies and different ε values".
The algorithm: (1) initialize the replay buffer D, the online parameters θ, copy θ− ← θ; (2) for each step, observe st, select at with the ε-greedy behaviour policy, execute, observe rt and st+1, store (st, at, rt, st+1) in D; (3) sample a minibatch, set yi = ri if s′i is terminal else ri + γ maxa′ Q(s′i, a′, θ−), update θ by minimising (yi − Q(si, ai, θ))², and every C steps copy θ− ← θ. Limits: "works only for discrete action spaces; sample inefficiencies". Extensions: Double DQN ("reduce overestimation bias by decoupling action selection and action evaluation in the target"), Prioritized Experience Replay ("sample the transitions from the replay buffer according to their TD-error"), Rainbow DQN ("combine several DQN improvements in a single agent").
The working example is CartPole: state st = (xt, ẋt, θt, θ̇t) — cart position, cart velocity, pole angle, angular velocity; actions: push left or right; reward 1 if the episode continues, 0 if it terminates — "maximizing return means surviving for many consecutive steps". The companion codebase (advanced-reinforcement-learning-asmd-code) shows the whole pipeline in Scala: the Agent/Learner abstractions (with the key distinction between behavioural and optimal policy — the ε-greedy split in code), the ReplayBuffer storing exactly the (s, a, r, s′, done) tuples, the DQN as "a compact MLP that outputs one Q-value per discrete action", and DeepQAgent with its two explicit networks, the terminal mask zeroing the future term, and the scheduler deciding when to sync the target network.
Q(s,a,θ); the two instabilities (correlated samples, moving target) are treated by the replay buffer and the frozen target network; ε-greedy decays from exploration to exploitation. Extensions (Double DQN, Prioritized Experience Replay, Rainbow) refine the same loop.Multi-Agent Reinforcement Learning (MARL) is the extension of the chapter to many learners: "multiple agents learn to take the right actions (policy) to maximise a reward signal", with applications from videogames and traffic control to swarm robotics, trading, energy management and environmental monitoring. The step of abstraction: "from MDPs to stochastic games".
The stochastic game (a.k.a. Markov game) is the common fully-observable model:
S = ⟨N, S, {A_i}_{i∈N}, P, {R_i}_{i∈N}, ρ₀⟩ with N = {1, ..., N}
S: global environment state · A_i: action space of agent i, joint action A = A₁ × ... × A_N
P(s′ | s, a): transition model · R_i(s, a, s′): reward of agent i · ρ₀: initial-state distribution
The repeated Rock–Paper–Scissors example fixes the reading: N = 2, both action spaces {Rock, Paper, Scissor}, "state tracks the last joint action: S ⊂ (A₁ ∪ {⊥}) × (A₂ ∪ {⊥})", deterministic transitions; the payoff matrix is the classic zero-sum one (Rock vs Paper: −1, +1, etc.). One step of evolution: at time t the environment is in st; the agents choose the joint action at = (a¹t, ..., a^Nt); the environment samples st+1 ∼ P(·|st, at); each agent receives rit+1 = Ri(st, at, st+1). The model is "idealised": "in many MARL problems agent i only sees a local observation oit", so it is "mainly a conceptual tool for understanding interaction". Common refinements: POSG (partially observable stochastic games), Dec-POMDP (cooperative partial observability), extensive-form games, mean-field games (large populations).
How to read a MARL task — the deck's four questions: "Are rewards aligned? (cooperative vs competitive); Who acts and who learns? (decentralized vs centralized); Are the agents symmetric? (homogeneous vs heterogeneous); Is coordination only implicit? (environment dynamics vs communication)." Changing any dimension changes the algorithm class. "Rock–Paper–Scissors is competitive: same actions, opposite incentives. The next alignment task is cooperative: shared reward, coordination challenge."
The case study is align the agents (in the codebase, BoundedWorld): "several agents move on the same grid with local actions: up, down, left, right, or stay; the team objective is simple: end up on the same row. The reward is shared by all agents: if they are aligned, everyone gets 0; otherwise, everyone gets −1" (r¹ = ... = r^N = −1 vs r¹ = ... = r^N = 0). The implementation details matter: each agent sees a relative state RelativeState(rowDiff, colDiff) — "the agent does not need the whole grid configuration: it only needs a local description of where the others are with respect to itself. This creates symmetry: the agents are homogeneous, execution is naturally decentralised, and later parameter sharing becomes plausible."
The lecture then compares three ways to learn the same task:
What richer settings may require: "communication: agents exchange messages, not only actions; CTDE: centralized training with decentralized execution; heterogeneity: different roles, action spaces, or policy classes; function approximation: the repo's sharedDeepQLearner() keeps the same sharing idea with a neural approximator".
The lab deck (09-Lab) condenses the whole chapter into one slide: "MDP is essentially DTMC plus actions/rewards, and the goal of maximising cumulative reward; optimal policy can be found by Bellman equations, which badly scale in practice — large state-space is addressable by Dynamic Programming (iterative algorithms); unknown model or non-Markovianity is addressable by Monte Carlo approaches (simulation). Q-learning: mixed DP and MC, with an off-policy learning that keeps improving the Q-table; Deep Q-learning: represents Q-table by a DNN, with additional ingredients to properly converge; MARL: many agents call for a wider model and specific algorithms."
asmd-public-models (the course repo); import it in IntelliJ as an SBT project; look at scala/u09/examples; run TryQLearningMatrix ("it should produce the expected matrix with directions"); check how variations of key parameters (ε, γ, α, episode length) affect learning; check how learning gets more difficult as the grid size increases.advanced-reinforcement-learning-asmd-code; import it as an SBT project; look at scala/it/unibo/gym for Deep Q-Learning (the CartPole of section 10); look at scala/it/unibo/examples for MARL (the BoundedWorld alignment task of section 11).| Task | What it asks |
|---|---|
| DESIGN BY Q-LEARNING | Change the environment to support the notion of "corridor with obstacles" and make your robot learn to "zigzag walk" to avoid them: update the QMatrix to also accept obstacles; make it impossible to move in the direction of an obstacle and give a negative reward if the robot tries; check if the agent learns to zigzag. "By changing the environment, state, and rewards (adding holes, items, enemies, moving obstacles) you can make your 'robot' learn virtually anything": program-by-learning a robot to collect items one at a time and return, or to move obstacles to hide from enemies. |
| DESIGN BY MARL | Update the row-alignment example with an obstacle in the middle of the system (or more than one) and make the agents learn to coordinate to avoid it: start with a fixed obstacle and design the reward so it is low when an agent approaches it; extend by changing the state space, e.g. adding a vision range (8 cells) and checking obstacles only within that range. |
The arc of this chapter is the arc from modelling to learning: DTMC (probabilistic evolution, chapter 10) → MDP (actions + rewards) → exact solution (Bellman) → learning (DP/MC/TD) → Q-learning → deep (DQN) and multi-agent (MARL) extensions. A strong presentation takes one problem — the grid robot or the alignment task — and walks it through all the rungs, ending with the connection the deck announces: RL policies can be learned inside the simulators of chapter 12 and deployed as the self-organising logic of chapter 14 — the "bootstrap discussions on collective learning and aggregate computing" promised on the first slide.
Two steps: add a notion of "action" performed by an external entity (agent) whose outcome can be probabilistic (DTMC with actions, → ⊆ S × A × [0,1] × S), then add a numerical reward on each arrow. The MDP is ⟨S, A, R, →⟩ with → ⊆ S × A × [0,1] × R × S — "essentially: DTMCs + rewarded actions" — with the sanity condition that for every state and action either it is a deadlock or the outgoing probability sums to 1, and at most one arc per action between two states.
A policy is a selection of which action to take at each state. From S1, always waiting gives k·r_w after k choices; sending has 99% probability to give r_s and 1% to give r_f, plus the reward obtainable in the remaining k−1 choices, recursively. Because of the Markov property the decision cannot depend on the past. MDPs are aimed at computing those estimates and the corresponding policies.
Model-based RL: the agent knows a model of the environment, but it is typically too big (defaults to MDP). Model-free RL: the agent does not know the environment and proceeds by trial-and-error — discovering by exploration the effect of actions and recalling it for the future.
All goals can be thought of as the maximisation of the expected value of the cumulative sum of a scalar reward signal. Return: G_t = Σ_{k=0..T} γ^k R_{t+k+1}, with 0 ≤ γ ≤ 1. γ measures the relative value of future rewards: γ = 0 is myopic; episodic tasks may use γ = 1; continuing tasks need γ < 1 (finite sum).
The state should summarise the past compactly so past states are never needed: Markovian dynamics p(s′, r|s, a) := Pr{R_{t+1}=r, S_{t+1}=s′ | S_t, A_t}. Derived: expected reward r(s, a) = Σ p(s′, r|s, a)·r; transition probability p(s′|s, a) = Σ_r p(s′, r|s, a); expected reward under a policy r_π(s) = Σ_a π(a|s) r(s, a).
v_π(s) = E_π[G_t | S_t = s] = E_π[Σ_k γ^k R_{t+k+1} | S_t = s] and q_π(s, a) = E_π[G_t | S_t = s, A_t = a]; one derives from the other. Bellman: v_π(s) = Σ_a π(a|s) Σ_{s′,r} p(s′, r|s, a) [r + γ·v_π(s′)] — a system of n equations in n variables with a unique solution, costly to compute.
Dynamic Programming: model-based, iterates v₀ → v₁ → ... to the optimum via the Bellman theorem (converges, impractical with many states). Monte Carlo: model-free, learns from sampled episodes without knowing p; exploring start or ε-soft policies guarantee exploration; updates are weighted averages. Temporal Difference: combination — learns from raw experience like MC but updates estimates from other learned estimates like DP, without full episodes; Q-learning (off-policy) and SARSA (on-policy) are members.
Q(S_t, A_t) := (1−α)Q(S_t, A_t) + α[R_{t+1} + γ max_a Q(S_{t+1}, a)]. Procedure: initialise Q (0 on terminal); per episode choose A via an explorative policy (ε-greedy), take the action, observe R and S′, update Q, move on, end at terminal. It is off-policy because the target uses the greedy action at S_{t+1} (max_a Q(S_{t+1}, a)), not the action the behaviour policy actually took — so it can learn the optimal policy while exploring.
model.QRL is a family trait with types and template methods (Environment, MDP, Policy, System, Q, LearningProcess); model.QRLImpl provides implementations; examples.TryQMatrix is the facade for grid examples. Q extends (State, Action) => Reward with update, bestPolicy (actions.maxBy), epsPolicy (ε-random), vFunction (max). QLearning implements updateQ with the exact Q-learning formula and a tail-recursive learn. TryQMatrix configures the 5×5 grid (rewards +10 and +5 with jumps, γ=0.9, α=0.5, ε=0.3, v0=1) and prints the learned v-table and policy.
Correlation: consecutive transitions are temporally correlated, so minibatches are not i.i.d. Moving target: both the target y = r + γ max Q(s′,a′,θ) and the prediction depend on the same changing parameters θ. Fixes: a replay buffer D stores (s,a,r,s′) and samples random minibatches (breaks correlation, reuses experience, better matches SGD's i.i.d. assumption); a fixed target network with parameters θ⁻ computes the target for C steps, then θ⁻ ← θ, so the prediction network is not chasing a moving target.
The behaviour policy selects actions with probability ε at random, otherwise greedily w.r.t. Q(s,a,θ); the target policy (what the update pushes towards) is the greedy policy induced by Q. High ε early broadens coverage while Q is inaccurate; ε decays to a floor ε_min to shift to exploitation. This works because DQN is off-policy: the replay buffer mixes experience collected under older behaviour policies and different ε values.
A stochastic game is ⟨N, S, {A_i}, P, {R_i}, ρ₀⟩: global state, joint action space A₁ × ... × A_N, transition model, per-agent rewards. Three ways: independent learners (each keeps its own Q-table — the environment becomes non-stationary); central controller (one learner chooses the whole joint action — with boundSize 10 and 6 agents: ~10¹² states and 5⁶ = 15625 joint actions); parameter sharing (all agents update the same learning object, executing locally — the sweet spot for symmetric cooperative tasks, e.g. via relative states).