Optimal control theory: LQR, LQG, iLQR and model predictive control
Derive LQR and Riccati recursion, combine control with Kalman estimation in LQG, and study iLQR, MPC, HJB and Pontryagin.
After this lesson you can
- Derive finite- and infinite-horizon LQR Riccati recursion and optimal gain.
- Prove LQR closed-loop stability with a Lyapunov function.
- Combine LQR and a Kalman filter in LQG and explain separation and its limits.
- Implement iLQR for a nonlinear swing-up problem.
- Design MPC, including sampling variants, and compare with learned policies.
Before you start
- 22Backward inductionBellman optimality equationState-value and action-value functionsMuJoCo physics simulationPPO training loop
- 14Kalman filter
- 03Linear ODE systemsStability of equilibriaLyapunov functionAdjoint sensitivity method
- 06Quadratic programmingNewton's method
- 09Reverse-mode automatic differentiation
- 02Positive definite matrixQuadratic form
Control starts with a model
When system dynamics are approximately known, you can use them to plan actions before trying them. The linear quadratic regulator (LQR) solves a case with linear dynamics and quadratic cost. This solution does not cover every constraint or robotic phenomenon, but provides an exact reference for studying planning and learning.
State summarizes position, velocity or other variables; is control. In discrete time, . Feedback yields closed-loop matrix . Zero equilibrium is asymptotically stable if all its eigenvalues have modulus below one. Complete controllability requires to have rank ; stabilizability is weaker, requiring control of unstable modes. In continuous time the corresponding condition requires negative real parts of closed-loop eigenvalues.
The figure simulates a nonlinear cart-pole model with cart mass 1, pole mass 0.1, half-length 0.5, gravity 9.8 and Euler step 0.02. Angle zero is upright. Gain comes from 800 Riccati steps on the linearization at that equilibrium, with and selectable . Force is limited to in nonlinear simulation; the calculated LQR does not incorporate that bound. The push slider represents an initial angular disturbance, not force applied during motion. If the cart leaves the window or angle moves far from zero, the figure shows the linear model’s local limit, not a global guarantee.
Riccati backward
For horizon , take and . The problem is to minimize
By backward induction, assume and substitute the dynamics. Terms in form a quadratic with matrix . Completing the square gives unique minimum , with
This is the Riccati recursion. In code solve the linear system for instead of forming an inverse. If cost has cross terms or dynamics an offset, linear and constant terms also appear; ignoring them changes the problem. A force constraint turns local minimization into a constrained problem, and clipping afterward is generally not the constrained optimum.
To see the calculation, write and . The part depending on is . Since is positive definite, rewrite it as . The first term vanishes only at ; combining the second with remaining terms in yields . This also explains gain sign: can be positive or negative depending on matrices, but the law is always in this convention.
Units matter. An entry of penalizes a state-coordinate square and a force square, so changing meters to centimeters without transforming weights changes the problem. If control is expensive relative to error, the regulator usually acts less strongly; heavily penalizing angle prioritizes keeping it near equilibrium. These are intuitions for the same dynamics and scale, not universal rules for each component of . Inspect trajectory, saturation and accumulated cost.
Here state is position and velocity of a double integrator with step 0.1: , , , and horizon 60. The ellipse represents ; the animation begins at terminal time, when there is no action yet. Curves show both components of against steps remaining. The stationary reference is approximated with 1200 backward steps; convergence depends on system assumptions and is not automatic for arbitrary matrices.
For an undiscounted infinite horizon, if is stabilizable and detectable, a stabilizing positive semidefinite solution of the algebraic Riccati equation exists under standard assumptions. With and , the stabilizing solution is positive definite. Calling this solution and gain and , the equation gives
Thus is positive for and its change in one closed-loop transition is . It is a strict Lyapunov function when . If is only semidefinite, the inequality need not be strict for every state; a detectability argument is needed, not simply declaring positive definite. The proof concerns the linear system without saturation or noise; the physical system inherits only a local guarantee under additional conditions.
Estimate and control: LQG
Now suppose and , with independent zero-mean Gaussian noises, known covariances, Gaussian initial state and known parameters. The Kalman filter maintains conditional mean and its covariance. Under the LQG separation principle, given past observations and actions and expected quadratic cost, optimal control uses : design control and estimator gains separately.
Separation depends on assumptions: linear dynamics and measurements, known noise and parameters, and no additional constraints changing the problem. It does not claim estimated state is exact or the system robust to every model error. Persistent noise generally prevents the state converging to zero on every trajectory; with suitable stability a stationary distribution can exist. Nominal LQG stability also does not imply perfect-state LQR robustness margins: Doyle constructed a counterexample without guaranteed uniform margins. Evaluate parameter errors and saturation separately.
In a scalar update with measurement , if prior variance is and measurement-noise variance , filter gain is . Posterior estimate is and posterior variance . Then predict using known control: and . The lab uses this measurement-before-action convention. Higher dimensions use matrices and numerically stable covariance updates; an unobserved sensor or wrong model is not corrected by choosing another LQR gain.
iLQR and trajectory optimization
In a nonlinear system , iLQR starts from a nominal trajectory, linearizes along it and quadratically approximates cost-to-go. Each backward step solves a local quadratic problem for correction . A forward pass tries for several values; only actual cost reduction is accepted. Positive regularization in the control matrix helps solve ill-conditioned steps, but does not guarantee a global optimum.
DDP also includes second derivatives of dynamics weighted by the value derivative; iLQR omits them and retains linearized dynamics. This matters under strong nonlinearity. Constraints require specific treatment, such as a bounded subproblem; clipping an unconstrained solution changes the step and can invalidate the local model. The next lab imposes no torque limit and therefore does not claim physically realizable motion with a limited motor. Tedrake develops connections to trajectory optimization and adjoints.
At one step, call the Jacobians of and , and future-value derivatives . The local approximation contains and , plus . With invertible , open-loop correction is and local feedback gain . The implementation uses when solving both systems and adjusts if factorization fails or no search reduces cost. This section’s gains use a different sign from LQR’s convention; here already includes the minus sign.
MPC: plan and replan
In model predictive control (MPC), at each instant optimize a sequence over steps, apply only the first action, observe the new state and solve again. This allows state and action constraints, but a numerical optimizer can fail or find no feasible solution. Suitable terminal cost and terminal set help reason about stability and recursive feasibility; arbitrary choices provide no such guarantees.
The toy vehicle advances 0.18 units per step in and chooses lateral displacement between −0.18 and 0.18. Search compares 25 constant lateral actions repeated over the entire horizon; it does not enumerate all possible sequences. A circular obstacle of radius 0.55 is centered at and collision has a finite penalty, not a hard constraint. The model predicts lateral displacement without error or noise; actual trajectory multiplies response by and adds deterministic normal innovations of scale (noise). The goal is . Each step displays selected plan and path already executed. A penalty and limited search do not guarantee avoiding the obstacle; the indicator checks only discrete states, so an intersection between samples may go unnoticed. Try a short horizon.
Sampling MPC evaluates many sequences in the model. CEM fits a distribution to lowest-cost sequences. MPPI uses an exponentially cost-weighted mean and, depending on formulation, includes an importance correction between proposal and prior. Temperature controls weight concentration; few effective rollouts can yield a noisy estimate. The lab uses a Gaussian prior on latent sequences and applies actuator bounds after sampling; correction is calculated before clipping. Formulation details and limits are compared with Williams and colleagues.
A short horizon may not see an obstacle until there is no room left to avoid it. A longer one extends foresight but increases simulated steps and can accumulate more model error. Actuator bounds must apply to the same control the simulator receives, and safety constraints must be checked on executed trajectory, not just nominal plan. Under noise or parameter uncertainty, one nominal prediction does not represent all futures: multiple scenarios, robust margins or other techniques may be needed depending on the problem.
Continuous time and connection to RL
For and stage cost , the finite-horizon Hamilton–Jacobi–Bellman equation is , with terminal condition. If is not differentiable, an appropriate interpretation such as viscosity solution is needed; classical derivation requires regularity.
The Pontryagin principle introduces Hamiltonian and costate with . For an interior minimum, ; with constraints minimize the Hamiltonian over admissible controls. These are necessary conditions under assumptions, not a general proof of global optimality. Where is differentiable and corresponding conditions hold, along the optimal trajectory: the costate is the adjoint propagating sensitivity backward.
LQR is also an RL problem with known dynamics and reward equal to negative cost: its optimal value and policy provide a reference for checking estimators and optimizers. Learning the model introduces identification errors affecting the controller; learning a model-free policy requires sufficient experience and evaluation. Recht analyzes the relationship. Neither simulator access nor success from one initial state guarantees transfer to a real system.
Lab: Riccati, LQG and iLQR
The first cell computes Riccati backward and compares with scipy.linalg.solve_discrete_are. It then implements general iLQR with central finite differences, regularization and line search on a toy pendulum. State is , angle zero down and π up; step is 0.05 and torque is unlimited. Initial controls use a fixed seed to break symmetry. Terminal cost is periodic in angle and penalizes velocity, so −π represents the same physical equilibrium as π. Displayed figures are from this simulation, not the MuJoCo pendulum.
import numpy as np
from scipy.linalg import solve_discrete_are
def riccati(A,B,Q,R,Qf,horizon):
P=np.array(Qf,dtype=float)
matrices=[P.copy()]; gains=[]
for _ in range(horizon):
K=np.linalg.solve(R+B.T@P@B,B.T@P@A)
P=Q+A.T@[email protected]@P@B@K
P=(P+P.T)/2
gains.append(K); matrices.append(P.copy())
return list(reversed(matrices)),list(reversed(gains))
def grad_hess(f,z,h=1e-4):
z=np.asarray(z,dtype=float); n=z.size; grad=np.empty(n); H=np.empty((n,n))
f0=float(f(z)); basis=np.eye(n)*h
for i in range(n):
fp=float(f(z+basis[i])); fm=float(f(z-basis[i]))
grad[i]=(fp-fm)/(2*h); H[i,i]=(fp-2*f0+fm)/h**2
for j in range(i):
v=(f(z+basis[i]+basis[j])-f(z+basis[i]-basis[j])-f(z-basis[i]+basis[j])+f(z-basis[i]-basis[j]))/(4*h*h)
H[i,j]=H[j,i]=v
return grad,H
def jacobian(f,z,h=1e-5):
n=z.size; eye=np.eye(n)*h
return np.column_stack([(f(z+eye[i])-f(z-eye[i]))/(2*h) for i in range(n)])
def ilqr(dynamics,stage,terminal,x0,U_init,max_iter=80):
U=np.array(U_init,dtype=float,copy=True); x0=np.asarray(x0,float); T,m=U.shape; n=x0.size
def rollout(us):
xs=np.empty((T+1,n)); xs[0]=x0; total=0.
for t in range(T):
total+=stage(xs[t],us[t]); xs[t+1]=dynamics(xs[t],us[t])
total+=terminal(xs[-1]); return xs,float(total)
X,cost=rollout(U); history=[cost]; regularization=1e-4
for iteration in range(max_iter):
Vx,Vxx=grad_hess(terminal,X[-1]); feed=[None]*T; feedback=[None]*T
try:
for t in range(T-1,-1,-1):
z=np.r_[X[t],U[t]]; F=jacobian(lambda w:dynamics(w[:n],w[n:]),z); A,B=F[:,:n],F[:,n:]
g,H=grad_hess(lambda w:stage(w[:n],w[n:]),z)
Qx=g[:n]+A.T@Vx; Qu=g[n:]+B.T@Vx
Qxx=H[:n,:n]+A.T@Vxx@A; Quu=H[n:,n:]+B.T@Vxx@B
Qux=H[n:,:n]+B.T@Vxx@A
reg=Quu+regularization*np.eye(m)
np.linalg.cholesky(reg)
k=-np.linalg.solve(reg,Qu); K=-np.linalg.solve(reg,Qux)
feed[t],feedback[t]=k,K
Vx=Qx+K.T@Quu@k+K.T@Qu+Qux.T@k
Vxx=Qxx+K.T@Quu@K+K.T@Qux+Qux.T@K
Vxx=(Vxx+Vxx.T)/2
except np.linalg.LinAlgError:
regularization*=10
if regularization>1e8: break
continue
accepted=False
for step in (1.,.5,.25,.1,.05,.01):
xn=np.empty_like(X); un=np.empty_like(U); xn[0]=x0; new_cost=0.
for t in range(T):
un[t]=U[t]+step*feed[t]+feedback[t]@(xn[t]-X[t])
new_cost+=stage(xn[t],un[t]); xn[t+1]=dynamics(xn[t],un[t])
new_cost+=terminal(xn[-1])
if np.isfinite(new_cost) and new_cost<cost:
improvement=cost-new_cost; X,U,cost=xn,un,float(new_cost)
history.append(cost); regularization=max(regularization/2,1e-8); accepted=True
break
if not accepted:
regularization*=10
if regularization>1e8: break
elif improvement < 1e-7: break
return X,U,history
A=np.array([[1.2]]); B=np.array([[1.]])
Q=np.array([[1.]]); R=np.array([[1.]])
P,K=riccati(A,B,Q,R,Q,80)
dare=solve_discrete_are(A,B,Q,R)
print('Riccati escalar',P[0].item(),'SciPy',dare.item(),'ganancia',K[0].item())
# Modelo explícito: ángulo cero abajo, pi arriba, aceleración angular y torque.
dt=.05
def pendulum(x,u):
theta,omega=x
acceleration=-np.sin(theta)-.1*omega+u[0]
return np.array([theta+dt*omega,omega+dt*acceleration])
def stage(x,u): return .05*(1+np.cos(x[0]))+.002*x[1]**2+.002*u[0]**2
def terminal(x): return 15*(1+np.cos(x[0]))+.5*x[1]**2
rng=np.random.default_rng(24)
U0=rng.normal(0,.5,(80,1))
X,U,history=ilqr(pendulum,stage,terminal,np.array([0.,0.]),U0)
print('iLQR iteraciones aceptadas',len(history)-1,'coste inicial y final',history[0],history[-1],
'estado final',X[-1], 'torque máximo',np.abs(U).max())
assert all(a>b for a,b in zip(history,history[1:]))The next scalar model uses process-noise variance 0.04 and measurement-noise variance 0.25 with a reproducible seed. The filter first updates its estimate from the measurement, then applies LQR and predicts the next state. Its averages diagnose one trajectory, not a precise population-performance estimate.
import numpy as np
from scipy.linalg import solve_discrete_are
# Modelo escalar parcialmente observado: x+ = 1.2 x + u + w, y = x + v.
a,b,q,r=1.2,1.,1.,1.
P=float(solve_discrete_are(np.array([[a]]),np.array([[b]]),np.array([[q]]),np.array([[r]]))[0,0])
K=b*P*a/(r+b*b*P)
rng=np.random.default_rng(24)
x=.5
estimate=0.
variance=1.
sq_error=[]
controls=[]
for t in range(80):
y=x+rng.normal(0,.5) # varianza de medición 0.25
gain=variance/(variance+.25)
estimate=estimate+gain*(y-estimate)
variance=(1-gain)*variance
sq_error.append((x-estimate)**2)
u=-K*estimate
controls.append(u)
x=a*x+b*u+rng.normal(0,.2) # varianza de proceso 0.04
estimate=a*estimate+b*u
variance=a*a*variance+.04
print('P',P,'K',K,'error cuadrático medio de estimación',np.mean(sq_error),
'media de control cuadrático',np.mean(np.square(controls)))Lab: MPPI in MuJoCo versus LQR and PPO
Install NumPy, SciPy, PyTorch and gymnasium[mujoco]==1.4.0. The first cell adapts the prior lesson’s continuous PPO to InvertedPendulum-v5, trains and saves its actor with frozen observation statistics and action bounds. The preceding lesson supplies no checkpoint for this environment: it is trained here, not assumed to exist. ORYON_PPO_OUT selects the folder. Full mode uses five seeds and one million transitions per seed; ORYON_QUICK=1 uses one seed, 1024 transitions and 64-step episodes. Quick mode checks the pipeline, not that PPO has learned.
import gc
import json
import math
import time
import os
import random
import traceback
from pathlib import Path
import gymnasium as gym
import mujoco
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal
if not gym.__version__.startswith('1.4.'):
raise RuntimeError('Este laboratorio usa el contrato vectorial de Gymnasium 1.4.x')
quick = os.environ.get('ORYON_QUICK', '0') == '1'
env_id = os.environ.get('ORYON_PPO_ENV', 'InvertedPendulum-v5')
if env_id not in ('InvertedPendulum-v5',):
raise ValueError('ORYON_PPO_ENV no es uno de los tres entornos')
case = os.environ.get('ORYON_PPO_CASE', 'default')
cases = ('default','no_adv_norm','no_orthogonal','no_value_clip','no_lr_anneal','no_obs_norm')
if case not in cases:
raise ValueError('ORYON_PPO_CASE desconocido')
run_sb3 = os.environ.get('ORYON_PPO_SB3', '0') == '1'
out = Path(os.environ.get('ORYON_PPO_OUT', 'oryon-ppo'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seeds = [0] if quick else [0,1,2,3,4]
n_env, horizon, updates = (2,16,32) if quick else (8,250,500)
epochs, minibatch = (2,16) if quick else (10,250)
eval_every, eval_episodes = (8,2) if quick else (10,5)
gamma, lam, clip, vf_clip, lr, target_kl = .99, .95, .2, .2, .0003, .03
value_coef, entropy_coef, max_norm = .5, 0., .5
def make_env():
return gym.make(env_id,max_episode_steps=64) if quick else gym.make(env_id)
class RunningMoments:
def __init__(self, shape=()):
self.mean = np.zeros(shape, dtype=np.float64)
self.var = np.ones(shape, dtype=np.float64)
self.count = 1e-4
def update(self, batch):
batch = np.asarray(batch, dtype=np.float64)
if batch.shape[0] == 0:
return
m, v, n = batch.mean(axis=0), batch.var(axis=0), batch.shape[0]
delta = m-self.mean
total = self.count+n
self.var = (self.var*self.count+v*n+delta**2*self.count*n/total)/total
self.mean = self.mean+delta*n/total
self.count = total
def normalized_obs(obs, moments):
if case == 'no_obs_norm':
return np.asarray(obs,dtype=np.float32)
return np.clip((obs-moments.mean)/np.sqrt(moments.var+1e-8),-10.,10.).astype(np.float32)
def tensor(x):
return torch.as_tensor(np.asarray(x),dtype=torch.float32,device=device)
def network(obs_dim, output_dim, gain):
layers = [nn.Linear(obs_dim,64),nn.Tanh(),nn.Linear(64,64),nn.Tanh(),nn.Linear(64,output_dim)]
if case != 'no_orthogonal':
for layer in layers:
if isinstance(layer,nn.Linear):
nn.init.orthogonal_(layer.weight, math.sqrt(2))
nn.init.zeros_(layer.bias)
nn.init.orthogonal_(layers[-1].weight,gain)
return nn.Sequential(*layers)
class Actor(nn.Module):
def __init__(self, obs_dim, act_dim):
super().__init__()
self.net=network(obs_dim,act_dim,.01)
self.log_std=nn.Parameter(torch.zeros(act_dim))
def dist(self,x):
mean=self.net(x)
return Normal(mean,self.log_std.clamp(-5.,1.).exp().expand_as(mean))
class Critic(nn.Module):
def __init__(self, obs_dim):
super().__init__()
self.net=network(obs_dim,1,1.)
def forward(self,x):
return self.net(x).squeeze(-1)
def gae(reward,value,successor_value,term,trunc):
out=np.zeros_like(reward,dtype=np.float64)
carry=np.zeros(reward.shape[1],dtype=np.float64)
for t in range(len(reward)-1,-1,-1):
delta=reward[t]+gamma*(~term[t])*successor_value[t]-value[t]
carry=delta+gamma*lam*(~(term[t]|trunc[t]))*carry
out[t]=carry
return out
assert np.allclose(gae(np.array([[1.],[2.]]),np.zeros((2,1)),np.array([[3.],[9.]]),
np.array([[False],[True]]),np.array([[True],[False]])),[[3.97],[2.]])
def successor(next_obs,term,trunc,info):
done=term|trunc
result=np.asarray(next_obs).copy()
if done.any():
if 'final_obs' not in info or '_final_obs' not in info:
raise RuntimeError('Falta final_obs en SAME_STEP')
if not np.array_equal(info['_final_obs'],done):
raise RuntimeError('Máscara final_obs incompatible')
for i in np.flatnonzero(done):
result[i]=info['final_obs'][i]
return result
def evaluate(actor,obs_moments,seed,low,high):
env=make_env()
result=[]
try:
for i in range(eval_episodes):
eval_seed=100000+1000*seed+i
obs,_=env.reset(seed=eval_seed)
total,length=0.,0
while True:
with torch.no_grad():
z=actor.dist(tensor(normalized_obs(obs,obs_moments)).unsqueeze(0)).mean[0].cpu().numpy()
action=(low+(np.tanh(z)+1.)*(high-low)/2.).astype(env.action_space.dtype)
obs,r,term,trunc,_=env.step(action)
total+=float(r); length+=1
if term or trunc:
result.append({'seed':eval_seed,'return_raw':total,'length':length,
'terminated':bool(term),'truncated':bool(trunc)})
break
finally:
env.close()
return result
def train(seed):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
shuffle=np.random.default_rng(seed+50000)
envs=gym.vector.SyncVectorEnv([make_env for _ in range(n_env)],
autoreset_mode=gym.vector.AutoresetMode.SAME_STEP)
try:
obs,_=envs.reset(seed=[seed*1000+i for i in range(n_env)])
low,high=envs.single_action_space.low,envs.single_action_space.high
if not np.isfinite(low).all() or not np.isfinite(high).all() or np.any(high<=low):
raise ValueError('Límites de acción inválidos')
obs_moments=RunningMoments(obs.shape[1:]); reward_moments=RunningMoments()
discounted=np.zeros(n_env); episode_return=np.zeros(n_env)
actor=Actor(obs.shape[1],low.size).to(device); critic=Critic(obs.shape[1]).to(device)
optimizer=torch.optim.Adam(list(actor.parameters())+list(critic.parameters()),lr=lr,eps=1e-5)
history=[]
started=time.monotonic()
for update in range(1,updates+1):
learning_rate=lr if case=='no_lr_anneal' else lr*(1-(update-1)/updates)
for group in optimizer.param_groups: group['lr']=learning_rate
scale=float(np.sqrt(reward_moments.var+1e-8))
observations,latents,old_logps,values,next_values=[],[],[],[],[]
rewards,terms,truncs,raw_states,return_samples=[],[],[],[],[]
completed,saturated,components=[],0,0
for _ in range(horizon):
raw_states.append(obs.copy())
state=tensor(normalized_obs(obs,obs_moments))
with torch.no_grad():
dist=actor.dist(state); z=dist.sample(); value=critic(state)
action=(low+(torch.tanh(z).cpu().numpy()+1.)*(high-low)/2.).astype(envs.single_action_space.dtype)
next_obs,reward,term,trunc,info=envs.step(action)
real_next=successor(next_obs,term,trunc,info)
next_value=critic(tensor(normalized_obs(real_next,obs_moments)))
observations.append(state); latents.append(z); old_logps.append(dist.log_prob(z).sum(-1))
values.append(value.cpu().numpy()); next_values.append(next_value.cpu().numpy())
rewards.append(np.clip(reward/scale,-10.,10.)); terms.append(term.copy()); truncs.append(trunc.copy())
discounted=gamma*discounted+reward
return_samples.append(discounted.copy())
episode_return+=reward
done=term|trunc
for i in np.flatnonzero(done):
completed.append(float(episode_return[i])); episode_return[i]=0.; discounted[i]=0.
saturated+=int(np.count_nonzero((action==low)|(action==high))); components+=action.size
obs=next_obs
old_values=np.stack(values)
advantages=gae(np.stack(rewards),old_values,np.stack(next_values),np.stack(terms),np.stack(truncs))
targets=advantages+old_values
if case!='no_adv_norm':
advantages=(advantages-advantages.mean())/(advantages.std()+1e-8)
states=torch.cat(observations); z=torch.cat(latents); old_logp=torch.cat(old_logps)
old_v=tensor(old_values.reshape(-1)); adv=tensor(advantages.reshape(-1)); target=tensor(targets.reshape(-1))
samples=states.shape[0]; used_epochs=0; last_norm=0.
for epoch in range(epochs):
for indices in np.array_split(shuffle.permutation(samples),math.ceil(samples/minibatch)):
ix=torch.as_tensor(indices,dtype=torch.long,device=device)
dist=actor.dist(states[ix]); new_logp=dist.log_prob(z[ix]).sum(-1)
ratio=torch.exp(new_logp-old_logp[ix])
policy_loss=-torch.minimum(ratio*adv[ix],ratio.clamp(1-clip,1+clip)*adv[ix]).mean()
value=critic(states[ix]); err=(value-target[ix]).square()
if case!='no_value_clip':
clipped=old_v[ix]+(value-old_v[ix]).clamp(-vf_clip,vf_clip)
err=torch.maximum(err,(clipped-target[ix]).square())
value_loss=.5*err.mean(); entropy=dist.entropy().sum(-1).mean()
loss=policy_loss+value_coef*value_loss-entropy_coef*entropy
if not torch.isfinite(loss): raise FloatingPointError('Pérdida no finita')
optimizer.zero_grad(set_to_none=True); loss.backward()
last_norm=float(nn.utils.clip_grad_norm_(list(actor.parameters())+list(critic.parameters()),max_norm,error_if_nonfinite=True))
optimizer.step()
used_epochs+=1
with torch.no_grad():
zratio=actor.dist(states).log_prob(z).sum(-1)-old_logp
approx_kl=float((torch.expm1(zratio)-zratio).mean())
if not math.isfinite(approx_kl): raise FloatingPointError('KL no finita')
if approx_kl>target_kl: break
with torch.no_grad():
dist=actor.dist(states); logratio=dist.log_prob(z).sum(-1)-old_logp
ratio=logratio.exp(); predicted=critic(states).cpu().numpy()
entropy=float(dist.entropy().sum(-1).mean())
clipfrac=float(((ratio-1).abs()>clip).float().mean())
approx_kl=float((torch.expm1(logratio)-logratio).mean())
variance=float(np.var(targets))
explained=None if variance<=1e-12 else float(1-np.var(targets.reshape(-1)-predicted)/variance)
obs_moments.update(np.concatenate(raw_states,axis=0))
reward_moments.update(np.concatenate(return_samples))
with torch.no_grad():
renormalized=tensor(normalized_obs(np.concatenate(raw_states,axis=0),obs_moments))
changed_logratio=actor.dist(renormalized).log_prob(z).sum(-1)-old_logp
changed_ratio=changed_logratio.exp()
kl_after_obs_update=float((torch.expm1(changed_logratio)-changed_logratio).mean())
clipfrac_after_obs_update=float(((changed_ratio-1).abs()>clip).float().mean())
if not math.isfinite(kl_after_obs_update) or not math.isfinite(clipfrac_after_obs_update):
raise FloatingPointError('Diagnóstico tras actualizar normalización no finito')
row={'update':update,'transitions':update*samples,'epochs_used':used_epochs,
'learning_rate':learning_rate,'completed_train_returns_raw':completed,
'reward_scale_used':scale,'latent_entropy':entropy,'approx_kl_k3':approx_kl,
'clipfrac':clipfrac,'explained_variance':explained,'last_gradient_norm_before_clip':last_norm,
'approx_kl_k3_after_obs_update':kl_after_obs_update,
'clipfrac_after_obs_update':clipfrac_after_obs_update,
'saturated_action_components':saturated,'action_components':components}
if update%eval_every==0 or update==updates:
row['evaluation']=evaluate(actor,obs_moments,seed,low,high)
row['elapsed_seconds']=time.monotonic()-started
print(env_id,case,'semilla',seed,'paso',update,'retorno bruto',
np.mean([e['return_raw'] for e in row['evaluation']]),'KL k3',approx_kl,flush=True)
history.append(row)
torch.save({'actor':actor.state_dict(),'obs_mean':torch.as_tensor(obs_moments.mean),
'obs_var':torch.as_tensor(obs_moments.var),'low':torch.as_tensor(low),
'high':torch.as_tensor(high),'obs_dim':obs.shape[1],'act_dim':low.size,
'quick':quick,'environment':env_id,'seed':seed,'transitions':updates*n_env*horizon},out / f'ppo-inverted-seed{seed}.pt')
return {'method':'PPO desde cero','case':case,'seed':seed,'history':history}
finally:
envs.close()
def train_sb3(seed):
try:
import stable_baselines3 as sb3
from stable_baselines3.common.vec_env import DummyVecEnv, VecNormalize
except ImportError as exc:
raise RuntimeError('ORYON_PPO_SB3=1 requiere instalar stable-baselines3 compatible') from exc
# Los cambios de caso también se aplican si SB3 expone el parámetro equivalente.
vec=VecNormalize(DummyVecEnv([make_env for _ in range(n_env)]),
norm_obs=(case!='no_obs_norm'),norm_reward=True,gamma=gamma)
try:
vec.seed(seed*1000)
schedule=lr if case=='no_lr_anneal' else lambda remaining: lr*remaining
model=sb3.PPO('MlpPolicy',vec,seed=seed,device=str(device),learning_rate=schedule,
n_steps=horizon,batch_size=minibatch,n_epochs=epochs,gamma=gamma,
gae_lambda=lam,clip_range=clip,clip_range_vf=None if case=='no_value_clip' else vf_clip,
normalize_advantage=(case!='no_adv_norm'),ent_coef=entropy_coef,vf_coef=value_coef,
max_grad_norm=max_norm,target_kl=target_kl,
policy_kwargs={'ortho_init':case!='no_orthogonal'},verbose=0)
model.learn(total_timesteps=updates*n_env*horizon)
vec.training=False
env=make_env(); episodes=[]
try:
for i in range(eval_episodes):
eval_seed=100000+1000*seed+i; obs,_=env.reset(seed=eval_seed); total=0.; length=0
while True:
norm=vec.normalize_obs(np.asarray(obs)[None,:])[0]
action,_=model.predict(norm,deterministic=True)
obs,reward,term,trunc,_=env.step(action)
total+=float(reward); length+=1
if term or trunc:
episodes.append({'seed':eval_seed,'return_raw':total,'length':length,
'terminated':bool(term),'truncated':bool(trunc)})
break
finally:
env.close()
return {'method':'Stable-Baselines3 PPO','version':sb3.__version__,'case':case,'seed':seed,
'transitions':int(model.num_timesteps),'evaluation':episodes}
finally:
vec.close()
report={'quick':quick,'environment':env_id,'case':case,'gymnasium':gym.__version__,
'mujoco':mujoco.__version__,'torch':torch.__version__,'numpy':np.__version__,'device':str(device),
'seeds':seeds,'configuration':{'n_env':n_env,'horizon':horizon,'updates':updates,
'epochs':epochs,'minibatch':minibatch,'gamma':gamma,'lambda':lam,'clip':clip,
'value_clip':None if case=='no_value_clip' else vf_clip,'target_kl':target_kl,
'learning_rate_initial':lr,'lr_annealing':case!='no_lr_anneal',
'advantage_normalization':case!='no_adv_norm','observation_normalization':case!='no_obs_norm',
'orthogonal_initialization':case!='no_orthogonal','reward_normalization':True,
'reward_clip':10.,'entropy_coef':entropy_coef,'value_coef':value_coef,
'autoreset':'SAME_STEP','evaluation_episodes':eval_episodes,
'quick_time_limit':64 if quick else None,
'evaluation_seed':'100000 + 1000 * train_seed + episode'},'runs':[]}
for seed in seeds:
for method in (('scratch','sb3') if run_sb3 else ('scratch',)):
failure=None
try:
result=train(seed) if method=='scratch' else train_sb3(seed)
except Exception:
failure=traceback.format_exc()
finally:
gc.collect()
if torch.cuda.is_available(): torch.cuda.empty_cache()
if failure is not None: raise RuntimeError('Falló el laboratorio:\n'+failure)
report['runs'].append(result)
filename='ppo-'+env_id+'-'+case+'.json'
(out/filename).write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
print('Informe:',out/('ppo-'+env_id+'-'+case+'.json'))npm run lab and open the connection link.The next cell loads only checkpoints for the mode and seed, computes LQR from a numerical linearization of the MuJoCo model, and uses the same simulator for MPPI rollouts. One trial transition is compared with the real transition before planning. Full state is used, without measurement noise or model error; keep this information and model advantage in mind against PPO. Planning objective penalizes state and action, incorporates LQR terminal cost and penalizes crossing the angle threshold; evaluation reward is the environment’s. Action clipping applies to the sampled latent sequence and the importance ratio is calculated in that latent space. The ratio’s common constant cancels in weight normalization. Minimum cost is subtracted before exponentiation.
Quick mode has two evaluation episodes per method, 16 sequences of horizon 8 and a 64-step limit. Full mode uses five training seeds, five episodes per seed, 128 sequences of horizon 20 and up to 1000 steps per episode: it can use substantial CPU time. Methods receive the same evaluation seeds; PPO training cost is not included in evaluation time. The cell records return, duration, termination and truncation per episode. This is a local comparison under these settings, not a universal algorithm comparison. Full-benchmark results are not presented without running it.
import json, os, time
from pathlib import Path
import gymnasium as gym
import mujoco
import numpy as np
from scipy.linalg import solve_discrete_are
import torch
from torch import nn
quick=os.getenv('ORYON_QUICK','0')=='1'
root=Path(os.getenv('ORYON_PPO_OUT','oryon-ppo'))
seeds=[0] if quick else list(range(5))
episodes=2 if quick else 5
horizon=8 if quick else 20
samples=16 if quick else 128
max_steps=64 if quick else 1000
temperature=.5
sigma=1.
torch.set_num_threads(1)
env=gym.make('InvertedPendulum-v5',max_episode_steps=max_steps)
model=env.unwrapped.model
frame_skip=env.unwrapped.frame_skip
lo,hi=env.action_space.low,env.action_space.high
if model.nq!=2 or model.nv!=2 or model.nu!=1 or model.na!=0:
raise ValueError('El ejemplo requiere el modelo sin actuadores dinámicos')
scratch=mujoco.MjData(model)
def simulate(state,action):
# Se reinician también las variables auxiliares; aquí no hay actuadores con estado.
mujoco.mj_resetData(model,scratch)
scratch.qpos[:]=state[:2]; scratch.qvel[:]=state[2:]
scratch.ctrl[:]=np.clip(action,lo,hi)
mujoco.mj_forward(model,scratch)
for _ in range(frame_skip): mujoco.mj_step(model,scratch)
return np.r_[scratch.qpos.copy(),scratch.qvel.copy()]
# La transición aislada debe coincidir con una transición del entorno real.
obs,_=env.reset(seed=123)
action=np.array([.37],dtype=np.float32)
pred=simulate(obs,action)
actual,_,_,_,_=env.step(action)
print('Error máximo de transición:',np.max(np.abs(pred-actual)))
assert np.allclose(pred,actual,rtol=0,atol=1e-9)
zero=np.zeros(4); h=1e-5
A=np.column_stack([(simulate(zero+np.eye(4)[i]*h,[0.])-simulate(zero-np.eye(4)[i]*h,[0.]))/(2*h) for i in range(4)])
B=((simulate(zero,[h])-simulate(zero,[-h]))/(2*h)).reshape(4,1)
Q=np.diag([.2,20.,.05,.2]); R=np.array([[.1]])
P=solve_discrete_are(A,B,Q,R)
K=np.linalg.solve(R+B.T@P@B,B.T@P@A)
print('LQR K:',K,'radio espectral:',max(abs(np.linalg.eigvals(A-B@K))))
def actor_from_checkpoint(path,seed):
if not path.exists(): raise FileNotFoundError('Entrena primero el PPO del laboratorio: '+str(path))
saved=torch.load(path,map_location='cpu',weights_only=True)
if (saved['obs_dim']!=4 or saved['act_dim']!=1 or saved['quick']!=quick or
saved['environment']!='InvertedPendulum-v5' or saved['seed']!=seed or
saved['transitions']!=(1024 if quick else 1_000_000)):
raise ValueError('Checkpoint PPO incompatible')
net=nn.Sequential(nn.Linear(4,64),nn.Tanh(),nn.Linear(64,64),nn.Tanh(),nn.Linear(64,1))
# La clase Actor contiene la red bajo net.* y una log_std aprendida.
net.load_state_dict({key[4:]:v for key,v in saved['actor'].items() if key.startswith('net.')})
net.eval()
mean=saved['obs_mean'].numpy(); var=saved['obs_var'].numpy()
if not np.allclose(saved['low'].numpy(),lo) or not np.allclose(saved['high'].numpy(),hi):
raise ValueError('Límites del checkpoint incompatibles')
def action(obs):
normalized=np.clip((obs-mean)/np.sqrt(var+1e-8),-10,10).astype(np.float32)
with torch.no_grad(): latent=net(torch.as_tensor(normalized)[None])[0].numpy()
return (lo+(np.tanh(latent)+1)*(hi-lo)/2).astype(np.float32)
return action
def stage(state,action):
return float(state@Q@state+.1*action[0]**2)
def plan(obs,nominal,rng):
noise=rng.normal(0,sigma,(samples,horizon,1))
candidates=nominal[None,:,:]+noise
costs=np.empty(samples)
for j in range(samples):
state=obs.copy(); cost=0.
for t in range(horizon):
action=np.clip(candidates[j,t],lo,hi)
cost+=stage(state,action)
state=simulate(state,action)
if not np.isfinite(state).all() or abs(state[1])>.2:
cost+=100.; break
cost+=float(state@P@state) if np.isfinite(state).all() else 1000.
# Corrección de razón entre prior N(0,σ²) y propuesta N(U,σ²),
# definida para la secuencia latente antes de recortar al actuador.
cost+=temperature/(sigma*sigma)*float(np.sum(nominal*noise[j]))
costs[j]=cost
weights=np.exp(-(costs-costs.min())/temperature)
weights/=weights.sum()
updated=np.sum(weights[:,None,None]*candidates,axis=0)
selected=np.clip(updated[0],lo,hi).astype(np.float32)
shifted=np.vstack((updated[1:],np.zeros((1,1))))
return selected,shifted
records=[]
try:
for seed in seeds:
actor=actor_from_checkpoint(root/f'ppo-inverted-seed{seed}.pt',seed)
for method in ('LQR','MPPI','PPO'):
for ep in range(episodes):
obs,_=env.reset(seed=100000+1000*seed+ep)
rng=np.random.default_rng(200000+1000*seed+ep)
nominal=np.zeros((horizon,1))
total=0.; length=0; started=time.perf_counter()
while True:
if method=='LQR': action=np.clip(-(K@obs),lo,hi).astype(np.float32)
elif method=='PPO': action=actor(obs)
else: action,nominal=plan(obs,nominal,rng)
obs,reward,term,trunc,_=env.step(action)
total+=float(reward); length+=1
if term or trunc: break
row={'seed':seed,'episode':ep,'method':method,'return':total,'length':length,
'terminated':bool(term),'truncated':bool(trunc),'seconds':time.perf_counter()-started}
records.append(row); print(row,flush=True)
finally:
env.close()
root.mkdir(parents=True,exist_ok=True)
(root/'control-comparison.json').write_text(json.dumps({'quick':quick,'gymnasium':gym.__version__,
'mujoco':mujoco.__version__,'horizon':horizon,'samples':samples,'records':records},indent=2),encoding='utf-8')npm run lab and open the connection link.Exercises
Step 1 of 3. Which matrix multiplies the quadratic in u?
Step 1 of 3. What identity follows by substituting K in Riccati?
import numpy as np
def ilqr(dynamics, cost, x0, U_init):
pass