|
|
|
|
| """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() |
| |
|
|
| 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'] |
| 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) |
| fig.canvas.draw() |
| img_arr = np.array(fig.canvas.renderer.buffer_rgba())[:, :, :3] |
| |
| |
| |
| 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 = [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) |
|
|