cable-representation-analysis / scripts /pca_cable_clusters.py
Kaz55's picture
ACT encoder representation analysis: 3-cable + 4-size t-SNE, contact-phase PCA, diameter axis
3c41fb5 verified
Raw History Blame Contribute Delete
4.61 kB
#!/usr/bin/env python3
"""PCA of a trained ACT policy's internal representation, coloured by cable type.
Asks whether the policy separates the three cables at all. Two spaces are
projected side by side:
encoder : ACT transformer-encoder output, captured with a forward hook --
this is what the policy actually conditions on
gelsight : raw tactile pixels (downsampled) -- what the sensor makes available
Read the pair together. Earlier resolution sweeps on four datasets showed the
training loss was unchanged even with GelSight removed entirely, so if the raw
tactile pixels separate by cable while the encoder features do not, that is
direct evidence the policy ignores information the sensor does provide.
"""
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from lerobot.datasets.lerobot_dataset import LeRobotDataset
from lerobot.policies.act.modeling_act import ACTPolicy
COLORS = {"blue cable": "#2B6CB0", "cable 1.70 sq": "#C05621", "cable 3.30 sq": "#2F855A"}
def episode_task(ds, ep):
t = ds.meta.episodes["tasks"][ep]
return t[0] if isinstance(t, (list, np.ndarray)) else str(t)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--repo-id", default="Kaz55/dg5f_ur5e_bluev2_cable170_330_270ep")
ap.add_argument("--policy-path", required=True)
ap.add_argument("--eps-per-task", type=int, default=15)
ap.add_argument("--frames-per-ep", type=int, default=20)
ap.add_argument("--device", default="cuda")
ap.add_argument("--out", default="outputs/pca/pca_cable_clusters.png")
args = ap.parse_args()
ds = LeRobotDataset(args.repo_id)
policy = ACTPolicy.from_pretrained(args.policy_path).to(args.device).eval()
# The encoder returns (seq, batch, dim); mean-pool the tokens into one vector.
captured = {}
policy.model.encoder.register_forward_hook(
lambda m, i, o: captured.__setitem__("enc", o.detach().mean(0).squeeze(0).float().cpu().numpy()))
by_task = {}
for ep in range(ds.meta.total_episodes):
by_task.setdefault(episode_task(ds, ep), []).append(ep)
rng = np.random.default_rng(0)
feats, pix, labels = [], [], []
for task, eps in sorted(by_task.items()):
chosen = rng.choice(eps, size=min(args.eps_per_task, len(eps)), replace=False)
print(f" {task}: {len(chosen)} episodes", flush=True)
for ep in chosen:
lo = int(ds.meta.episodes["dataset_from_index"][ep])
hi = int(ds.meta.episodes["dataset_to_index"][ep])
for i in rng.choice(np.arange(lo, hi),
size=min(args.frames_per_ep, hi - lo), replace=False):
item = ds[int(i)]
batch = {k: v.unsqueeze(0).to(args.device)
for k, v in item.items() if isinstance(v, torch.Tensor)}
batch["task"] = [task]
with torch.no_grad():
policy.select_action(batch) # runs the encoder; hook captures it
policy.reset() # clear the action queue between frames
feats.append(captured["enc"])
gs = item["observation.images.gelsight1"].unsqueeze(0).float()
pix.append(F.adaptive_avg_pool2d(gs, 16).flatten().numpy())
labels.append(task)
feats, pix = np.array(feats), np.array(pix)
print(f"collected {len(labels)} frames; encoder dim {feats.shape[1]}", flush=True)
fig, axes = plt.subplots(1, 2, figsize=(12, 5.2))
for ax, X, name in ((axes[0], feats, "ACT encoder features"),
(axes[1], pix, "raw GelSight pixels")):
Xc = X - X.mean(0)
p = PCA(n_components=2).fit(Xc)
xy = p.transform(Xc)
for task in sorted(set(labels)):
m = np.array([l == task for l in labels])
ax.scatter(xy[m, 0], xy[m, 1], s=9, alpha=0.55, edgecolors="none",
c=COLORS.get(task, "#666"), label=task)
ax.set_title(f"{name}\nPC1+PC2 explain {p.explained_variance_ratio_[:2].sum():.1%}",
fontsize=11)
ax.set_xlabel("PC1"); ax.set_ylabel("PC2")
ax.spines[["top", "right"]].set_visible(False)
axes[0].legend(frameon=False, fontsize=9)
fig.suptitle("Do the three cables form separate clusters?", fontsize=13)
fig.tight_layout()
fig.savefig(args.out, dpi=150)
print(f"wrote {args.out}", flush=True)
if __name__ == "__main__":
main()