Module contents
Lesson 1 of 33Review 80 min

Review and map: perceive, estimate, decide and act

Review the tools needed for embodied systems, from rotations and Bayesian filters to multimodal representations, and see why open-loop evaluation does not predict closed-loop behaviour.

After this lesson you can

  • Describe a robot's perception, estimation, decision and action loop and locate each block in the module.
  • Classify each modality by its structure and symmetries.
  • Distinguish joint and coordinated multimodal representations using VLMs and CLIP.
  • Use a numerical example to explain how a small open-loop error can cause a large closed-loop failure.
  • Implement the prediction and update steps of a Bayesian filter on a one-dimensional grid.

Before you start

From predictor to robot

A model can predict the next action in a demonstration well and still knock the object over. When it acts, its error changes the scene it sees next. Building a useful system requires studying the predictor together with sensors, timing, mechanics and the consequences of its actions.

The perception, estimation, decision and action loop turns observations into a state estimate, selects an action and applies it to the world. The new observation closes the loop. The true state includes position and velocity, for example; an image or inertial reading reveals only part of it and may arrive late. Embodiment is this process’s dependence on the body, its sensors and actuators, and its physical interaction with the environment. A policy useful for an arm with a gripper does not automatically transfer to another arm with different joints or limits.

InteractiveTiming is part of the controller
  • Position
  • Reference
5
0.20
0.10
Final position1.01
Vary frequency, latency and noise. The model is a one-dimensional integrator with proportional control and delayed observations; it does not represent a measured robot.

The simulation integrates x˙=u\dot{x}=u with a 0.020.02 s step, reference 11 and control u=3(1−y)u=3(1-y) held between updates. The observation is the stored position at the selected delay, plus asin⁡(17t)a\sin(17t) as a deterministic disturbance. The delay is rounded to the integration step. Increasing frequency does not make an old observation current: each new command may still correct a state that no longer exists. An oscillation here is a property of this model and its parameters, not a universal guarantee about every robot.

In a real system, the camera, estimator and actuator may operate at different frequencies. Record capture, delivery and application times and synchronize clocks; the rate alone does not reveal the age of an observation. A state predictor can compensate for some delay if its model is good enough, but adds uncertainty.

Geometry and error: a practical review

An orthogonal matrix R\mat{R} satisfies R⊤R=I\mat{R}\T\mat{R}=\mat{I}. It preserves inner products and lengths. A proper rotation also requires det⁡R=1\det\mat{R}=1: a reflection is orthogonal too, but reverses orientation. To transform a vector from camera to world coordinates, write xw=Rwcxc+twc\vb{x}_w=\mat{R}_{wc}\vb{x}_c+\vb{t}_{wc} explicitly; the subscript identifies destination and origin. Matrix multiplication composes transformations from right to left.

If y=f(x)\vb{y}=f(\vb{x}) and x\vb{x} is close to μ\vb{\mu}, linearization with the Jacobian J=∂f/∂x\mat{J}=\partial f/\partial\vb{x} gives f(x)≈f(μ)+J(x−μ)f(\vb{x})\approx f(\vb{\mu})+\mat{J}(\vb{x}-\vb{\mu}). For covariance Σx\mat{\Sigma}_x, the output covariance is therefore approximately JΣxJ⊤\mat{J}\mat{\Sigma}_x\mat{J}\T. This is exact for an affine map; for a nonlinear function it is a local approximation and can fail when uncertainty covers a large or multimodal region.

For example, if a camera point has covariance Σc\mat{\Sigma}_c and the rigid transform is known exactly, its covariance in world coordinates is RwcΣcRwc⊤\mat{R}_{wc}\mat{\Sigma}_c\mat{R}_{wc}\T. Fixed translation changes the mean but not the covariance. If the pose is also uncertain, this calculation is insufficient: include it in the input vector and retain its correlations. Units help detect errors: position covariance has units of squared length, whereas a Jacobian of position with respect to angle relates length to radians.

