Skip to content

LeWAM: a matched experiment on our robotic arm ​

INFO

本页尚未翻译。 阅读英文版

Open in Colab

Compare the upstream LeWAM model and training loss with our library implementation on the same ObstacleArm-v0 trajectories. Both start from identical active weights and train sampled future goals for 50 epochs. This is an owned-environment study, not a reproduction of DMControl Reacher scores.

Upstream code · Implementation and experiment details

1. Setup ​

Install torch-world[lewam,notebooks]. The default path reads saved progress/results and never trains or commands a physical robot. Rerunning training also requires torchvision and an explicit checkout of the pinned upstream source, supplied through LEWAM_REFERENCE.

python
import importlib.util

if importlib.util.find_spec("torch_world") is None:  # on Colab
    %pip install -q "torch-world[lewam]"
python
import json
import os
import sys
from pathlib import Path

if sys.platform == "linux":
    os.environ.setdefault("MUJOCO_GL", "egl")

import matplotlib.pyplot as plt
from IPython.display import Image, Markdown, display

import torch_world
from torch_world.benchmarks.lewam_arm_diagnostics import plot_rollout
from torch_world.benchmarks.lewam_matched import train_matched
from torch_world.benchmarks.lewam_study import evaluate_study, prepare_data

ROOT = Path(torch_world.__file__).resolve().parents[1]
REPORTS = ROOT / "examples/action/reports"
OUTPUT = ROOT / "runs/lewam-matched-repeat"
REFERENCE = os.environ.get("LEWAM_REFERENCE")
RUN_TRAINING = False

2. Matched training ​

ComponentShared setting
Data128 verified training trajectories; 16 validation trajectories
InputsTwo RGB frames five controls apart; sampled future image goal
ArchitectureResNet18/GN16, spatial keypoints, 192-dimensional latents
Dynamics / actionsPredict one state at +5 controls; ten-action chunks
Schedule50 complete epochs, batch 128, five warmup epochs; 4,800 updates per model
InitializationIdentical active parameters, from scratch
OptimizationAdamW, peak learning rate 0.00015, cosine decay, gradient clipping
PrecisionBfloat16 autocast; float32 latent boundary for both models

The float32 boundary fixes an upstream indexed-write dtype incompatibility with the installed PyTorch version. It preserves gradients through the encoder. Bfloat16 is an upstream-supported option; its default configuration uses float32. The implementations consume random draws differently, so paired seeds do not imply identical stochastic gradients.

The actual upstream encoder, transformer, loss and regularizer are loaded from the supplied source. Both use our shared data sampler, optimizer schedule, environment and tested planning API. This isolates the model/training implementations; it is not an independent reproduction of the entire upstream CLI.

python
if RUN_TRAINING:
    if not REFERENCE:
        raise ValueError("Set LEWAM_REFERENCE to the pinned upstream checkout before training")
    prepare_data(OUTPUT / "data")
    training = train_matched(
        OUTPUT / "training", OUTPUT / "data/episodes.pt", REFERENCE,
        epochs=50, batch_size=128, precision="bf16", device="cuda",
    )
    result = evaluate_study(OUTPUT / "training", REFERENCE, OUTPUT / "evaluation", cases=50)
    artifact_root = OUTPUT / "evaluation/unseen_trajectories/42/local/0"
else:
    training_path = REPORTS / "lewam-matched-training.json"
    training = json.loads(training_path.read_text()) if training_path.exists() else {}
    result_path = REPORTS / "lewam-matched.json"
    result = json.loads(result_path.read_text()) if result_path.exists() else {}
    artifact_root = REPORTS

ready = bool(result.get("complete"))
print(f"Training: {len(training.get('curve', []))}/{training.get('epochs', 50)} epochs recorded")
print("Matched evaluation complete" if ready else "Matched evaluation pending; no new success result is claimed")
if training.get("curve"):
    fig, ax = plt.subplots(figsize=(7, 3))
    for name in ("local", "upstream"):
        ax.plot([r["epoch"] for r in training["curve"]],
                [r[name]["validation_flow"] for r in training["curve"]], label=name)
    ax.set(xlabel="Epoch", ylabel="Validation flow loss", title="Selection metric; not control success")
    ax.legend()
    plt.show()
text
Training: 50/50 epochs recorded
Matched evaluation complete

3. Environment and coverage ​

Physics, torque limits and native success tolerances stay fixed. A render-only marker preserves the collection target in current and goal images. The scored target is the sampled future arm pose. Trajectory replay and goal rendering are checked independently of learned performance.

