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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import argparse, json, os, random
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import DataLoader, Subset
|
| 8 |
+
import matplotlib
|
| 9 |
+
matplotlib.use('Agg')
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
from sklearn.manifold import TSNE
|
| 12 |
+
from sklearn.preprocessing import StandardScaler
|
| 13 |
+
|
| 14 |
+
from vitacdreamer.dataset_v2 import ViTacDreamerTemporalMaskedDataset
|
| 15 |
+
from vitacdreamer.model_v2 import ViTacDreamerV2
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def list_hdf5(root: Path):
|
| 19 |
+
return sorted([p for p in root.iterdir() if p.suffix in ('.hdf5', '.h5')])
|
| 20 |
+
|
| 21 |
+
def task_from_path(p: Path):
|
| 22 |
+
stem=p.stem
|
| 23 |
+
return stem.split('__episode_',1)[0] if '__episode_' in stem else p.parent.name
|
| 24 |
+
|
| 25 |
+
def build_dataset(data_dir: Path, cfg: dict):
|
| 26 |
+
paths=list_hdf5(data_dir)
|
| 27 |
+
inferred=sorted({task_from_path(p) for p in paths})
|
| 28 |
+
cfg_tasks=cfg.get('task_names') or []
|
| 29 |
+
if cfg_tasks:
|
| 30 |
+
task_names=[t for t in cfg_tasks if t in inferred]
|
| 31 |
+
extra=[t for t in inferred if t not in task_names]
|
| 32 |
+
if extra:
|
| 33 |
+
raise ValueError(f'data contains tasks not in checkpoint config: {extra}; config tasks={cfg_tasks}')
|
| 34 |
+
else:
|
| 35 |
+
task_names=inferred
|
| 36 |
+
ds=ViTacDreamerTemporalMaskedDataset(
|
| 37 |
+
data_paths=paths,
|
| 38 |
+
history_len=int(cfg.get('history_len',5)),
|
| 39 |
+
image_size=int(cfg.get('visual_image_size',224)),
|
| 40 |
+
sample_stride=int(cfg.get('sample_stride',5)),
|
| 41 |
+
num_tail_frames=int(cfg.get('num_tail_frames',2)),
|
| 42 |
+
random_tail_mask=False,
|
| 43 |
+
augment=False,
|
| 44 |
+
task_names=task_names,
|
| 45 |
+
tactile_temporal_mode=cfg.get('tactile_temporal_mode','raw'),
|
| 46 |
+
tactile_flow_target_mode=cfg.get('tactile_flow_target_mode','depth_delta'),
|
| 47 |
+
tactile_flow_clip=float(cfg.get('tactile_flow_clip',0.25)),
|
| 48 |
+
marker_flow_clip=float(cfg.get('marker_flow_clip',1.0)),
|
| 49 |
+
depth_delta_clip=float(cfg.get('depth_delta_clip',0.5)),
|
| 50 |
+
tactile_delta_clip=float(cfg.get('tactile_delta_clip',0.25)),
|
| 51 |
+
)
|
| 52 |
+
return ds, task_names
|
| 53 |
+
|
| 54 |
+
def choose_balanced_indices(ds, max_per_task:int, seed:int):
|
| 55 |
+
rng=random.Random(seed)
|
| 56 |
+
buckets=defaultdict(list)
|
| 57 |
+
for i,s in enumerate(ds.samples):
|
| 58 |
+
buckets[s['task_name']].append(i)
|
| 59 |
+
chosen=[]
|
| 60 |
+
for task in sorted(buckets):
|
| 61 |
+
arr=buckets[task]
|
| 62 |
+
rng.shuffle(arr)
|
| 63 |
+
chosen.extend(arr[:max_per_task])
|
| 64 |
+
rng.shuffle(chosen)
|
| 65 |
+
return chosen
|
| 66 |
+
|
| 67 |
+
def load_model(cfg, ckpt_path, device, num_tasks):
|
| 68 |
+
model=ViTacDreamerV2(
|
| 69 |
+
visual_image_size=int(cfg.get('visual_image_size',224)),
|
| 70 |
+
tactile_image_size=int(cfg.get('tactile_image_size',224)),
|
| 71 |
+
action_dim=int(cfg.get('action_dim',7)),
|
| 72 |
+
latent_dim=int(cfg.get('latent_dim',512)),
|
| 73 |
+
history_len=int(cfg.get('history_len',5)),
|
| 74 |
+
pretrained_encoders=bool(cfg.get('pretrained_encoders',True)),
|
| 75 |
+
max_delta_t=int(cfg.get('max_delta_t',64)),
|
| 76 |
+
num_memory_layers=int(cfg.get('num_memory_layers',4)),
|
| 77 |
+
num_latent_layers=int(cfg.get('num_latent_layers',4)),
|
| 78 |
+
num_tail_frames=int(cfg.get('num_tail_frames',2)),
|
| 79 |
+
num_tasks=num_tasks,
|
| 80 |
+
reconstruct_tactile_flow=(cfg.get('tactile_flow_target_mode','none')!='none'),
|
| 81 |
+
).to(device)
|
| 82 |
+
ckpt=torch.load(ckpt_path, map_location=device)
|
| 83 |
+
state=ckpt.get('model_state_dict', ckpt)
|
| 84 |
+
missing, unexpected = model.load_state_dict(state, strict=False)
|
| 85 |
+
print('load', ckpt_path, 'missing', len(missing), 'unexpected', len(unexpected), flush=True)
|
| 86 |
+
model.eval()
|
| 87 |
+
return model
|
| 88 |
+
|
| 89 |
+
def collate(batch):
|
| 90 |
+
return torch.utils.data.default_collate(batch)
|
| 91 |
+
|
| 92 |
+
def extract(args):
|
| 93 |
+
out_dir=Path(args.out_dir); out_dir.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
cfg=json.load(open(args.config))
|
| 95 |
+
ds, task_names=build_dataset(Path(args.data_dir), cfg)
|
| 96 |
+
indices=choose_balanced_indices(ds, args.max_per_task, args.seed)
|
| 97 |
+
print('dataset samples', len(ds), 'selected', len(indices), 'tasks', task_names, flush=True)
|
| 98 |
+
subset=Subset(ds, indices)
|
| 99 |
+
loader=DataLoader(subset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True)
|
| 100 |
+
device=torch.device(args.device)
|
| 101 |
+
model=load_model(cfg, args.ckpt, device, len(task_names))
|
| 102 |
+
feats=[]; labels=[]; files=[]; timesteps=[]
|
| 103 |
+
with torch.no_grad():
|
| 104 |
+
for bi,batch in enumerate(loader):
|
| 105 |
+
visual_seq=batch['visual_seq'].to(device, non_blocking=True)
|
| 106 |
+
tactile_seq=batch['tactile_seq'].to(device, non_blocking=True)
|
| 107 |
+
action_seq=batch['action_seq'].to(device, non_blocking=True) if 'action_seq' in batch else None
|
| 108 |
+
visual_mask=batch['visual_mask'].to(device, non_blocking=True)
|
| 109 |
+
delta_steps=batch['delta_steps'].to(device, non_blocking=True) if 'delta_steps' in batch else None
|
| 110 |
+
task_id=batch['task_id'].to(device, non_blocking=True) if 'task_id' in batch else None
|
| 111 |
+
out=model(visual_seq, tactile_seq, action_seq, visual_mask, delta_steps=delta_steps, task_id=task_id)
|
| 112 |
+
# memory_context: B x num_tail_frames? or B x 1 x D. Flatten mean is stable for comparison.
|
| 113 |
+
f=out['memory_context'].detach().float()
|
| 114 |
+
if f.ndim>2: f=f.mean(dim=1)
|
| 115 |
+
feats.append(f.cpu().numpy())
|
| 116 |
+
labels.extend([task_names[int(x)] for x in task_id.detach().cpu().tolist()])
|
| 117 |
+
# map subset local batch rows back to ds samples
|
| 118 |
+
start=bi*args.batch_size
|
| 119 |
+
for j in range(len(task_id)):
|
| 120 |
+
s=ds.samples[indices[start+j]]
|
| 121 |
+
files.append(str(s['file']))
|
| 122 |
+
timesteps.append(int(s['timestep']))
|
| 123 |
+
print('batch', bi+1, 'features', sum(x.shape[0] for x in feats), flush=True)
|
| 124 |
+
X=np.concatenate(feats, axis=0)
|
| 125 |
+
Xs=StandardScaler().fit_transform(X)
|
| 126 |
+
perplexity=min(args.perplexity, max(5, (len(Xs)-1)//3))
|
| 127 |
+
Y=TSNE(n_components=2, perplexity=perplexity, init='pca', learning_rate='auto', random_state=args.seed, metric='euclidean').fit_transform(Xs)
|
| 128 |
+
np.savez(out_dir/f'{args.name}_features_tsne.npz', features=X, tsne=Y, labels=np.array(labels), files=np.array(files), timesteps=np.array(timesteps), task_names=np.array(task_names))
|
| 129 |
+
with open(out_dir/f'{args.name}_tsne.csv','w') as f:
|
| 130 |
+
f.write('x,y,task,file,timestep\n')
|
| 131 |
+
for (x,y),lab,fp,t in zip(Y,labels,files,timesteps):
|
| 132 |
+
f.write(f'{x},{y},{lab},{fp},{t}\n')
|
| 133 |
+
plt.figure(figsize=(7.2,6.0), dpi=220)
|
| 134 |
+
cmap=plt.get_cmap('tab10')
|
| 135 |
+
for k,task in enumerate(task_names):
|
| 136 |
+
m=np.array([l==task for l in labels])
|
| 137 |
+
plt.scatter(Y[m,0], Y[m,1], s=args.point_size, alpha=0.70, color=cmap(k%10), label=task, linewidths=0)
|
| 138 |
+
plt.title(f'{args.name}: ViTacDreamer memory-context t-SNE')
|
| 139 |
+
plt.xlabel('t-SNE 1'); plt.ylabel('t-SNE 2')
|
| 140 |
+
plt.legend(markerscale=2, fontsize=7, frameon=True)
|
| 141 |
+
plt.tight_layout()
|
| 142 |
+
plt.savefig(out_dir/f'{args.name}_tsne.png')
|
| 143 |
+
print('SAVED', out_dir/f'{args.name}_tsne.png', flush=True)
|
| 144 |
+
|
| 145 |
+
if __name__ == '__main__':
|
| 146 |
+
ap=argparse.ArgumentParser()
|
| 147 |
+
ap.add_argument('--name', required=True)
|
| 148 |
+
ap.add_argument('--data_dir', required=True)
|
| 149 |
+
ap.add_argument('--ckpt', required=True)
|
| 150 |
+
ap.add_argument('--config', required=True)
|
| 151 |
+
ap.add_argument('--out_dir', default='outputs/tsne_scaling_20260728')
|
| 152 |
+
ap.add_argument('--device', default='cuda:4')
|
| 153 |
+
ap.add_argument('--batch_size', type=int, default=32)
|
| 154 |
+
ap.add_argument('--num_workers', type=int, default=4)
|
| 155 |
+
ap.add_argument('--max_per_task', type=int, default=250)
|
| 156 |
+
ap.add_argument('--perplexity', type=int, default=35)
|
| 157 |
+
ap.add_argument('--point_size', type=float, default=10.0)
|
| 158 |
+
ap.add_argument('--seed', type=int, default=42)
|
| 159 |
+
extract(ap.parse_args())
|