Module contents
Stage 4 of 9Advanced 100 min

Vision-based policies

Move from privileged simulation state to camera images using a pretrained ResNet encoder with spatial softmax, multi-camera fusion with proprioception, and random-crop augmentation. Compare against the state policy and measure inference latency and memory on the RTX 4060.

After this lesson you can

  • Implement a ResNet encoder with spatial softmax and multi-camera fusion.
  • Apply image augmentation compatible with the task geometry.
  • Compare image and state policies on success and data efficiency.
  • Measure inference latency and ensure the control frequency.

Before you start

When state no longer comes labeled

The previous behavior-cloning policy received the exact T vertices. On a physical robot there is no simulator variable providing that geometry: a camera provides pixels affected by occlusion, lighting, and calibration. The problem is no longer simply choosing an action from a known state. First we must learn a visual representation that retains what is needed for control.

Proprioception, such as the pusher’s position, remains useful. The image can show the object and goal, while a proprioceptive sensor tells us where the actuator is even when hidden. This combination does not eliminate partial observability: an instantaneous image can be consistent with several velocities or contact histories. In this lesson we keep the same action and evaluation contract so the comparison with privileged state is interpretable.

InteractiveOne coordinate per map
  • Activation map
  • Expected coordinate
0.7
0.6
Expected x coordinate−0.191
Expected y coordinate0.000
The curves are an artificial activation map with two peaks. The magenta point is the expected coordinate of a softmax distribution over a grid. Change temperature and relative intensity: with two similar peaks, the point can fall between them where there is no maximum.

From activations to positions

If one activation dominates and temperature is low, its coordinate attracts the expectation. If two peaks have similar weight, the average can fall between them: the point need not coincide with a visible feature or follow the same object in every frame. With a constant map the mean is at the center of a symmetric grid, but does not indicate the model has found anything. The gradient does propagate to all positions, unlike a discrete argmax. Levine et al. use a differentiable spatial representation in visuomotor policies; the artificial map above illustrates the calculation, not a measured robot activation.

The precise derivative clarifies that gradient. For a horizontal coordinate xˉc=∑i,jpcijxj\bar x_c=\sum_{i,j}p_{cij}x_j, differentiating softmax gives

∂xˉc∂Fcuv=pcuvτ(xv−xˉc).\frac{\partial\bar x_c}{\partial F_{cuv}}=\frac{p_{cuv}}{\tau}(x_v-\bar x_c).

Increasing an activation to the right of the mean moves it right, and one to the left moves it left. Adding a constant to the whole map does not change pp, because that factor cancels between numerator and denominator. A very low temperature can concentrate the distribution, but also leave nearly zero gradients at positions of very low probability; no value is optimal for every scene.

The lab uses a ResNet18 initialized with torchvision’s public ImageNet weights. It replaces each BatchNorm with GroupNorm of 32 groups and copies its affine parameters, but not its moving means and variances: the result is no longer exactly the original pretrained network. We fine-tune the whole network on task data. GroupNorm does not compute statistics across batch examples, avoiding changes to other examples’ statistics in small batches, though this alone does not ensure transfer works. Wu and He (2018) define group normalization. We record the decision with the checkpoint; comparing against frozen BatchNorm would be an additional ablation.

Each camera passes through the same encoder. Its coordinates are concatenated with normalized pusher position and an MLP head predicts two normalized action coordinates. The first camera looks from above; the second looks obliquely. Both are rendered before acting from the same state. Sharing weights reduces parameters, but does not make different cameras identical: their frames and occlusions must be known. Fusion is a form of sensor integration, not explicit geometric calibration.

Transfer from ImageNet has two parts. Convolution weights provide filters learned from natural images, while the original classification head is discarded. The policy receives no ImageNet labels: it updates those filters using the task’s imitation loss. A camera, color, or lighting change may shift the input distribution and pretraining is not guaranteed to resolve that difference. Compare with random initialization and a frozen encoder to attribute an improvement to pretraining; neither ablation is the crop ablation in this lab.

Synchronization is also part of the contract. Here both views represent exactly the same simulated state. On physical hardware, acquisition or latency differences between cameras can show different object positions, especially during fast contact. Aligning timestamps and measuring delay avoids presenting movement as geometry. If one camera loses the object, the other can help only if it sees it and the model has encountered examples of that occlusion; concatenating two vectors does not guarantee useful redundancy.