A separate coverage dataset adds reverse approaches, corrections on both sides of the goal, and braking from nonzero velocity. All 128 training and 16 validation demonstrations held native success over their final ten recorded states. This dataset has not been used by the matched baseline models. To run a subsequent coverage comparison, call prepare_data(path, diverse_motion=True) and pass its episodes.pt to the same trainer.

python
coverage_path = REPORTS / "lewam-matched-coverage.json"
if coverage_path.exists():
    coverage = json.loads(coverage_path.read_text())
    for split, held in coverage["ten_frame_hold"].items():
        print(f"Diverse data · {split}: {sum(held)}/{len(held)} final ten-frame holds")
replay_path = REPORTS / "lewam-matched-replay.json"
if replay_path.exists():
    replay = json.loads(replay_path.read_text())["replay"]
    display(Markdown(
        "| Replay check | Maximum error |\n|---|---:|\n"
        f"| State | {max(r['max_state_error'] for r in replay):.2g} |\n"
        f"| Pixels (uint8) | {max(r['max_pixel_error_uint8'] for r in replay):.2g} |\n"
        f"| State changed by goal rendering | {max(r['goal_render_state_error'] for r in replay):.2g} |"
    ))
text
Diverse data · train: 128/128 final ten-frame holds
Diverse data · validation: 16/16 final ten-frame holds
Replay checkMaximum error
State0
Pixels (uint8)0
State changed by goal rendering0

4. Reaching, settling and holding ​

Evaluation uses 50 cases for each of seeds 42, 0 and 1, separately on training trajectories and unseen trajectories. Starts are sampled across the eligible trajectory; goals are 25 controls later, with a 50-control budget. Models share exactly the same tasks. Each planner uses 32 proposals and five Adam refinements, executing five controls before replanning.

Pose reached ignores velocity. Native reached also requires settling. Final checks native success at the last step; hold requires it throughout the final ten controls. Initial pose successes are shown explicitly, with a separate score for initially unsatisfied tasks. Our pose tolerance is not the identical DMControl criterion.

Direct policy, planned policy and shuffled-goal planning are learned controllers. Expert and zero-control baselines check feasibility and passive motion; neither intervenes in learned control.

python
if ready:
    rows = ["| Split | Model / controller | Initial pose | Pose reached | Native reached | Final | Hold |",
            "|---|---|---:|---:|---:|---:|---:|"]
    for split, models in result["summary"].items():
        for model, controllers in models.items():
            for controller, scores in controllers.items():
                if model == "upstream" and controller in ("expert", "zero"):
                    continue  # Shared baseline trials, already displayed once.
                n = scores["count"]
                values = " | ".join(f"{scores[k]}/{n}" for k in
                    ("pose_initial_success", "pose_success", "success", "final_success", "hold_success"))
                rows.append(f"| {split} | {model} / {controller} | {values} |")
    display(Markdown("\n".join(rows)))
    rows = ["| Split | Model / controller | Pose hits from initially unsatisfied tasks |", "|---|---|---:|"]
    for split, models in result["summary"].items():
        for model, controllers in models.items():
            for controller in ("policy", "planner", "shuffled_goal_planner"):
                s = controllers[controller]["initially_pose_unsatisfied"]
                rows.append(f"| {split} | {model} / {controller} | {s['pose_success']}/{s['count']} |")
    display(Markdown("\n".join(rows)))
else:
    display(Markdown("**Evaluation is pending.** Earlier pilot scores are not substituted for this study."))