The covariance rule follows directly from the definition. For the perturbation δx=x−μ\delta\vb{x}=\vb{x}-\vb{\mu}, the approximate output is δy≈Jδx\delta\vb{y}\approx\mat{J}\delta\vb{x}. Hence E[δyδy⊤]≈JE[δxδx⊤]J⊤\E[\delta\vb{y}\delta\vb{y}\T]\approx\mat{J}\E[\delta\vb{x}\delta\vb{x}\T]\mat{J}\T. Evaluate J\mat{J} at the linearization point and avoid transforming standard deviations directly as vectors: the full matrix contains correlations and changes shape under the transformation.

Belief, prediction and correction

The belief bt(x)b_t(x) is the distribution of the state conditioned on observations and actions up to tt. Under the Markov and conditionally independent observation assumptions, the Bayesian filter separates motion and measurement:

bˉt(x)=∑x′p(x∣x′,ut−1)bt−1(x′),bt(x)=p(zt∣x)bˉt(x)∑jp(zt∣j)bˉt(j).\bar b_t(x)=\sum_{x'} p(x\given x',u_{t-1})b_{t-1}(x'),\qquad b_t(x)=\frac{p(z_t\given x)\bar b_t(x)}{\sum_j p(z_t\given j)\bar b_t(j)}.

The first operation transports and spreads probability mass; the second multiplies by the likelihood and normalizes. If the denominator is zero, the observation is impossible under the model and no posterior is defined. The Kalman filter performs the same cycle with Gaussian distributions and linear Gaussian models: it stores a mean and covariance instead of all grid cells. A single Gaussian cannot represent two equally plausible doors without losing that multimodality.

For the model xt=Axt−1+But−1+wt\vb{x}_t=\mat{A}\vb{x}_{t-1}+\mat{B}\vb{u}_{t-1}+\vb{w}_t and zt=Hxt+vt\vb{z}_t=\mat{H}\vb{x}_t+\vb{v}_t, with independent Gaussian noises of covariance Q\mat{Q} and R\mat{R}, the predicted mean and covariance are μˉt=Aμt−1+But−1\bar{\vb{\mu}}_t=\mat{A}\vb{\mu}_{t-1}+\mat{B}\vb{u}_{t-1} and Pˉt=APt−1A⊤+Q\bar{\mat{P}}_t=\mat{A}\mat{P}_{t-1}\mat{A}\T+\mat{Q}. The innovation zt−Hμˉt\vb{z}_t-\mat{H}\bar{\vb{\mu}}_t compares observation and prediction. Its covariance is St=HPˉtH⊤+R\mat{S}_t=\mat{H}\bar{\mat{P}}_t\mat{H}\T+\mat{R}; if it is invertible, the gain is Kt=PˉtH⊤St−1\mat{K}_t=\bar{\mat{P}}_t\mat{H}\T\mat{S}_t\inv. The corrected mean adds Kt\mat{K}_t times the innovation, and the corrected covariance is (I−KtH)Pˉt(\mat{I}-\mat{K}_t\mat{H})\bar{\mat{P}}_t in exact arithmetic. A more uncertain sensor generally receives less weight, though that intuition depends on the covariances and observation geometry.

The grid discretizes space and can preserve multiple peaks; its cost increases with additional dimensions. The compact Kalman filter is exact under the assumptions above, but nonlinear dynamics, a multimodal distribution or ambiguous data association call for other approximations. Both still require validation of the sensor model and synchronization.

Lab: circular corridor

Use ten positions, three doors and stochastic motion of zero or four cells. A circular corridor avoids special boundary conditions. The sensor reports a door with probability 0.80.8 at a door and 0.10.1 at another cell. Start with a uniform belief, observe a door, move and observe another door. The bars come from a run of the model defined in the code, not real data.

[ ]Grid prediction and updateBrowser
import numpy as np
import matplotlib.pyplot as plt

doors = np.array([1, 0, 0, 1, 0, 0, 0, 1, 0, 0], dtype=bool)
belief = np.ones(10) / 10
kernel = np.array([0.05, 0, 0, 0, 0.95])  # desplazamientos 0 y 4
likelihood = np.where(doors, 0.8, 0.1)

def step(belief, kernel, likelihood):
    predicted = sum(p * np.roll(belief, shift) for shift, p in enumerate(kernel))
    weighted = predicted * likelihood
    if weighted.sum() <= 0:
        raise ValueError('Observación imposible')
    return weighted / weighted.sum()

first = belief * likelihood
first /= first.sum()
second = step(first, kernel, likelihood)
print('Posterior primera puerta:', round(first[0], 6))
print('Suma posterior:', round(second.sum(), 6))
print('Posterior celda 7:', round(second[7], 6))
fig, ax = plt.subplots()
ax.bar(np.arange(10), first, alpha=0.5, label='primera observación')
ax.plot(np.arange(10), second, 'o-', label='tras mover y observar')
ax.set(xlabel='celda (índice desde 0)', ylabel='probabilidad')
ax.legend()
plt.show()

The first observation favours three locations at once: seeing a door does not identify which one. The second result combines the movement history with another measurement and concentrates most mass in cell 7, consistent with moving from the door at cell 3. Uncertainty does not disappear entirely because motion and sensing are fallible. Accuracy depends on the map, motion model and sensor, not normalization alone.

To check the direction of movement, imagine all mass at cell 3 and motion of exactly four cells: np.roll(belief, 4) moves the mass to cell 7. This avoids a common error of reversing the kernel and predicting backwards. Here the action is a motion command, while the kernel expresses uncertainty in its execution. The conditional sensor probability must express the probability of the observation given each state, not the probability of the state given the observation.

Structure before vectorization

The taxonomy of modalities by structure helps select the transformations an architecture should respect. An image is a spatial grid; audio and text are ordered sequences; a point cloud is a set without intrinsic ordering; proprioception is a time signal of positions, velocities or forces; an action also has units, limits and an application time.

InteractivePermutation and displacement
00.511.522.533.5102133425060intensity
Structure
Input
Global mean1.00
Value at position 33.00
Compare the global aggregate and the value at one position when transforming a discrete input. The data are the explicit vector [0, 1, 3, 2, 0, 0].

A function is invariant if its output does not change under a transformation; it is equivariant if its output transforms correspondingly. In a point cloud, permuting the list does not change the object, so a global prediction should be invariant and a label for each point should follow the permutation. A convolution without boundary effects is equivariant to integer translations, though not necessarily invariant. Shifting audio changes when a sound occurs: global classification may ignore the shift, but temporal detection must preserve it. The figure uses an invariant mean and an order-sensitive reading of the third position; it does not simulate a neural network. In this particular example, image and audio shifts use zeros and preserve the sum.

Invariance does not mean discarding all position information. In a grasping task, the cup’s position relative to the gripper matters; a global representation that removes geometry could erase exactly the information needed. Similarly, permuting two words can change an instruction. The inductive bias should reflect which changes leave the task’s answer unchanged, not just the sensor’s physical form.

Alignment and fusion

A coordinated multimodal representation encodes modalities separately into comparable spaces; a joint representation combines information from multiple modalities into a representation that depends on both. CLIP aligns image and text encodings to compare pairs by similarity. Its contrastive objective connects to InfoNCE: distinguish the matching pair from alternatives in a batch. An aligned space does not imply that a single encoding already contains details from both inputs.

LLaVA connects a visual encoder to a language model; Flamingo integrates visual information into a language model using cross-attention layers. Both produce jointly conditioned representations when generating text. In cross-attention, queries from one modality weight keys and values from another. Early fusion combines signals or features before the decision; late fusion combines predictions or representations processed by separate branches. Those labels describe where information is combined, whereas joint and coordinated describe the relationship between representations. A Kalman filter fusing IMU and GNSS estimates a common state, but is not itself an example of a learned multimodal representation such as CLIP or a VLM.

In a batch of BB image-text pairs, let sijs_{ij} be the similarity between image ii and text jj, divided by a positive temperature. An image-to-text contrastive loss is

LI→T=−1B∑i=1Blog⁡exp⁡(sii)∑j=1Bexp⁡(sij).\Loss_{I\to T}=-\frac{1}{B}\sum_{i=1}^{B}\log\frac{\exp(s_{ii})}{\sum_{j=1}^{B}\exp(s_{ij})}.

Each row competes for its diagonal partner and the other batch entries serve as alternatives. The reverse direction exchanges rows and columns; averaging both trains both retrieval directions. An alternative can be semantically valid even if it is not the annotated pair: the objective observes correspondence in the data, not perfect semantic truth. Lowering temperature sharpens the probability distribution over alternatives, but does not add information missing from the data.

For cross-attention, if text produces nn queries of dimension dd and the image provides mm keys and values, the product QK⊤\mat{Q}\mat{K}\T has shape n×mn\times m. Row-wise softmax gives each query a distribution over visual positions, and multiplication by V\mat{V} gives nn outputs conditioned on the image. The order and shapes of the products reveal which modality asks and which supplies information. Do not directly treat these weights as a causal explanation of the model’s answer.

Same local error, different trajectories

Open-loop and closed-loop evaluation distinguish two distributions. Open-loop evaluation compares actions on fixed states from a validation set. Closed-loop evaluation applies actions and measures the resulting trajectory. The second distribution depends on the policy.

InteractiveSame squared error, different outcome
  • Constant bias
  • Random signs
  • Lane boundaries
  • Constant bias
  • Random signs
  • Outer boundary
  • Inner boundary
0.04
40
MSE of both0.0016
Final biased deviation1.60
Final random deviation0.08
Compare a constant bias with equally likely random signs. The circular trajectory has radius 3+xt3+x_t and the model is xt+1=xt+etx_{t+1}=x_t+e_t; it stops when a boundary is crossed.

In this simplified vehicle model both sequences have et2=ε2e_t^2=\eps^2 at every step. With bias, xT=Tεx_T=T\eps; with independent equally likely signs, E[xT]=0\E[x_T]=0 and Var⁡(xT)=Tε2\Var(x_T)=T\eps^2. For ε=0.04\eps=0.04 and T=40T=40, the bias reaches 1.61.6 and crosses the boundary at 11. Each sample of signs can follow a different path and may also leave the lane. The drawn circuit is one lap with angle 2πt/T2\pi t/T and radius 3+xt3+x_t: it visualizes the same deviation rather than simulating tyres or steering. The trajectory stops at the first crossing, while the lower graph continues the equation without stopping. In real systems, disturbances, dynamics and recovery determine the result.

The difference between tests can also be expressed through distributions. Supervised error averages over demonstration states; during deployment, the policy induces another state distribution through its own actions. If a small deviation leads to an image outside the demonstrations, loss measured on those demonstrations does not say how the policy will act there. Comparing policies requires a seed, initial conditions, number of episodes, success criterion and treatment of interruptions. Keep the set used to select hyperparameters separate from final evaluation episodes.

Lab: fit and deploy a controller

The scalar system xt+1=1.05xt+utx_{t+1}=1.05x_t+u_t has quadratic cost ∑t(xt2+ut2)\sum_t(x_t^2+u_t^2). Riccati iteration obtains the infinite-horizon LQR gain for this choice. We generate demonstrations with a small deliberate action bias, fit a linear policy with an intercept by least squares and measure error against the unbiased expert on independent validation states. We then deploy both with the same disturbance. The comparison describes this particular experiment, not a theorem about every policy.

[ ]Supervised fitting and deploymentBrowser
import numpy as np

a, q, r = 1.05, 1.0, 1.0
p = 1.0
for _ in range(100):
    p = q + a*a*p - (a*p)**2 / (r+p)
k = a*p / (r+p)
rng = np.random.default_rng(7)
train_x = rng.uniform(-1, 1, 200)
train_u = -k * train_x + 0.01
X = np.column_stack([train_x, np.ones_like(train_x)])
coef = np.linalg.lstsq(X, train_u, rcond=None)[0]
val_x = rng.uniform(-1, 1, 100)
mse = np.mean((coef[0]*val_x + coef[1] + k*val_x)**2)

def rollout(slope, intercept, horizon=80):
    x = 0.5
    result = [x]
    for t in range(horizon):
        disturbance = 0.005*np.sin(0.2*t)
        x = a*x + slope*x + intercept + disturbance
        result.append(x)
    return np.array(result)

expert = rollout(-k, 0)
learner = rollout(*coef)
print('Ganancia LQR:', round(k, 6))
print('ECM de acción en validación:', round(mse, 6))
print('Diferencia final de estado:', round(learner[-1]-expert[-1], 6))
fig, ax = plt.subplots()
ax.plot(expert, label='experto')
ax.plot(learner, label='política ajustada')
ax.set(xlabel='paso', ylabel='estado')
ax.legend()
plt.show()

The bias causes a persistent difference even when action error appears small. Here the closed-loop system is stable and the difference approaches a limit; it does not grow without bound. An unstable closed-loop system or an integrator can behave very differently. A useful protocol reports supervised error alongside task success, collisions, initial conditions and disturbances, with separate training and evaluation episodes.

To interpret the lab, subtract the equations of the expert and learner under the same disturbance. Since their slopes coincide up to numerical error, the difference approximately satisfies dt+1=(1.05−k)dt+0.01d_{t+1}=(1.05-k)d_t+0.01, with d0=0d_0=0. The geometric sum gives dT=0.01(1−(1.05−k)T)/(1−(1.05−k))d_T=0.01(1-(1.05-k)^T)/(1-(1.05-k)) when the denominator is nonzero. A single step has discrepancy 0.010.01; feedback accumulates it until equilibrium. If ∣1.05−k∣<1|1.05-k|<1, that equilibrium exists and is attractive. The comparison uses the same disturbances, reducing variation between the trajectories, while repetition under other conditions remains necessary.

Module roadmap

Lessons 2 and 3 build rotations and rigid motions; lesson 4 derives kinematics and lesson 5 covers dynamics and control. Lesson 6 implements simulation and lesson 7 planning. Lessons 8 through 13 study imitation, DAgger, inverse learning, action chunks, diffusion and evaluation. Lessons 14 through 22 cover cameras, point clouds, sensor fusion and reconstruction; 23 through 26 connect image and language; 27 through 31 cover audio and video; 32 and 33 unite language and action. The imitation-robot project takes demonstrations, trains policies and compares them through deployment. This map separates responsibilities: perception, estimation and decision are distinct even when a learned model combines blocks.

Exercises

Quiz
Which combination best respects the structure of camera, LiDAR point cloud and IMU data?
Quiz
Which classification is most accurate for CLIP, LLaVA, Flamingo and an IMU-GNSS Kalman filter?
Numeric
With ten initially uniform cells, three doors, and probabilities of observing a door of 0.8 at a door and 0.1 elsewhere, what is the posterior probability of a particular door cell?
Code
Implement bayes_filter_step(belief, motion_kernel, likelihood). The kernel index gives the non-negative circular displacement. Return the normalized posterior; raise ValueError if its mass is zero.
def bayes_filter_step(belief, motion_kernel, likelihood):
  pass
Shift+Enter to run
Numeric
For next x = 1.05 x + u and u = -0.5 x + 0.01, calculate the steady state.
Key idea
A robot is a closed-loop dynamical system: sensor structure, uncertainty, timing and actions jointly determine what happens next.