The operation has a deliberate limitation. Two numbers per channel summarize its distribution and discard its shape: two maps with different peaks may have the same expectation. A later network cannot recover spread or decide whether there were two objects from that mean alone. Retaining full maps through pooling or attention offers more information at the cost of a larger representation. In either case, inspecting a learned coordinate does not prove the channel discovered a stable semantic concept.

For a convolution it is tempting to turn each channel’s maximum into a position. However, the maximum’s index changes discontinuously when two values swap order and its gradient does not indicate how to modify the remaining pixels. The softmax expectation distributes contributions by probabilities and enables end-to-end training with action loss. Loss still supervises actions, not coordinates: learning may use a channel as a background reference, encode lighting, or focus on an edge, as long as it helps reduce error on the observed dataset.

A quick gradient test needs no robot: create a uniform map, calculate the coordinate, and check that it is centered; then increase a cell on the right and observe that the horizontal coordinate moves toward it. Adding the same constant to all activations should preserve the output. The code exercise checks these properties alongside a corner peak. For images with a single row or column, the coordinate convention must be specified separately, since the geometric center and endpoint of a degenerate grid may not coincide with an implementation based on linspace.

Representation cost can be counted before running it. For 512 channels, each camera contributes 1024 coordinates; two cameras and two proprioceptive coordinates form 2050 inputs to the head’s first layer. That figure excludes shared ResNet parameters and training activation buffers. Sharing the encoder avoids duplicating weights, but the two images still require separate convolutional passes and occupy memory. Measuring actual loop time helps determine whether this architecture fits within the control period.

InteractiveCoordinates on a real episode

Loading visual episode…

Evaluation episode 20000 of the first trained visual policy, without cropping and with training seed 0. One frame every ten steps and the spatial expectations of three channels are shown; these were selected for their variation in the overhead camera during this episode, not for semantic meaning. Change camera and step through the episode.

The marks come from the trained encoder and are overlaid on the pixels received by the policy. Because we selected the most variable channels to make them visible, this view is not an unbiased sample of all 512 channels. The same selection is shown in both cameras: a point following an edge or region does not prove the channel learned an object. The displayed episode did not reach the success threshold; it does not by itself represent the rate for the entire evaluation.

Change pixels without changing the task

The code shifts images slightly using a crop with edge padding and changes brightness. The same shift and brightness factor are applied to both cameras of an example. This avoids changing one camera randomly in a different way from the other, although the same pixel shift is not necessarily a physically coherent transformation across cameras with different perspectives. Augmentation is used only for training, not evaluation. A goal near the boundary may leave the frame; if necessary information is lost, the original action is no longer a valid label for what the model sees.

The following experiment controls a specific question: what happens when crop shifts are added while both variants already have the same brightness variation? It does not separately measure the effect of brightness. To test visual robustness to new conditions, define a test set by condition beforehand: for example, training background and light versus altered lighting, without transforming labels or selecting hyperparameters on that set. Report success by condition and its interval, as well as aggregate success. Augmentation can lower supervised loss while worsening control if it shifts attention to irrelevant scene regions.

A horizontal flip is not automatically safe either. If the image is reflected while the action remains in the table’s original frame, a leftward command may be paired with the scene for a rightward command. To use a reflection, coherently transform image, calibration, proprioception, and action, and verify that the physics and task possess that symmetry. Color variation can also erase object identity if color determines the task. Geometric and photometric augmentation is a hypothesis about invariances, not a universal recipe.

Episode comparisons require care with the denominator. If one episode has many more frames than another, a per-frame average weights the first more heavily, even though both count as one demonstration. The subsets of 10, 40, and 80 are nested prefixes of the same demonstrations; their size counts episodes, but training consumes all their frames. The validation split is outside all three prefixes and final seeds are outside selection. This facilitates comparing curves without making their points independent samples.

Lab: reconstruct cameras and evaluate

Download p13_vision.py, p13_bc_subsets.py, p13_pusht.py, and p13_bc.py into the kernel directory. You need the complete dataset from the first lesson, PyTorch, torchvision, and MuJoCo with rendering. The first run downloads ResNet18_Weights.IMAGENET1K_V1 from the URL declared by torchvision. The resulting policy weights and statistics are saved locally.

The preceding lesson’s dataset saves one camera. To obtain the second without inventing images, the lab restores each episode’s initial state, applies its recorded actions, and renders both cameras before each action. Before saving a frame it checks that computed vertices exactly match recorded ones. Adding a camera to the MJCF does not modify forces or dynamic state. Reproduction can diverge under a different MuJoCo version because of numerical differences: the code stops so you can investigate rather than hiding that difference.

