Action multimodality
When several actions are correct in the same state, such as going around an object on the left or right, squared-error regression averages them into an action that does neither. Reproduce the failure in a toy example and in T pushing, and compare Gaussian mixture and discretized action heads.
After this lesson you can
- Build a multimodal toy example and show the failure of squared-error regression.
- Implement a Gaussian mixture head and a discretized action head.
- Measure multimodality in T-pushing demonstrations.
- Compare success rate and behavioral diversity for each head.
Before you start
Two good decisions and a bad average
A pusher can go around an obstacle on the left or on the right. If both paths are correct and the observation does not indicate which one was chosen, a deterministic policy trained with squared error may predict an intermediate action. In this example that action goes through the obstacle. The demonstrations need not be noisy or the optimizer have failed: the average is the correct solution for the chosen loss.
With , the mean is . A straight path through crosses the rectangle. The interactive treats contact with the boundary as a collision; for this geometry that occurs exactly when . This is an explicit geometric system, not a Push-T measurement. The example isolates the phenomenon; we will then look for it in real demonstrations and measure whether a mixture policy improves control.
Why squared error returns the expectation
Let be an action with a finite second moment and the observation. For any measurable predictor with a finite second moment, write . On expanding the square and conditioning on , the cross term vanishes because :
Therefore minimizes squared risk and is unique except on sets of probability zero. This follows from projection by conditional expectation. It does not say the average is a safe action or that every MLP reaches the population optimum. If both paths are truly indistinguishable in the observation, more epochs do not remove the ambiguity. If an observable variable does indicate intention, incorporating it can make the conditional distribution unimodal.
import numpy as np
p = 0.6
acciones = np.array([-1., 1.])
pesos = np.array([p, 1-p])
media = float(pesos @ acciones)
riesgo = lambda a: float(pesos @ (acciones-a)**2)
print('media', media, 'riesgo de la media', riesgo(media), 'riesgos de los modos', riesgo(-1), riesgo(1))
print('la trayectoria media toca el obstáculo:', abs(media) <= 0.5)A distribution instead of a single arrow
To calculate likelihood without overflow we use log_softmax and logsumexp. In a diagonal Gaussian, dimension contributions are summed within each component before summing components. Bounding log_sigma prevents scales from numerically approaching zero or infinity, though it changes the fitted family. Components can collapse into one, share a single mode, or swap indices: inspect weights, means, and samples rather than automatically interpreting the number of components as the number of strategies.
Two distinct failures lie behind the word collapse. If a component receives an almost-zero weight, it obtains almost no gradient from the examples and may stop specializing. At the other extreme, a component can try to place its mean on an example and make its scale very small: the continuous density at that point can grow without bound. Scale clipping bounds that behavior in this implementation, but does not force the five components to represent five useful modes. Log-likelihood can be positive as a density and its negative can be less than zero; that is not a probability greater than one, since a density has units inverse to those of the action.
Before the robot, fit a small mixture to data explicitly generated from two Gaussians with standard deviation 0.08. To isolate fitting of weights and means, we fix the known standard deviation; we do not claim it would be known in a real task. Initialization places one mean on each side and the EM algorithm alternates responsibilities and weighted averages. Discretization counts samples on each side of zero. Both recover alternatives in this constructed example; that does not guarantee a neural head will find every mode in high-dimensional observations.
import numpy as np
rng = np.random.default_rng(19)
modo = rng.choice(2, size=1000, p=[0.6, 0.4])
acciones = np.where(modo == 0, -1., 1.) + rng.normal(0, 0.08, size=1000)
mu = np.array([-0.8, 0.8])
pesos = np.array([0.5, 0.5])
sigma = 0.08
for _ in range(12):
log_r = np.log(pesos)[None, :] - 0.5*((acciones[:, None]-mu)/sigma)**2
log_r -= log_r.max(axis=1, keepdims=True)
r = np.exp(log_r)
r /= r.sum(axis=1, keepdims=True)
pesos = r.mean(axis=0)
mu = (r*acciones[:, None]).sum(axis=0)/r.sum(axis=0)
print('media MSE', round(float(acciones.mean()), 3))
print('mezcla: medias', np.round(mu, 3), 'pesos', np.round(pesos, 3))
print('categorías izquierda/derecha', np.bincount((acciones >= 0).astype(int), minlength=2))With that seed, the 1000 samples have mean ; the mixture fits means and , with weights and . The categories count 583 and 417 observations. The realized proportion need not exactly match the generation probability 0.6: this is a finite sample. The empirical mean also falls within the collision region of the preceding geometric model.
A sample and a mixture mean answer different questions. The global expectation averages components again and can fall between modes. Selecting a component mean avoids that global average, but can take a poor action if weights or means are badly estimated. Taking the highest-weight component does not represent less frequent alternatives; sampling it can represent the distribution at the cost of variation across episodes. In either case the seed should be controlled and physical consequences measured.
Sampling an independent component at every step can alternate between incompatible strategies. The lab chooses a component at the beginning of each episode according to its weights and keeps its index, using that component’s mean on subsequent steps. This is a simple persistence mechanism, not a guarantee of coherence: component identities are not required to retain the same meaning in different states. Policies predicting action chunks or entire sequences address the problem with more context.
This lab’s discretized head predicts an independent distribution per dimension, with 21 intervals per coordinate. That can create combinations never demonstrated. If only and are observed, each marginal has both signs, but their product also assigns mass to and . A joint distribution, an autoregressive factorization, or vector-action tokens can represent that dependence at the cost of more categories or sequential decisions. Behavior Transformers combines action discretization and continuous correction; it is not equivalent to this independent head.
Discretization also introduces resolution error. With uniform intervals of width and an action within range, replacing it by the interval center produces absolute error up to in that coordinate. Making smaller reduces that error, but spreads data across more categories and may leave some with no examples. Boundaries matter too: in this lab they are computed during training and a validation action outside them falls into the extreme interval. This avoids evaluation leakage, but prevents extrapolation beyond the represented range. With absolute actions, also check the environment’s physical clipping after reconstructing units.
Are there alternatives in the pushing data?
The question must concern actions conditioned on similar observations, rather than a global histogram of all actions. For each state, the lab looks for a neighbor from another episode in the normalized 18-variable space and compares their normalized actions if input distance is at most 0.5. It reports how many states have a neighbor meeting the rule and the median action distance. Two nearby states are not identical, and the metric counts correlated coordinates: a difference may arise from geometry, hidden history, or sampling, and does not by itself prove two actions are equally good in exactly the same state.
The expert demonstrations from the first lesson are not human: the planner maintains an internal sequence of commands and may visit similar states with different plans. The experiment does not attribute human strategies to those trajectories. It compares the MSE policy, a five-component mixture, and the discretized head on the same 80 training episodes, the same 20 held-out trajectories for loss, and the same 100 rollout seeds. Three training seeds show part of the variability. Density loss, categorical cross-entropy, and MSE have different scales and units: their numerical values should not be compared across families.
Lab with three heads
Download p13_multimodal.py, p13_pusht.py, and p13_bc.py, and prepare the complete p13-l01 dataset. All heads have two hidden layers of 256 units, Adam, and 60 epochs. Observation and action means and standard deviations are computed from training only, and the action is denormalized before application. Discrete head interval endpoints also come only from training; a validation action outside that range is assigned to the extreme interval.
Choose each family’s checkpoint by its own validation loss, then measure success with intervals. Save coverage, trajectories, chosen component, and an indication of the initial horizontal direction. That direction is a partial measure of behavioral diversity, not a perfect identification of the complete strategy. If the mixture does not outperform MSE on this set, the negative result is valid and should be reported with intervals; the real task is not replaced by the toy example.
In one run with three training seeds and MuJoCo 4.0.1, all three families achieved 0/100 successes for each seed, each rate with Wilson interval . The first predicted horizontal displacement was negative in 51, 53, and 56 episodes for MSE, mixture, and discrete respectively, for the first seed; for the other two the counts were (51, 51, 52) and (52, 49, 48). Those counts indicate sign diversity but do not demonstrate that the trajectories represent two useful strategies. Of the 8595 training states, 4508 had a neighbor from another episode within normalized distance 0.5; the median distance between their normalized actions was 0.138. This is a proximity diagnostic, not proof that both movements are valid in an identical state. On this result the mixture does not exceed MSE in success.
import os, sys
from pathlib import Path
for variable, fallback in [('P13_BC_CODE_DIR', 'public/data/p13/l02'),
('P13_MULTI_CODE_DIR', 'public/data/p13/l05')]:
directory = Path(os.environ.get(variable, fallback))
if directory.exists():
sys.path.insert(0, str(directory.resolve()))
from p13_multimodal import experimento
base = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab'))
dataset = base / 'p13-l01' / 'completo' / 'empuje_t_programadas'
assert (dataset / 'meta' / 'info.json').exists(), 'Ejecuta primero p13-l01 en modo completo.'
resultados = experimento(dataset, base / 'p13-l05', seeds=(0, 1, 2), epochs=60)npm run lab and open the connection link.import numpy as np
for r in resultados:
z = r['rollouts']
left = sum(e['initial_delta_x'] < 0 for e in z['episodes'])
print(r['seed'], r['family'], 'éxito', z['successes'], '/', z['n'],
'Wilson', np.round(z['wilson'], 3), 'primer delta x negativo', left,
'diagnóstico de vecinos', r['diagnostic'])npm run lab and open the connection link.An additional check looks at the pusher’s requested displacement direction, , for those neighbors. Among the 4508 nearby pairs, 4432 have displacements of at least 5 mm in both examples; 974 of those pairs have a negative dot product, meaning directions separated by more than 90°. Because the states are close but not identical, this suggests local action diversity but does not identify causal modes or show that both actions are interchangeable.
from scipy.spatial import cKDTree
from p13_pusht import leer_lerobot
info, _, episodios, _ = leer_lerobot(dataset)
n = int(info['splits']['train'].split(':')[1])
train = episodios[:n]
x = np.concatenate([np.concatenate([e['observation.state'], e['observation.environment_state']], axis=1) for e in train])
a = np.concatenate([e['action'] for e in train])
ids = np.concatenate([np.full(len(e['action']), i) for i, e in enumerate(train)])
sd = x.std(axis=0)
z = (x-x.mean(axis=0))/np.where(sd < 1e-6, 1, sd)
dist, neighbors = cKDTree(z).query(z, k=40, workers=1)
pairs = []
for i in range(len(z)):
valid = np.flatnonzero((ids[neighbors[i]] != ids[i]) & (dist[i] <= 0.5))
if len(valid):
pairs.append((i, neighbors[i, valid[0]]))
if pairs:
pairs = np.asarray(pairs)
delta = a-x[:, :2]
u, v = delta[pairs[:, 0]], delta[pairs[:, 1]]
eligible = (np.linalg.norm(u, axis=1) >= 5) & (np.linalg.norm(v, axis=1) >= 5)
opposite = (u*v).sum(axis=1) < 0
enough, differing = int(eligible.sum()), int((eligible & opposite).sum())
else:
enough = differing = 0
print('pares', len(pairs), 'ambas magnitudes >= 5 mm', enough, 'producto negativo', differing)npm run lab and open the connection link.Exercises
Step 1 of 3. What happens to the cross term when taking the expectation conditional on O?
import torch
def mdn_nll(pi_logits, mu, log_sigma, a):
passMSE learns the conditional mean, which may be an invalid action when several strategies are correct. Mixtures and categories can represent alternatives, but dependencies and temporal coherence must be preserved. A representation’s validity is decided through demonstrations, coverage analysis, and rollouts, not merely by the shape of its loss.