File size: 6,274 Bytes
337a98d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
"""Compute 6 sequences of embeddings for three different tasks
and visualiza them in 3D t-SNE. Each task has 2 sequences.
"""
import os
import typing
from absl import app
from absl import flags
from absl import logging
import numpy as np
import torch
from torchkit import CheckpointManager
from tqdm.auto import tqdm
import utils
from xirl import common
from xirl.models import SelfSupervisedModel
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import matplotlib
import timm
plt.ion()
# pylint: disable=logging-fstring-interpolation
FLAGS = flags.FLAGS
flags.DEFINE_string("experiment_path", None, "Path to model checkpoint.")
flags.DEFINE_string("encoder_type", None, "Encoder: tcc or dinov2")
flags.DEFINE_boolean(
"restore_checkpoint", True,
"Restore model checkpoint. Disabling loading a checkpoint is useful if you "
"want to measure performance at random initialization.")
ModelType = SelfSupervisedModel
DataLoaderType = typing.Dict[str, torch.utils.data.DataLoader]
def _gen_emb_plot(embs):
"""Create a pyplot plot and save to buffer."""
markers = ['o', 'o', '^', '^', 's', 's']#, 'p', '*', 'D', 'X', 'v', '<', '>']
fig = plt.figure(dpi=600)
ax = fig.add_subplot(111, projection='3d')
for i, emb in enumerate(embs):
marker = markers[i % len(markers)]
ax.scatter(emb[:, 0], emb[:, 1], emb[:, 2], label=f"Sequence {i+1}", marker=marker)#, s=0.5
fig.canvas.draw()
img_arr = np.array(fig.canvas.renderer.buffer_rgba())[:, :, :3]
# plt.show()
# input("Press the Enter key to continue: ")
# plt.close()
return img_arr
def setup():
"""Load the latest embedder checkpoint and dataloaders."""
config = utils.load_config_from_dir(FLAGS.experiment_path)
model = common.get_model(config)
downstream_loaders = common.get_downstream_dataloaders(config, False)["train"]
pretraining_loaders = common.get_pretraining_dataloaders(config, False)["train"]
checkpoint_dir = os.path.join(FLAGS.experiment_path, "checkpoints")
if FLAGS.restore_checkpoint:
checkpoint_manager = CheckpointManager(checkpoint_dir, model=model)
global_step = checkpoint_manager.restore_or_initialize()
logging.info("Restored model from checkpoint %d.", global_step)
else:
logging.info("Skipping checkpoint restore.")
return model, downstream_loaders
def embed(
model,
downstream_loader,
device,
):
"""Embed the stored trajectories."""
seq_embs = []
for class_name, class_loader in downstream_loader.items():
count = 0
logging.info("Embedding %s.", class_name)
for batch in tqdm(iter(class_loader), leave=False):
out = model.infer(batch["frames"].to(device), class_name)
emb = out.numpy().embs
if count <= 1:
emb_3d = PCA(n_components=3, random_state=0).fit_transform(emb)
seq_embs.append(emb_3d)
count += 1
seq_lens = [s.shape[0] for s in seq_embs]
min_len = np.min(seq_lens)
same_length_embs = []
for emb in seq_embs:
emb_len = len(emb)
stride = emb_len / min_len
idxs = np.arange(0.0, emb_len, stride).round().astype(int)
idxs = np.clip(idxs, a_min=0, a_max=emb_len - 1)
idxs = idxs[:min_len]
same_length_embs.append(emb[idxs])
return same_length_embs, min_len
def tcc_enc_plot():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model, downstream_loader = setup()
model.to(device).eval()
traj, min_len = embed(model, downstream_loader, device)
return traj, min_len
def setup_dinov2():
encoder = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')
del encoder.head
import timm
encoder.pos_embed.data = timm.layers.pos_embed.resample_abs_pos_embed(
encoder.pos_embed.data, [16, 16],
)
encoder.head = torch.nn.Identity()
for param in encoder.parameters():
param.requires_grad = False
encoder.eval()
print("Restored pretrained dinov2 model.")
return encoder
def embed_dinov2(
model,
downstream_loader,
device,
):
"""Embed the stored trajectories."""
from torchvision import transforms as T, utils
seq_embs = []
for class_name, class_loader in downstream_loader.items():
count = 0
logging.info("Embedding %s.", class_name)
print(class_name)
for batch in tqdm(iter(class_loader), leave=False):
resize_transform = T.Resize((224, 224), interpolation=T.InterpolationMode.BICUBIC)
frames = resize_transform(batch["frames"].to(device).squeeze())
out = model(frames)
emb = out.cpu().numpy()
if count <= 1:
emb_3d = PCA(n_components=3, random_state=0).fit_transform(emb)
seq_embs.append(emb_3d)
count += 1
seq_lens = [s.shape[0] for s in seq_embs]
min_len = np.min(seq_lens)
same_length_embs = []
for emb in seq_embs:
emb_len = len(emb)
stride = emb_len / min_len
idxs = np.arange(0.0, emb_len, stride).round().astype(int)
idxs = np.clip(idxs, a_min=0, a_max=emb_len - 1)
idxs = idxs[:min_len]
same_length_embs.append(emb[idxs])
return same_length_embs, min_len
def dinov2_enc_plot():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
_, downstream_loader = setup()
model = setup_dinov2()
model.to(device).eval()
traj, min_len = embed_dinov2(model, downstream_loader, device)
return traj, min_len
def main(_):
encoder_type = FLAGS.encoder_type
if encoder_type == 'tcc':
traj, min_len = tcc_enc_plot()
if encoder_type == 'dinov2':
traj, min_len = dinov2_enc_plot()
# rand_tasks_idx = np.random.randint(0, len(traj)//2, size=3)
rand_tasks_idx = [7,8,9]
seq_to_vis = np.ones((6, min_len, 3))
for i in range(len(rand_tasks_idx)):
seq_to_vis[i*2] = traj[rand_tasks_idx[i]*2]
seq_to_vis[i*2+1] = traj[rand_tasks_idx[i]*2+1]
print(i*2, rand_tasks_idx[i]*2)
print(i*2+1, rand_tasks_idx[i]*2+1)
image = _gen_emb_plot(seq_to_vis)
if encoder_type == 'tcc':
matplotlib.image.imsave(f'/home/lei/Downloads/seq_vis_3tasks_{encoder_type}_{FLAGS.experiment_path.split("/")[-1]}.png', image)
else:
matplotlib.image.imsave(f'/home/lei/Downloads/seq_vis_3tasks_{encoder_type}.png', image)
if __name__ == "__main__":
flags.mark_flag_as_required("encoder_type")
flags.mark_flag_as_required("experiment_path")
app.run(main)
|