Evaluation again uses the same two cameras, resolution, orientation, and pixel conversion as training without augmentation. This correspondence matters: vertically flipping only the evaluation camera or changing its framing without recording the change can produce an interface failure that does not measure visual generalization. Reconstruction code checks state agreement before every render and uses the same camera function for rollout. In an independent review of four episodes and three instants per episode, repeating the render after restarting the computer produced matching states but some RGB components varied: mean absolute difference was between 0.0032 and 0.0086 levels out of 255 in the overhead view, and between 0.0119 and 0.0137 in the oblique view. The largest observed difference in the oblique view was 18 levels. The cause is unidentified and this sample cannot rule out an effect on control. Thus the same function and geometry do not imply identical pixels. This does not automatically validate a different real camera either; that transfer requires calibration and its own test set.

We train two variants, with and without cropping, using the same seeds and episode splits. Both receive the same kind of brightness variation, so the ablation changes cropping without simultaneously confounding the two transformations. Each uses 20 epochs, AdamW, and mixed precision when CUDA is available; the effective batch of 64 is split into microbatches of up to 16, whose losses are weighted by their example counts and accumulated before each update. GroupNorm uses no cross-example statistics, but addition and random-number order can change numerical results relative to a single batch; the checkpoint is selected by validation loss and then evaluated on the 100 reserved seeds 20000 through 20099. Identify the machine on which measurements are obtained: the machine here is an RTX 3060, so its latencies are not measurements of the RTX 4060 mentioned in the design. Selection by loss has the limitation seen in the previous lesson. Latency is measured after warmup and with CUDA synchronization: it includes inference, not rendering or communication with a robot. The recorded memory peak belongs to the PyTorch process during that inference benchmark, including the already loaded model; it is neither the training peak nor all GPU memory. Times depend on the machine and other workloads.

[ ]Train perception and controlLocal GPU
import os, sys
from pathlib import Path
for variable, fallback in [('P13_BC_CODE_DIR', 'public/data/p13/l02'),
                           ('P13_VISION_CODE_DIR', 'public/data/p13/l04')]:
    directory = Path(os.environ.get(variable, fallback))
    if directory.exists():
        sys.path.insert(0, str(directory.resolve()))
from p13_vision 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.'
salida = Path(os.environ.get('P13_VISION_OUTPUT_DIR', base / 'p13-l04' / 'entrenamientos'))
resultados = experimento(dataset, base / 'p13-l04' / 'camaras', salida,
                         seeds=(0, 1, 2), epochs=20)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Compare augmentation, success, and latencyLocal GPU
import numpy as np
for r in resultados:
    e = r['rollouts']
    print('semilla', r['seed'], 'recorte', r['augment'], 'MSE validación', round(r['validation_mse'], 5),
          'éxito', e['successes'], '/', e['n'], 'Wilson', np.round(e['wilson'], 3),
          'latencia', r['latency'])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Control analysis must also observe what is lost. If the predicted action seems correct in a static image but the object ends up outside the camera, subsequent frames no longer contain the information supporting that prediction. A useful failure analysis aligns image, applied action, target coverage, and time step; this distinguishes mistaken perception from an action that fails because of dynamics or contact. The spatial expectation can be tracked over each camera, but a point moving alongside the object does not by itself prove the channel represents it causally: a controlled occlusion or an intervention on activations could test that hypothesis.

To study data efficiency, compare nested subsets of 10, 40, and 80 episodes with n_train=10, 40, and 80, saving outputs in separate directories. Validation remains the held-out split, and statistics are recomputed only on the chosen subset. Train the state policy with the same subsets and seeds for 20 epochs: this compares loss-based selection of both methods under a common epoch budget, even though their per-epoch costs differ. The visual set of 80 was already trained in the first cell. This sweep is far more expensive than a quick test.

In the complete visual campaign, each number below counts successes in 100 final episodes of one policy; lists follow training seed order 0, 1, and 2:

DemonstrationsWithout cropWith crop
100, 0, 00, 0, 0
401, 1, 00, 0, 0
800, 0, 00, 0, 0

For 0/100, the 95% Wilson interval is [0, 0.037]; for 1/100 it is [0.0018, 0.0545]. The two policies with 1/100 solved different seeds (20004 and 20071). Their intervals overlap widely and this sample does not demonstrate an advantage for control without cropping; nor does success improve monotonically as demonstrations are added. The same 100 conditions are reused across policies to allow paired comparisons, so successes should not be added as if they were 1800 independent episodes from one policy.

