DAgger and interactive correction
Implement DAgger using the scripted expert as an oracle: the policy acts, the expert labels visited states, and the data are aggregated. Compare with adding demonstrations at an equal label count and test interactive correction when a human intervenes on policy errors.
After this lesson you can
- Implement DAgger with policy mixtures and dataset aggregation.
- Compare DAgger with additional demonstrations at an equal number of expert labels.
- Implement interactive correction with on-demand human intervention.
- Measure demonstrator time against the improvement in success.
Before you start
Ask where the policy makes mistakes
Behavior cloning learns from states visited by the expert. When the policy follows a different trajectory, it encounters questions for which it may have no examples. Adding more expert demonstrations increases coverage of the expert’s trajectories, but does not guarantee coverage of states generated by the learner. DAgger changes who drives during collection: the learner visits states and a queryable expert says what it would do in them.
The drawing shows a possibility, not a law of learning. Adding labels can correct behavior in new states if the policy class can represent it and the expert offers a useful action there. It may also fail to improve success, for example if the state is already unrecoverable or the same observation hides necessary information. That is why the comparison takes place in the simulator with the same label budget.
The algorithm and what it actually promises
The difference between the executed action and the label is essential. If the learner’s action is executed and that same action is saved as the label, the model learns to reproduce its own mistake. If the expert’s action is executed and only the expert trajectory is saved, the learner’s deviations are not covered. Aggregating also differs from replacing: discarding earlier data can make a policy forget states it had already mastered.
The result of Ross, Gordon and Bagnell (2011) reduces sequential imitation to online learning. Its guarantee requires a suitable sequence of mixtures, a policy class, and a learning procedure with low regret on the induced losses, as well as assumptions linking imitation loss to cost. Under these assumptions there is a policy in the sequence whose loss on its own distribution is controlled by the best aggregate fit and regret; a bounded per-step error cost permits a term linear in the horizon instead of BC’s quadratic worst case. This does not imply that an MLP trained with Adam has zero regret or that the last iteration is always the best. The guarantees of online optimization depend on assumptions we do not take for granted here.
We can see the reduction without hiding the necessary terms. Let be the state distribution at step when running the mixture from round , and let the per-state loss be . Define
The cumulative regret is . By definition, the average loss of the produced models is , so at least one has loss no greater than that average on the mixture distributions. This statement does not yet address autonomous deployment.
To connect the two distributions, couple a rollout of and one of using the same initial state and random transitions until the mixture chooses the expert. By the union bound, the probability that the expert has intervened at least once by step is at most . Since loss lies in , the difference between expected losses at that step is at most . Averaging over bounds the difference by . If is the same average evaluated under , there is a round whose autonomous loss satisfies
The bound is useful if the class can fit the aggregated data, average regret is small, and the contribution from the mixtures decreases. Selecting that round requires independent evaluation; the existence argument does not automatically identify the last one. It also concerns a bounded imitation loss. Converting it to task cost requires an additional assumption about how much future cost can worsen after a disagreement. Unbounded continuous MSE and a neural network trained without guarantees do not automatically meet these premises.
In the lab is the planner from the first lesson. It sees the true pose and simulates candidates before recommending an action. To query a learner state, we clear the previous plan and ask for a fresh decision from the current state. This avoids labeling with a pending command from a previous trajectory. This query is expensive: we time it, but its cost does not represent a human operator’s time.
Compare by labels, not by hope
We start from the same ten demonstration episodes and freeze their normalization statistics for both branches. BC then receives expert actions sampled without replacement from the remaining training episodes; DAgger receives the same number of labels for states visited by its mixture. The count includes every initial pair and every additional query, even when the policy executes its own action. The state distribution changes while the number of labels stays fixed.
In three rounds we add 200 labels each, with , , and . The same MLP architecture is reinitialized and trained with the same recipe in both arms. Evaluation uses the 100 held-out test seeds from the previous lesson, paired across methods. The set describes the curve and is not used to choose hyperparameters; if you adapt the experiment based on it, you need another final set. A Wilson interval applies to one fixed policy and does not replace a paired comparison or an analysis of variation across training runs.
Equal numbers of labels do not mean equal total effort: a recorded episode required a complete trajectory, while each planner query may require many simulations. We also report oracle time and collection episodes. With a person, supervision time, intervention time, fatigue, and the ability to correct from unfamiliar states also matter. The clock time of a scripted expert measures none of these quantities.
The human takes control
HG-DAgger proposes human takeover as a more suitable alternative for interaction: asking for labels while another policy is in control can introduce perceived delay and be unsafe or difficult. In a real interface the operator should see the same camera as the policy, know who is in control, and have an unambiguous way to intervene and release control. A risk signal can help draw attention, but a learned threshold does not make a dangerous state recoverable.
In our specific example the person sees the overhead camera and the l02 policy receives exact vertices from the simulator rather than an image. This is an information asymmetry: the test instruments intervention, but does not provide a clean comparison of human and policy perceptual capabilities. When the policy is visual, show the operator the same views and document any other information they receive.
Published human evidence illustrates the cost of that supervision. In the ThriftyDAgger study, ten participants supervised three simulated robots for 350 steps. Table 7 reports means of 532.6 s of active teleoperation and 792.8 s total with HG-DAgger, versus 365.4 s active and 625.5 s total with the ThriftyDAgger query criterion. Table 2 reports averages of 5.1 and 9.2 completed tasks, respectively. The protocol required continuous monitoring under HG-DAgger, while ThriftyDAgger requested help from the participant, who could do another task between requests. These are results from that study, not times for our simulator or a guarantee for another robot.
The same paper reports a physical cable-routing experiment: with 25 initial human demonstrations, the BC policy achieved 0/15 autonomous successes, HG-DAgger 10/15, and ThriftyDAgger 12/15. Those trials used a different robot, interface, and intervention budget from ours. The published data illustrate that human correction can help, but they do not demonstrate that our scripted comparison has the same outcome or that the methods used the same number of additional labels. We attribute no human time or annotator to our experiment.
The lab module includes intervenciones(env, policy, operador). The callback returns whether it has control and the action; while it has control its applied actions are recorded. The code measures total supervision time, time spent in calls under control, and intervened steps. A simulated callback checks the interface mechanics; it is not a human demonstration or a measurement of human time. OperadorPygame displays the overhead camera: hold Space to take control with the mouse, release it to hand control back, and press Escape to cancel. The time in calls under control includes rendering and waiting in the loop; it is not an independent measurement of cognitive effort.
For a real test in a local kernel with a display, after running this lesson’s first cell you can use the following snippet. Load only a checkpoint you generated yourself: it contains NumPy arrays and requires weights_only=False in recent PyTorch. The person supervises the entire episode; their interventions are neither simulated nor invented.
import json, time
import numpy as np, torch
from p13_bc import Politica
from p13_pusht import TareaEmpujeT
from p13_dagger import OperadorPygame, intervenciones
checkpoint = torch.load(base / 'p13-l02' / 'bc_0_roll.pt', map_location='cpu', weights_only=False)
modelo = Politica()
modelo.load_state_dict(checkpoint['state_dict'])
modelo.eval()
xm, xs, am, ast = checkpoint['stats']
def politica(obs):
x = np.r_[obs['observation.state'], obs['observation.environment_state']].astype('float32')
with torch.no_grad():
return modelo(torch.as_tensor(((x-xm)/xs)[None])).numpy()[0] * ast + am
tarea = TareaEmpujeT()
tarea.reiniciar(50000)
operador = OperadorPygame(tarea)
try:
registro = intervenciones(tarea, politica, operador)
finally:
operador.cerrar()
print('segundos supervisando', registro['supervision_seconds'],
'segundos en llamadas intervenidas', registro['intervention_seconds'],
'etiquetas', registro['intervention_steps'])
if registro['labels']:
out = base / 'p13-l03' / 'humano'
out.mkdir(parents=True, exist_ok=True)
stamp = str(time.time_ns())
x_humano = np.stack([np.r_[o['observation.state'], o['observation.environment_state']]
for o, _ in registro['labels']]).astype('float32')
a_humano = np.stack([a for _, a in registro['labels']]).astype('float32')
np.savez_compressed(out / f'intervenciones-{stamp}.npz', observations=x_humano, expert_actions=a_humano)
meta = {k: v for k, v in registro.items() if k != 'labels'}
(out / f'intervenciones-{stamp}.json').write_text(json.dumps(meta), encoding='utf-8')
The saved matrix contains one row per intervention and the same applied action received by the simulator. To retrain, concatenate it with the training pairs from p13-l01 and call entrenar from p13_dagger using the statistics saved in the checkpoint; then evaluate with independent seeds. Do not present the time of the automated test below as a person’s time.
from p13_pusht import leer_lerobot
from p13_bc import matriz, evaluar
from p13_dagger import entrenar
if registro['labels']:
info, _, episodios, _ = leer_lerobot(dataset)
n_train = int(info['splits']['train'].split(':')[1])
x = np.concatenate([matriz(e) for e in episodios[:n_train]] + [x_humano])
a = np.concatenate([e['action'] for e in episodios[:n_train]] + [a_humano]).astype('float32')
corregida = entrenar(x, a, (xm, xs, am, ast), seed=0, device=torch.device('cpu'), epochs=60)
prueba_humana = evaluar(corregida, (xm, xs, am, ast), list(range(20000, 20100)),
x, torch.device('cpu'))
print('éxitos', prueba_humana['successes'], '/', prueba_humana['n'], 'Wilson', prueba_humana['wilson'])
Lab with the same simulator
Download p13_dagger.py together with p13_pusht.py and p13_bc.py, or place the modules at the repository paths. The complete dataset from the first lesson is required. Each expert query runs candidate simulations, so this experiment takes considerably longer than evaluating an MLP. The code does not replace the oracle with a synthetic response.
import os, sys
from pathlib import Path
for variable, fallback in [('P13_BC_CODE_DIR', 'public/data/p13/l02'),
('P13_DAGGER_CODE_DIR', 'public/data/p13/l03')]:
directory = Path(os.environ.get(variable, fallback))
if directory.exists():
sys.path.insert(0, str(directory.resolve()))
from p13_dagger import comparar
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_DAGGER_OUTPUT_DIR', base / 'p13-l03'))
resultados = [comparar(dataset, salida / f'semilla-{seed}', train_seed=seed,
budgets=(200, 200, 200), betas=(0.6, 0.3, 0.0), epochs=60)
for seed in (0, 1, 2)]npm run lab and open the connection link.Each row saves the cumulative number of additional labels, collection episodes, query time, per-episode results, and labeled states and actions. The checkpoints contain the same input and output transformations used during training. The oracle is queried only at physically reached states; that does not prove all of them are recoverable. If the experiment does not improve, report the rates and their intervals as observed, examine the collected states, and consider whether the planner and representation are suitable before attributing failure to DAgger.
In one run with MuJoCo 4.0.1 and three training seeds, both BC and DAgger achieved 0/100 successes after each budget of 200, 400, and 600 additional labels. Each Wilson interval is . In every round the 200 queries were exhausted in a single episode: there are many correlated states and little diversity in initial conditions. This run shows no DAgger advantage at equal budget and does not establish that the methods are equivalent or cannot improve under another design. The cell produces oracle times for your machine; we do not extrapolate them as human times or hardware constants.
import numpy as np
for seed, filas in enumerate(resultados):
for row in filas:
print('semilla', seed, 'ronda', row['iteration'], 'etiquetas iniciales', row['initial_labels'],
'adicionales', row['additional_labels'], 'episodios de recogida', row['timing']['episodes'],
'segundos de oráculo', round(row['timing']['oracle_seconds'], 2))
for name in ('bc', 'dagger'):
result = row[name]
print(name, result['successes'], '/', result['n'], 'Wilson', np.round(result['wilson'], 3))npm run lab and open the connection link.The following automated test forces two intervention steps and verifies that the applied action is saved after clipping to the table. It does not measure operator ergonomics: it checks only the contract among the callback, controller, and environment.
from p13_pusht import TareaEmpujeT
from p13_dagger import intervenciones
import numpy as np
tarea = TareaEmpujeT()
tarea.reiniciar(50000)
politica_quieta = lambda obs: obs['observation.state']
operador_simulado = lambda obs, t: (t in (1, 2), np.array([-1., 513.]))
prueba = intervenciones(tarea, politica_quieta, operador_simulado, max_steps=5)
assert prueba['intervention_steps'] == 2
assert all(np.array_equal(action, [0., 512.]) for _, action in prueba['labels'])
print('pasos bajo control simulado', prueba['intervention_steps'], 'etiquetas', len(prueba['labels']))npm run lab and open the connection link.Exercises
def dagger(policy, expert, env, n_iters, beta_schedule):
passDAgger queries the expert on the distribution created by the policy and accumulates corrected pairs. Its advantage is measured at equal budget and with new rollouts; it requires a useful oracle outside the demonstrations and does not guarantee that every implementation or final iteration outperforms BC. Human correction adds supervision and control costs that must be measured separately.