Partial observability: POMDPs, belief states and policies with memory
Formalize partially observable decision problems, derive Bayesian belief updates and finite-horizon value functions, and compare exact, approximate, particle-based and recurrent approaches.
After this lesson you can
- Formalize a problem with hidden state as a POMDP and update belief states.
- Prove that the finite-horizon optimal value is piecewise linear and convex in the belief.
- Implement exact alpha-vector value iteration, PBVI and QMDP and compare their policies.
- Explain POMCP and particle representations of belief.
- Train recurrent PPO and compare it with observation stacking in memory tasks.
Before you start
- 22Markov decision processValue iterationBellman optimality equationValue of informationDeep Q-NetworkPPO training loop
- 14Forward algorithm (filtering)Bootstrap particle filterSequential importance samplingParticle resampling
- 10Monte Carlo Tree SearchUpper Confidence bounds applied to Trees
- 17LSTM cellGated recurrent unitTruncated backpropagation through time
- 06Linear programming
Deciding without seeing the state
A robot hears a door but does not know where it is in a corridor. A defender sees noisy alerts without knowing an attacker’s actual situation. The physical state may be Markovian even when the latest observation is not: two histories ending with the same sound can imply very different positions. A policy that receives only that sound must choose the same action for both histories, even if different actions would be preferable.
In the tiger problem there are two doors. A tiger is behind one of them; opening its door costs 100, opening the other yields 10, and listening costs 1. The sound identifies the correct side with probability . Opening a door resets the tiger’s position uniformly. Listening accumulates evidence before committing, but each listen has a cost. The sequence makes the value of information a decision rather than a free improvement in accuracy.
The figure maintains a hidden position sampled with a seed. “Simulate listen” produces a sound at the selected accuracy; the two sound buttons also force observations for exploring the filter, but manual choices are not sensor samples. Opening reveals whether the tiger was behind the door and shows the undiscounted sum of the opening reward and listening costs. It then resamples the tiger and resets the belief. The horizontal axis is the belief that the tiger is on the left and the vertical axis is plan value; the region below is clipped to enlarge the decision region. The indicator compares discounted plans with three steps remaining after each observation; it does not represent a horizon decreasing during a game. The immediate opening values exclude the future value of the reset.
At accuracy , try three sounds from the left. After the first two the belief is approximately and the best three-step plan still starts by listening. After the third it rises to and the plan starts by opening the right door. The change depends on the horizon, cost and discount: there is no universally appropriate number of listens. Then change accuracy to : sounds no longer change the prior because both states make them equally likely.
Model and filter
A finite partially observable Markov decision process (POMDP) specifies states , actions , observations , transition , observation , expected reward , discount and an initial distribution. Here the observation arrives after the transition. Other conventions are possible, but the equation and code indices must change together. The underlying MDP is Markovian in the hidden state, though not necessarily in the observation. Kaelbling, Littman and Cassandra develop the planning model and policies conditioned on observations.
The belief is a state distribution conditioned on the available history . After action , predict and then correct:
The denominator is the predictive probability of the observation. If it is zero, the model considers that observation impossible and the division is undefined. This operation is the forward filter of an HMM with controlled transitions. Kalman filtering performs the same operation for a linear Gaussian model, where mean and covariance suffice to represent the distribution.
The equation uses all the signal the agent receives within . If an observed reward reveals additional information about the state, include it in the joint observation and its likelihood. Ignoring it can discard information. The filter also depends on the action actually taken. In robotics, a missing action record or a misspecified dynamic can make the computed belief wrong even when Bayes’ rule is implemented correctly.
With a uniform prior, two conditionally independent sounds from the left give
Independence is conditional on the tiger’s side and assumes listening does not move it. Probabilities cannot simply be added. One sound from each side returns the belief to uniform by symmetry.
The posterior odds multiply by upon hearing left, and by its reciprocal upon hearing right. In logarithms, each observation adds or subtracts . The first figure stores this sum and then converts it to probability, avoiding a belief rounded to one becoming artificially stuck when contrary evidence appears. Changing accuracy resets the experiment and its seed because past observations would have different likelihoods.
The belief induces a belief MDP: its reward is and its transition to occurs with probability . Apply the Bellman optimality equation and value iteration in this continuous space. The finite-horizon operator with zero terminal value is
Belief is sufficient when the model and initial distribution are known: it summarizes the distribution of all relevant futures, conditioned on future actions. Uncertainty about the model parameters is separate; when they are unknown they must also be inferred or included in an augmented state.
Envelopes of contingent plans
At a finite horizon, a deterministic policy is a tree that chooses an action and then a continuation for each observation. For a fixed tree , expected return conditioned on each initial state forms a vector . Value at a belief is linear: . The optimal policy can change with and takes the maximum over finitely many lines or hyperplanes. Randomization cannot improve that maximum: its value averages deterministic-tree values and cannot exceed the largest. Therefore the optimal value is piecewise linear and convex on the belief simplex.
The induction also gives an algorithm. With , select an action and, for each observation , a vector . The new vector has components
In the expected continuation value, observation probability cancels the filter denominator. Enumerating continuation combinations covers every tree, and . The maximum of linear functions is convex: for , each plane at does not exceed . The proof requires finite spaces and a finite horizon; it does not give the same shape to an arbitrary approximation or a minimized cost function.
To see the cancellation, write . If , then . Thus, for a continuation , the contribution is , linear in . Impossible observations contribute zero to the expectation and do not require a defined posterior. Since a continuation can be chosen independently for each observation, maximizing the sum amounts to enumerating combinations. This justifies the componentwise backup above.
Enumeration grows quickly. A vector that is never strictly better than its rivals may be removed without changing the envelope, taking care with ties and numerical tolerances. To check, maximize a margin subject to , and for every rival . This is a linear program; a positive optimal margin certifies a region where the vector is needed.
The figure enumerates finite-horizon plans and removes those that are not optimal on any interval of the belief segment. With two states, interval intersections can test dominance without solving the general linear program. The control overlays pruned candidates without repeating identical planes; the candidate count includes duplicates. Numerical tolerances can lose extremely small intervals. The horizontal axis is belief and the vertical axis is value; the graph clips values below when present. Colors mark a plan’s first action, not necessarily its later actions.
Lab: exact plans, PBVI and QMDP
Represent and . Both doors reset the tiger uniformly and yield an uninformative observation; listening leaves the state unchanged. The filter rejects zero-probability observations. Each backup enumerates continuations by observation. Pruning uses a linear program over the simplex and keeps vectors with a region of strict advantage after removing duplicates.
import itertools
import numpy as np
from scipy.optimize import linprog
gamma, precision = .95, .85
T = np.array([np.eye(2), np.full((2, 2), .5), np.full((2, 2), .5)])
O = np.array([[[precision, 1-precision], [1-precision, precision]],
[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]]])
R = np.array([[-1., -1.], [-100., 10.], [10., -100.]])
def belief_update(b, a, o):
predicted = np.asarray(b) @ T[a]
weights = predicted * O[a, :, o]
if weights.sum() <= 0:
raise ValueError('Observación imposible')
return weights / weights.sum()
b = np.array([.5, .5])
b = belief_update(belief_update(b, 0, 0), 0, 0)
print('Dos sonidos a izquierda:', np.round(b, 6))def backup(a, branches):
return R[a] + gamma * sum(T[a] @ (O[a, :, o] * branches[o]) for o in range(2))
def prune(pairs, tol=1e-9):
unique = []
for action, alpha in pairs:
if not any(np.allclose(alpha, old, rtol=0, atol=tol) for _, old in unique):
unique.append((action, alpha))
kept = []
for i, (action, alpha) in enumerate(unique):
others = [x for j, (_, x) in enumerate(unique) if j != i]
if not others:
kept.append((action, alpha))
continue
inequalities = np.array([np.r_[other-alpha, 1.] for other in others])
result = linprog([0, 0, -1], A_ub=inequalities,
b_ub=np.zeros(len(others)), A_eq=[[1, 1, 0]],
b_eq=[1], bounds=[(0, None), (0, None), (None, None)],
method='highs')
if not result.success:
raise RuntimeError(result.message)
if result.x[-1] > tol:
kept.append((action, alpha))
return kept
def exact_step(pairs):
vectors = [alpha for _, alpha in pairs]
return prune([(a, backup(a, choice)) for a in range(3)
for choice in itertools.product(vectors, repeat=2)])
exact = [(0, np.zeros(2))]
exact = exact_step(exact)
print('Horizonte 1:', len(exact), 'vectores')The next cell advances two horizons; run it in order with the others. The PBVI grid in the comparison is selected explicitly and does not represent every reachable belief. An error measured on the evaluation grid is a discrepancy at those points, not a global bound.
exact = exact_step(exact)
print('Horizonte 2:', len(exact), 'vectores')
exact = exact_step(exact)
print('Horizonte 3:', len(exact), 'vectores')def pbvi_step(pairs, beliefs):
vectors = [v for _, v in pairs]
chosen = []
for b in beliefs:
candidates = []
for a in range(3):
branches = []
for o in range(2):
weights = (b @ T[a]) * O[a, :, o]
branches.append(vectors[int(np.argmax([weights @ v for v in vectors]))])
candidates.append((a, backup(a, branches)))
chosen.append(max(candidates, key=lambda pair: b @ pair[1]))
return prune(chosen)
def qmdp(horizon):
value = np.zeros(2)
for _ in range(horizon):
q = R + gamma * np.einsum('ask,k->as', T, value)
value = q.max(axis=0)
return q
beliefs = np.array([[p, 1-p] for p in np.linspace(0, 1, 21)])
pbvi = [(0, np.zeros(2))]
for _ in range(3):
pbvi = pbvi_step(pbvi, beliefs)
grid = np.array([[p, 1-p] for p in np.linspace(0, 1, 101)])
v_exact = np.array([max(b @ alpha for _, alpha in exact) for b in grid])
v_pbvi = np.array([max(b @ alpha for _, alpha in pbvi) for b in grid])
q = qmdp(3)
print('PBVI vectores:', len(pbvi), 'error máximo en la malla:', round(max(v_exact-v_pbvi), 6))
print('Valor exacto en prior uniforme:', round(v_exact[50], 6))
print('Valores QMDP en prior uniforme:', np.round(q @ grid[50], 6))
print('Acción QMDP en prior uniforme:', ['escuchar', 'abrir izquierda', 'abrir derecha'][int(np.argmax(q @ grid[50]))])Now change the model, not just the tiger belief. This two-state control problem has asymmetric transitions, action-dependent sensors and different rewards. The matrices are an example defined here to exercise the algorithm, not robot data. Values are compared on a grid and the matrices are restored for the remaining cells.
old_T, old_O, old_R = T, O, R
try:
T = np.array([[[.9,.1],[.2,.8]], [[.7,.3],[.1,.9]], [[.6,.4],[.4,.6]]])
O = np.array([[[.8,.2],[.3,.7]], [[.7,.3],[.2,.8]], [[.5,.5],[.5,.5]]])
R = np.array([[1.,-2.],[-1.,2.],[0.,0.]])
control_exact = [(0,np.zeros(2))]
control_pbvi = [(0,np.zeros(2))]
for _ in range(2):
control_exact = exact_step(control_exact)
control_pbvi = pbvi_step(control_pbvi, beliefs)
control_gap = max(max(b @ v for _,v in control_exact) -
max(b @ v for _,v in control_pbvi) for b in grid)
control_q = qmdp(2)
print('Vectores exactos:',len(control_exact),'PBVI:',len(control_pbvi))
print('Diferencia máxima en malla:',round(control_gap,6))
print('Acciones en prior uniforme: exacta',
max(control_exact,key=lambda pair:grid[50] @ pair[1])[0],
'QMDP',int(np.argmax(control_q @ grid[50])))
finally:
T, O, R = old_T, old_O, old_RApproximation and planning
Point-based value iteration (PBVI) retains backups for a finite set of beliefs, usually selected for reachability. At each point it selects, for every action and observation, the continuation maximizing the contribution weighted by the next state’s unnormalized probability. It then chooses the best action at that point. Vectors still represent feasible plans, but their envelope can lose value between points. Pineau, Gordon and Thrun describe the method and belief selection; a uniform grid need not cover high-dimensional spaces efficiently.
QMDP solves the MDP as if the state were fully revealed after the current action and computes . This assumption removes the future benefit of acquiring information: by construction, the next decision already knows the state. It does not imply that listening is never chosen. In the symmetric tiger problem above with a uniform belief, the future term is equal for listening and opening, but the immediate reward of listening is versus for opening. QMDP chooses to listen even without valuing what it learns. The distinction matters: listening can be preferred because it avoids the immediate penalty, not because the policy correctly anticipates the observation.
In the horizon-three run, QMDP gives values , and to listening, opening left and opening right. The exact optimal value at the prior is . The difference illustrates the optimism of assuming full revelation, not a calculation error in the exact policy. In the tiger problem QMDP may keep listening at a central belief because it never includes the observation’s effect when valuing future plans. A measurement action with positive cost and no other consequence is discarded by QMDP if the alternative of not measuring has the same transition and reward before the cost: both share the fully observed future value.
What is observation worth?
For identical transitions and immediate rewards, compare revealing an observation before choosing a continuation with not revealing it. The average posterior equals the predictive belief, . By convexity,
This is Jensen’s inequality: with information one can imitate the decision made without it, or choose another if the signal changes the best continuation. Improvement can be zero if all posteriors lie in the same linear region of the value. It does not follow that every listening action is optimal: its cost and any effect on dynamics must be considered. This is the value of information applied to sequential decisions.
POMCP combines a generative simulator, state particles and Monte Carlo tree search over action-observation histories. Each simulation starts from a root-belief particle, traverses the tree and backs up rewards; UCT balances estimation and exploration at each node. History nodes group compatible simulated states: the tree decides using available information rather than the hidden state known by the simulator. Its formulation and experiments are in Silver and Veness. With few particles, an unlikely observation can leave the root without support. Reinvigoration with compatible samples requires an appropriate proposal or model and does not automatically make a biased distribution an exact posterior.
The example has five positions, two visually identical doors at 1 and 3, a center at 2 and boundaries at 0 and 4. Initial particles are split between the doors. Moving costs , hitting a boundary costs , and opening terminates with reward at the center or elsewhere. The sensor identifies boundary, door or center with probability and splits the remainder between the other categories. You select the observation; it is not presented as a real trajectory. The filter propagates each particle and resamples according to its likelihood. A search of 500 simulations at depth four selects with UCT and displays visit counts and mean returns, not exact values or a guarantee that the most visited action is optimal. This illustration rebuilds the tree after each update, uses discount , exploration coefficient and zero value at the depth cutoff; it does not reproduce every detail of the published POMCP implementation.
Try moving right and observing center. Before the observation, possible positions are 2 and 4 with equal weight. The exact calculation assigns the center ; the observation favors it and makes opening more attractive. The initial-seed sample has 186 of 200 particles at the center, a finite approximation rather than the exact value. Observing a boundary favors 4 and moving left becomes an option. Resampling can duplicate a few particles. Positive likelihood in this example avoids zero total weight, but does not prevent a plausible state from disappearing; a more general filter must detect missing support and decide how to obtain newly conditioned particles.
The bootstrap filter propagates a sample from each state and weights it by likelihood. Sequential importance sampling retains weights; resampling converts those weights into frequencies but loses diversity. Before resampling, effective sample size summarizes concentration of normalized weights: it approaches one when one particle dominates. On its own it does not say whether particles cover every important mode. Reinvigoration can use a proposal conditioned on the new observation and correct its weights, or MCMC rejuvenation that preserves the posterior. Adding uniform states without correcting weights changes the belief and is not equivalent to Bayesian inference.
Learned memory
Stacking the most recent observations gives a policy a finite window, useful when the necessary information fits inside it. A clue appearing long before the decision may be lost. A recurrent policy updates a hidden state from observations and, where applicable, previous actions and rewards. There is no guarantee that this learned vector is a calibrated Bayesian belief.
In the recurrent PPO loop, the rollout must store the hidden state at the start of each fragment and an episode-start mask. At each step, memory for terminated environments is zeroed before incorporating their new observations. The update uses ordered sequences, not shuffled individual samples, since that would break temporal dependence. Truncated BPTT limits gradients to a window. A gradient-free burn-in reconstructs a more consistent hidden state before computing losses, although it does not recover exactly the state of a network whose parameters have changed. True termination and time-limit truncation must be distinguished when bootstrapping.
DRQN adds recurrence to DQN, and R2D2 studies recurrent replay. Both require context reconstruction. An LSTM or GRU can retain useful information without guaranteeing that it learns the filter. Ni, Eysenbach and Salakhutdinov compared a well-tuned recurrent baseline against six specialized methods on 21 environments, reporting better sample efficiency and asymptotic performance on 18. Results depend on tasks, configurations and budgets. They do not establish that any LSTM configuration beats stacking in every environment.
Lab: PPO with and without memory
Implement PPO in PyTorch with three variants: the current observation, the four most recent observations, and an LSTM. In CartPole, only position and angle are shown, not velocities. The discrete T-maze has a corridor of ten advances and a junction: in the corridor the two actions are wait or advance; at the junction they choose left or right and terminate the episode. An initial clue identifies the correct side and vanishes after the first step; a window of four does not contain it at the junction. Choosing gives +1 or -1; advancing gives 0.05, waiting costs 0.05 and exhausting 40 steps without choosing incurs an additional -1. The advancement reward helps learn to reach the junction and is part of this example’s objective. The comparison uses the same transition budget, 64-unit architecture and three seeds. CartPole return counts steps; maze return sums all rewards. Evaluation uses 100 greedy episodes per training run with seeds distinct from training. Run the local cells in order; they need torch, numpy and gymnasium.
The rollout stores initial memory and a mask per step. The update recalculates each complete sequence with current parameters, respecting the masks. Initial hidden states come from the policy that collected the rollout and can become stale between updates; burn-in is not implemented here. Generalized advantage estimation cuts recursion at termination or truncation but removes bootstrap only for termination: at truncation it evaluates the final observation before resetting. The maze’s 40-step limit is part of its finite task and is treated as termination; CartPole’s external limit is treated as truncation. Each block trains for 204,800 transitions per method and seed.
All variants receive only observations, without previous action or reward. This isolates a particular comparison but restricts reconstruction of history in CartPole, whose transitions depend on actions. The loss sums the clipped PPO objective, squared critic error with coefficient and an entropy incentive with coefficient . There is no per-variant hyperparameter search, so an observed difference mixes architecture and sensitivity to this configuration. Each evaluated episode is one measurement within a training seed; the episodes are not 300 independent training replications.
For each transition, the policy ratio is . PPO maximizes the minimum between and . The ratio compares probabilities of the same action under the same history. Shuffling individual observations and resetting the LSTM each time changes that history and makes the comparison inconsistent. The lab preserves order within each fragment, with the stored initial-state approximation noted above. Keeping only the rollout’s final hidden state cannot reconstruct every sequence either.
The advantage estimator combines temporal error with . Here indicates termination or truncation, preventing the advantage from mixing with the next episode. The value has already been set to zero for true termination; for truncation the final observation is evaluated before reset. These masks serve different purposes. The code uses and .
"""Prototipo independiente PPO: T-maze de memoria y CartPole sin velocidades."""
import argparse
import collections
import json
import random
import numpy as np
import gymnasium as gym
import torch
from torch import nn
from torch.distributions import Categorical
torch.set_num_threads(1)
class MemoryMaze:
def __init__(self, length=10):
self.length=length
self.rng=np.random.default_rng()
def reset(self, seed=None):
if seed is not None: self.rng=np.random.default_rng(seed)
self.target=int(self.rng.integers(2)); self.position=0; self.t=0; self.chosen=False; self.success=False
return np.array([2*self.target-1, 0.],np.float32), {}
def step(self, action):
self.t+=1
at_junction=self.position==self.length
chosen=at_junction
self.chosen=chosen; self.success=chosen and action==self.target
progressed=not at_junction and action==1
reward=(1. if action==self.target else -1.) if chosen else (.05 if progressed else -.05)
if progressed: self.position+=1
done=chosen or self.t>=40
if done and not chosen: reward-=1.
return np.array([0., self.position/self.length],np.float32),reward,done,False,{}
class Task:
def __init__(self, name, stack, seed):
self.name=name; self.stack=stack
self.env=gym.make('CartPole-v1') if name=='cartpole' else MemoryMaze()
self.actions=2
self.seed=seed; self.frames=collections.deque(maxlen=stack)
self.reset(first=True)
def observation(self, raw):
return np.asarray(raw[[0,2]] if self.name=='cartpole' else raw,dtype=np.float32)
def reset(self, first=False):
raw,_=self.env.reset(seed=self.seed if first else None)
x=self.observation(raw)
self.frames.clear()
for _ in range(self.stack-1): self.frames.append(np.zeros_like(x))
self.frames.append(x)
return np.concatenate(self.frames)
def step(self, action):
raw,reward,terminated,truncated,_=self.env.step(int(action))
self.frames.append(self.observation(raw))
return np.concatenate(self.frames),float(reward),terminated,truncated
def close(self):
if self.name=='cartpole': self.env.close()
class Policy(nn.Module):
def __init__(self, dim, recurrent, actions):
super().__init__(); self.recurrent=recurrent; self.width=64
self.embed=nn.Sequential(nn.Linear(dim,64),nn.Tanh())
self.lstm=nn.LSTMCell(64,64) if recurrent else None
self.actor=nn.Linear(64,actions); self.critic=nn.Linear(64,1)
def initial(self,n): return (torch.zeros(n,64),torch.zeros(n,64))
def step(self, obs, state, mask):
x=self.embed(obs)
if self.recurrent:
h,c=state; h,c=self.lstm(x,(h*mask[:,None],c*mask[:,None])); state=(h,c); x=h
return self.actor(x),self.critic(x).squeeze(-1),state
def sequence(self, obs, initial, masks):
logits=[]; values=[]; state=initial
for x,mask in zip(obs,masks):
lg,v,state=self.step(x,state,mask);logits.append(lg);values.append(v)
return torch.stack(logits),torch.stack(values)
def evaluate(net, task, stack, seed, episodes=100):
scores=[]; successes=[]; choices=[]
env=Task(task,stack,seed)
for _ in range(episodes):
obs=env.reset(); state=net.initial(1); mask=torch.zeros(1); total=0.
while True:
with torch.no_grad():
logits,_,state=net.step(torch.tensor(obs)[None],state,mask)
action=int(logits.argmax(-1).item())
obs,r,term,trunc=env.step(action);total+=r;mask=torch.ones(1)
if term or trunc:break
scores.append(total)
if task=='maze': successes.append(env.env.success);choices.append(env.env.chosen)
env.close()
return float(np.mean(scores)),float(np.std(scores,ddof=1)/np.sqrt(len(scores))), (float(np.mean(successes)) if successes else None), (float(np.mean(choices)) if choices else None)
def train(task, kind, steps, seed):
torch.manual_seed(seed);np.random.seed(seed);random.seed(seed)
n=16; horizon=64; stack=4 if kind=='stack' else 1
envs=[Task(task,stack,seed*100+n0) for n0 in range(n)]
obs=np.stack([env.reset() for env in envs]); dim=obs.shape[1]
net=Policy(dim,kind=='lstm',envs[0].actions);opt=torch.optim.Adam(net.parameters(),lr=3e-4,eps=1e-5)
state=net.initial(n);mask=torch.zeros(n); num_updates=steps//(n*horizon)
for update in range(num_updates):
initial=tuple(x.detach().clone() for x in state)
xs=[]; masks=[]; acts=[]; oldlogs=[]; vals=[]; rewards=[]; nextvals=[]; ends=[]
for _ in range(horizon):
xt=torch.tensor(obs); xs.append(xt); masks.append(mask.clone())
with torch.no_grad():
logits,v,state=net.step(xt,state,mask); dist=Categorical(logits=logits)
action=dist.sample(); log=dist.log_prob(action)
transitions=[env.step(a) for env,a in zip(envs,action.numpy())]
nextobs=np.stack([row[0] for row in transitions]); terms=np.array([row[2] for row in transitions]); done=np.array([row[2] or row[3] for row in transitions])
with torch.no_grad():
_,nv,_=net.step(torch.tensor(nextobs),state,torch.ones(n))
nv=nv*torch.tensor(~terms,dtype=torch.float32)
acts.append(action);oldlogs.append(log);vals.append(v);rewards.append(torch.tensor([row[1] for row in transitions]));nextvals.append(nv);ends.append(torch.tensor(done,dtype=torch.float32))
for i,done_i in enumerate(done):
if done_i: nextobs[i]=envs[i].reset()
obs=nextobs;mask=torch.tensor(~done,dtype=torch.float32)
xs=torch.stack(xs); masks=torch.stack(masks);acts=torch.stack(acts);oldlogs=torch.stack(oldlogs);vals=torch.stack(vals); rewards=torch.stack(rewards);nextvals=torch.stack(nextvals);ends=torch.stack(ends)
advantages=torch.zeros_like(rewards); gae=torch.zeros(n)
for t in reversed(range(horizon)):
delta=rewards[t]+.99*nextvals[t]-vals[t]
gae=delta+.99*.95*(1-ends[t])*gae;advantages[t]=gae
returns=advantages+vals
advantages=(advantages-advantages.mean())/(advantages.std(unbiased=False)+1e-8)
for _ in range(4):
logits,v=net.sequence(xs,initial,masks);dist=Categorical(logits=logits)
ratio=(dist.log_prob(acts)-oldlogs).exp()
loss=-torch.minimum(ratio*advantages,ratio.clamp(.8,1.2)*advantages).mean()+.5*((v-returns)**2).mean()-.01*dist.entropy().mean()
opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(net.parameters(),.5);opt.step()
for env in envs:env.close()
score,se,success,chosen=evaluate(net,task,stack,seed*10000+9000)
return {'task':task,'kind':kind,'seed':seed,'steps':num_updates*n*horizon,'evaluation_episodes':100,'mean_return':score,'standard_error':se,'success_rate':success,'choice_rate':chosen}npm run lab and open the connection link.cartpole_results = [train('cartpole', kind, 204800, seed)
for kind in ['none', 'stack', 'lstm'] for seed in range(3)]
for row in cartpole_results:
print(row)npm run lab and open the connection link.maze_results = [train('maze', kind, 204800, seed)
for kind in ['none', 'stack', 'lstm'] for seed in range(3)]
for row in maze_results:
print(row)npm run lab and open the connection link.In one CPU run with the three stated seeds, mean CartPole returns were 41.96, 43.43 and 43.81 without memory; 27.91, 26.59 and 24.61 with four observations; and 9.48, 9.43 and 9.37 with an LSTM. Under this configuration the recurrent variant performed worse. The experiment does not show that recurrence solves CartPole or by itself identify which hyperparameter explains the difference.
In the T-maze, all three policies reached an exit choice in all 100 episodes of each seed. Without memory, successes were 54, 49 and 58; with four observations, also 54, 49 and 58; with the LSTM they were 100, 100 and 100. The respective mean returns were , and for the first two variants, and for the LSTM. The maximum sums ten advances of and the correct exit of . This environment was designed so that the clue vanishes before the junction. Three seeds and 100 episodes per seed establish neither a perfect success rate outside this evaluation nor general LSTM superiority. The per-episode standard error printed by the program also does not measure variation across training runs.
Exercises
Step 1 of 4. What is the base case?
belief_update(b, a, o, T, O) and particle_filter(particles, a, o, T, O, rng). T[a,s,s2] and O[a,s2,o] are probabilities, b is a normalized distribution, and particles contains equiprobable state indices. The first function predicts and corrects the exact distribution using vectorized operations. The second propagates each particle according to the transition row and resamples with replacement in proportion to the observation likelihood. Use only the supplied rng generator. Each function raises ValueError when its weights sum to zero.import numpy as np
def belief_update(b, a, o, T, O):
pass
def particle_filter(particles, a, o, T, O, rng):
passSummary
- The filter predicts through the transition and corrects using observation likelihood.
- Finite-horizon contingent plans yield value planes; their maximum is piecewise linear and convex. PBVI retains plans suited to a set of beliefs.
- QMDP assumes the state will be revealed after the action and omits the future benefit of observation. POMCP plans using simulator samples and a particle belief.
- An LSTM helps only when training, sequences, masks and evaluation enable learning and use of the required memory.