The 18 median inference latencies ranged from 4.94 to 33.22 ms, and their 95th percentiles from 7.07 to 46.95 ms. All these isolated measurements were below the task period of 100 ms on this machine, but they were taken under varying concurrent workloads and exclude capture, rendering, and communication. The peak allocated by PyTorch during the inference benchmark ranged from about 218 to 410 MB; it includes the loaded model and is not the training peak. To claim that a specific system meets its frequency, measure the complete chain under its own workload distribution.

In our own state-baseline run, all three seeds of each prefix achieved 0/100 on test, with a 95% Wilson interval [0, 0.037] for each policy. Models for 10 and 40 were trained on CPU; the models for 80 reuse epoch 20 of the previous lesson’s campaign, with the same dataset, architecture, seeds, and optimizer. These figures do not show an increasing success curve or establish by themselves what happens with images. Test seeds are shared across policies and allow paired episode analysis; they should not be treated as 900 independent cases from one policy.

[ ]Data curves with state and visionLocal GPU
from p13_bc_subsets import experimento as entrenar_estado
barrido = Path(os.environ.get('P13_VISION_SWEEP_DIR', base / 'p13-l04' / 'barrido'))
comparacion = {}
for n in (10, 40, 80):
    vis = resultados if n == 80 else experimento(dataset, base / 'p13-l04' / 'camaras',
                                                  barrido / f'vision-{n}', seeds=(0, 1, 2),
                                                  epochs=20, n_train=n)
    estado = entrenar_estado(dataset, barrido / f'estado-{n}', n_epochs=20,
                             seeds=(0, 1, 2), n_train=n)
    comparacion[n] = {'vision': vis, 'estado': estado}
    print('demostraciones', n, 'estado', [r['val']['successes'] for r in estado],
          'visión sin recorte', [r['rollouts']['successes'] for r in vis if not r['augment']],
          'visión con recorte', [r['rollouts']['successes'] for r in vis if r['augment']])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To interpret a small rate, the interval and failures convey more than a rounded number. The two 40-demonstration policies that solved one episode are distinct and their successes occur on different seeds; comparison with state shares initial conditions but does not establish which modality caused the difference. In the traces, some policies that do not reach the threshold still approach the goal: for example, the best coverage observed among the 100 seeds of the 80-demonstration visual policy with seed 0 and no crop was 0.914, below 0.95. Review the trajectory before concluding that all failures were alike.

Reading a success rate also depends on when the episode stops. Here the evaluator limits each rollout to 300 steps and records success if the coverage threshold was reached before termination. Failure includes both a trajectory that never approaches and one that approaches without reaching the threshold; inspecting coverage over time distinguishes them. The Wilson interval summarizes proportion uncertainty under its statistical model; it does not automatically cover lighting changes, other cameras, or systematic simulator errors.

The per-episode metric is a function of the environment and chosen criterion, not an isolated property of the network. The pushing task uses geometric target coverage and the same horizon for every variant. Changing threshold or horizon changes the question: a controller that approaches slowly might count as failure at 300 steps and success with a longer horizon. To decide whether an improvement is consistent, inspect paired successes on the same seeds, trajectories changed by each variant, and training variation. Three training seeds do not describe all initialization or data-selection uncertainty.

In physical deployment, reducing latency can compete with input size and accuracy. Before lowering resolution or converting weights to lower precision, measure how success changes on the same test split and verify capture and conversion do not overshadow network time. A fast median does not resolve a slow tail: if the high percentile of the complete chain exceeds 100 ms, the controller needs a strategy for late observations or a faster implementation. Isolated inference latency is one part of the budget, not a frequency guarantee.

Exercises

NumericInference budget
At 10 Hz each step has 100 ms. If simulation and rendering take 20 ms and you reserve no additional margin, how many milliseconds remain for inference and the rest of the loop?
QuizReflect an image
Why can a horizontal image flip be an incorrect augmentation for the policy?
QuizThe object leaves the camera
A policy works with the object centered but fails at the edge. What is the most cautious conclusion?
CodeSpatial softmax
Implement spatial_softmax(features) for a PyTorch tensor (B,C,H,W). Return (B,C,2), expected coordinates (x,y) on a grid from −1 to 1. Use softmax per channel over H×W and torch.meshgrid with indexing='ij'.
import torch
def spatial_softmax(features):
  pass
Shift+Enter to run
Key idea

A visual policy learns what information to extract from cameras, but images can hide relevant state. Spatial softmax returns differentiable expectations, not guaranteed objects; fusion and augmentation must respect frames and geometry. Evaluate in closed loop with deployment cameras and latency against the privileged-state baseline.