SplitModel / controllerInitial posePose reachedNative reachedFinalHold
training_trajectorieslocal / policy65/150149/150138/15081/15081/150
training_trajectorieslocal / planner65/150146/150120/15015/15015/150
training_trajectorieslocal / shuffled_goal_planner65/150139/15092/1501/1501/150
training_trajectorieslocal / expert65/150150/150150/150150/150148/150
training_trajectorieslocal / zero65/15072/15071/1500/1500/150
training_trajectoriesupstream / policy65/150149/150140/15099/15099/150
training_trajectoriesupstream / planner65/150145/150116/1508/1508/150
training_trajectoriesupstream / shuffled_goal_planner65/150138/15091/1502/1501/150
unseen_trajectorieslocal / policy60/150147/150136/15084/15084/150
unseen_trajectorieslocal / planner60/150141/150110/1508/1507/150
unseen_trajectorieslocal / shuffled_goal_planner60/150134/15089/1507/1505/150
unseen_trajectorieslocal / expert60/150150/150150/150150/150148/150
unseen_trajectorieslocal / zero60/15065/15062/1500/1500/150
unseen_trajectoriesupstream / policy60/150147/150135/15089/15089/150
unseen_trajectoriesupstream / planner60/150142/150107/1509/1509/150
unseen_trajectoriesupstream / shuffled_goal_planner60/150129/15080/1501/1500/150
SplitModel / controllerPose hits from initially unsatisfied tasks
training_trajectorieslocal / policy84/85
training_trajectorieslocal / planner81/85
training_trajectorieslocal / shuffled_goal_planner74/85
training_trajectoriesupstream / policy84/85
training_trajectoriesupstream / planner80/85
training_trajectoriesupstream / shuffled_goal_planner73/85
unseen_trajectorieslocal / policy87/90
unseen_trajectorieslocal / planner81/90
unseen_trajectorieslocal / shuffled_goal_planner74/90
unseen_trajectoriesupstream / policy87/90
unseen_trajectoriesupstream / planner82/90
unseen_trajectoriesupstream / shuffled_goal_planner69/90

5. Does the world model choose useful actions? ​

The prediction audit compares identical recorded/perturbed action sequences in both models at 5, 10 and 25 controls. It measures latent prediction error, action-ranking agreement with actual pose distance, and selection regret relative to the best tested candidate. Tied candidate pairs are excluded from ranking agreement.

Ranking actual future images tests the visual distance metric; ranking imagined future images additionally tests learned dynamics. These are diagnostic candidate sets, not proof of global planning accuracy. The audit uses validation episodes and does not select checkpoints.

python
if ready:
    rows = ["| Controls | Model | Variance-normalized prediction MSE | Predicted ranking agreement | Actual-image ranking agreement | Selection regret |",
            "|---:|---|---:|---:|---:|---:|"]
    def mean_valid(values):
        valid = [x for x in values if x is not None]
        return sum(valid) / len(valid) if valid else float("nan")
    for horizon, models in result["prediction_audit"]["horizons"].items():
        for name, metrics in models.items():
            predicted = metrics["predicted_ranking"]
            actual = metrics["encoded_actual_ranking"]
            rows.append(f"| {horizon} | {name} | {metrics['variance_normalized_mse']:.3f} | "
                        f"{mean_valid(predicted['pairwise_agreement']):.3f} | "
                        f"{mean_valid(actual['pairwise_agreement']):.3f} | "
                        f"{mean_valid(predicted['selection_regret']):.3f} |")
    display(Markdown("\n".join(rows)))
else:
    print("Prediction diagnostics will be displayed after matched evaluation completes.")
ControlsModelVariance-normalized prediction MSEPredicted ranking agreementActual-image ranking agreementSelection regret
5local1.1420.7500.7720.485
5upstream1.1650.6790.8300.759
10local1.2960.7370.8481.062
10upstream1.3080.7460.8440.600
25local1.5670.7370.8040.000
25upstream1.5350.7320.8170.000

6. Inspect the first unseen rollout and interpret the comparison ​

The video uses the first unseen task for evaluation seed 42, selected without inspecting success. Left: current observation; right: goal. The action plot compares commands with expert labels at the states actually visited. Those labels never control the learned rollout.

If both implementations fail similarly, focus next on demonstration coverage and the learned distance/dynamics rather than assuming a local model bug. If upstream performs materially better, isolate the remaining implementation differences before changing the task. A reaching advantage does not establish sustained holding, and neither result qualifies SO101 hardware execution.

This study uses one shared model initialization. The three evaluation seeds measure task-sampling variation, not variation across independently trained models. No near-100% result is guaranteed.

python
if ready:
    trace_path = artifact_root / ("trace-planner.json" if RUN_TRAINING else "lewam-matched-trace.json")
    video_path = artifact_root / ("rollout.gif" if RUN_TRAINING else "lewam-matched.gif")
    trace = json.loads(trace_path.read_text())
    print(f"First unseen rollout · seed {trace['seeds'][0]}")
    display(Image(filename=str(video_path)))
    plot_rollout(trace)
    plt.show()
else:
    print("Full study still running. No new rollout or completed-result interpretation is available yet.")
print("Simulation only; no physical-robot commands were issued.")
text
First unseen rollout · seed 50017

text
Simulation only; no physical-robot commands were issued.