| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| """Compute and store the mean goal embedding using a trained model.""" |
|
|
| import os |
| import typing |
|
|
| from absl import app |
| from absl import flags |
| from absl import logging |
| import numpy as np |
| import torch |
| import matplotlib.pyplot as plt |
| from torchkit import CheckpointManager |
| from tqdm.auto import tqdm |
| import utils |
| from xirl import common |
| from xirl.models import SelfSupervisedModel |
|
|
| |
|
|
| FLAGS = flags.FLAGS |
|
|
| flags.DEFINE_string("experiment_path", None, "Path to model checkpoint.") |
| 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 compute_frame_distances( |
| model, |
| downstream_loader, |
| device, |
| goal_emb, |
| save_path |
| ): |
| """Compute per-frame distance to the averaged goal embedding for each trajectory. |
| |
| Args: |
| model: Trained model used for embedding. |
| downstream_loader: DataLoader containing video frames. |
| device: Torch device (CPU/GPU). |
| goal_emb: Averaged goal embedding computed earlier. |
| save_path: Path to save the per-frame distances as a .txt file. |
| """ |
| with open(save_path, "w") as f: |
| for class_name, class_loader in downstream_loader.items(): |
| logging.info(f"Computing per-frame distances for {class_name}.") |
| for batch in tqdm(iter(class_loader), leave=False): |
| task_txts = [path.split('/')[-2] for path in batch["video_name"]] |
| out = model.infer(batch["frames"].to(device), task_txts) |
| embs = out.numpy().embs |
| |
|
|
| |
| distances = np.linalg.norm(embs - goal_emb, axis=-1) |
|
|
| |
| traj_name = batch["video_name"][0] |
| f.write(f"{traj_name}: {' '.join(map(str, distances))}\n") |
|
|
| def compute_subgoal_embeddings( |
| model, |
| downstream_loader, |
| device, |
| num_keyframes=8, |
| save_path="subgoals.pkl", |
| img_save_path="keyframes_visualization.png" |
| ): |
| """Compute subgoal embeddings by subsampling keyframes across all trajectories. |
| |
| Args: |
| model: Trained model used for embedding. |
| downstream_loader: DataLoader containing video frames. |
| device: Torch device (CPU/GPU). |
| num_keyframes: Number of keyframes to sample (default=8). |
| save_path: Path to save the final subgoal embeddings as a pickle file. |
| """ |
| subgoal_embs = [] |
| sampled_images = [] |
|
|
| for class_name, class_loader in downstream_loader.items(): |
| logging.info(f"Processing {class_name} for subgoal embeddings.") |
| traj_embs = [] |
| traj_keyframes = [] |
|
|
| for batch in tqdm(iter(class_loader), leave=False): |
| task_txts = [path.split('/')[-2] for path in batch["video_name"]] |
| |
| |
| out = model.infer(batch["frames"].to(device), task_txts) |
| embs = out.numpy().embs |
|
|
| |
| num_frames = embs.shape[0] |
| keyframe_idxs = np.linspace(0, num_frames - 1, num=num_keyframes, dtype=int) |
|
|
| |
| traj_embs.append(embs[keyframe_idxs]) |
| traj_keyframes.append(batch["frames"][0][keyframe_idxs]) |
|
|
| |
| subgoal_emb = np.mean(np.stack(traj_embs, axis=0), axis=0) |
| subgoal_embs.append(subgoal_emb) |
| sampled_images.append(traj_keyframes) |
|
|
| |
| final_subgoals = np.mean(np.stack(subgoal_embs, axis=0), axis=0) |
|
|
| |
| |
| |
| |
|
|
| |
| utils.save_pickle(FLAGS.experiment_path, final_subgoals, save_path) |
| logging.info(f"Saved subgoal embeddings to {save_path}.") |
|
|
| |
| |
| |
| logging.info("Calculating per-chunk subgoal scale factors.") |
| subgoal_scale_factors = [] |
| |
| for i in range(len(final_subgoals) - 1): |
| subgoal_a = final_subgoals[i] |
| subgoal_b = final_subgoals[i+1] |
|
|
| |
| distance = np.linalg.norm(subgoal_b - subgoal_a) |
| scale_factor = 1.0 / (distance + 1e-8) |
| subgoal_scale_factors.append(scale_factor) |
|
|
| subgoal_scale_factors = np.array(subgoal_scale_factors) |
| print(subgoal_scale_factors) |
|
|
| |
| scale_save_path = "subgoal_scale_factors.pkl" |
| utils.save_pickle( |
| FLAGS.experiment_path, subgoal_scale_factors, scale_save_path |
| ) |
| logging.info(f"Saved subgoal scale factors to {scale_save_path}.") |
| |
| |
| |
|
|
| save_keyframe_visualization(np.array(sampled_images), img_save_path) |
|
|
| return final_subgoals |
|
|
| def save_encoded_trajectories( |
| model, |
| downstream_loader, |
| device, |
| base_save_dir, |
| ): |
| """ |
| Embeds all frames of all trajectories and saves each sequence as a |
| separate .npy file, structured by task directory. |
| |
| Args: |
| model: Trained model (temporal encoder). |
| downstream_loader: DataLoader containing demonstration video frames. |
| device: Torch device (CPU/GPU). |
| base_save_dir: Base directory to save the output structure |
| (e.g., 'experiment_path/encoded_features/'). |
| """ |
| logging.info("Starting to embed and save full trajectories.") |
| os.makedirs(base_save_dir, exist_ok=True) |
| |
| for class_name, class_loader in downstream_loader.items(): |
| |
| task_save_dir = os.path.join(base_save_dir, class_name) |
| os.makedirs(task_save_dir, exist_ok=True) |
| logging.info(f"Saving embeddings for task '{class_name}' to {task_save_dir}.") |
|
|
| for batch in tqdm(iter(class_loader), leave=False): |
| task_txts = [path.split('/')[-2] for path in batch["video_name"]] |
| |
| |
| with torch.no_grad(): |
| out = model.infer(batch["frames"].to(device), task_txts) |
| embs = out.numpy().embs |
|
|
| |
| |
| path_parts = batch["video_name"][0].split(os.path.sep) |
| |
| if len(path_parts) >= 3: |
| traj_id = path_parts[-1] |
| else: |
| traj_id = "unknown_traj_" + str(np.random.randint(10000)) |
|
|
| traj_save_dir = os.path.join(task_save_dir, traj_id) |
| os.makedirs(traj_save_dir, exist_ok=True) |
|
|
| |
| filename = os.path.join(traj_save_dir, f"{traj_id}.npy") |
| np.save(filename, embs) |
| |
| logging.info(f"Finished saving all encoded trajectories to {base_save_dir}.") |
|
|
| def save_keyframe_visualization(sampled_images, save_path): |
| """Save an example visualization of the sampled keyframes. |
| |
| Args: |
| sampled_images: Array of shape (num_trajectories, num_keyframes, C, H, W). |
| save_path: Path to save the visualization image. |
| """ |
| sampled_images = np.squeeze(sampled_images) |
| num_trajectories = sampled_images.shape[0] |
| num_keyframes = sampled_images.shape[1] |
|
|
| fig, axes = plt.subplots(num_trajectories, num_keyframes, figsize=(num_keyframes * 2, num_trajectories * 2)) |
|
|
| for i in range(num_trajectories): |
| for j in range(num_keyframes): |
| ax = axes[i, j] if num_trajectories > 1 else axes[j] |
| img = sampled_images[i, j].transpose(1, 2, 0) |
| ax.imshow(img) |
| ax.axis("off") |
|
|
| plt.tight_layout() |
| plt.savefig(save_path) |
| plt.close() |
| logging.info(f"Saved keyframe visualization to {save_path}.") |
|
|
| def compute_subgoal_to_goal_distances(subgoals, goal_emb, save_path): |
| """Compute and save the L2 distance between each subgoal embedding and the final goal embedding. |
| |
| Args: |
| subgoals: Array of subgoal embeddings. |
| goal_emb: Final goal embedding. |
| save_path: Path to save the subgoal-to-goal distances as a .txt file. |
| """ |
| |
| distances = np.linalg.norm(subgoals - goal_emb, axis=-1) |
|
|
| |
| with open(save_path, "w") as f: |
| for i, dist in enumerate(distances): |
| f.write(f"Subgoal {i + 1}: {dist:.6f}\n") |
|
|
| logging.info(f"Saved subgoal-to-goal distances to {save_path}.") |
|
|
| def embed( |
| model, |
| downstream_loader, |
| device, |
| ): |
| """Embed the stored trajectories and compute mean goal embedding.""" |
| goal_embs = [] |
| init_embs = [] |
| for class_name, class_loader in downstream_loader.items(): |
| logging.info("Embedding %s.", class_name) |
| for batch in tqdm(iter(class_loader), leave=False): |
| task_txts = [path.split('/')[-2] for path in batch["video_name"]] |
| out = model.infer(batch["frames"].to(device), task_txts) |
| emb = out.numpy().embs |
| init_embs.append(emb[0, :]) |
| goal_embs.append(emb[-1, :]) |
| goal_emb = np.mean(np.stack(goal_embs, axis=0), axis=0, keepdims=True) |
| dist_to_goal = np.linalg.norm( |
| np.stack(init_embs, axis=0) - goal_emb, axis=-1).mean() |
| distance_scale = 1.0 / dist_to_goal |
| return goal_emb, distance_scale |
|
|
|
|
| def setup(): |
| """Load the latest embedder checkpoint and dataloaders.""" |
| config = utils.load_config_from_dir(FLAGS.experiment_path) |
| model = common.get_model(config) |
| config.data_augmentation.train_transforms = config.data_augmentation.eval_transforms |
| downstream_loaders = common.get_downstream_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 main(_): |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| model, downstream_loader = setup() |
| model.to(device).eval() |
| goal_emb, distance_scale = embed(model, downstream_loader, device) |
| utils.save_pickle(FLAGS.experiment_path, goal_emb, "goal_emb.pkl") |
| utils.save_pickle(FLAGS.experiment_path, distance_scale, "distance_scale.pkl") |
| |
| |
| save_path = os.path.join(FLAGS.experiment_path, "frame_distances.txt") |
| compute_frame_distances(model, downstream_loader, device, goal_emb, save_path) |
|
|
| |
| subgoals = compute_subgoal_embeddings(model, downstream_loader, device, |
| num_keyframes=8, save_path="subgoals_emb.pkl") |
|
|
| |
| save_distance_path = os.path.join(FLAGS.experiment_path, "subgoal_to_goal_distances.txt") |
| compute_subgoal_to_goal_distances(subgoals, goal_emb, save_distance_path) |
|
|
| |
|
|
|
|
| if __name__ == "__main__": |
| flags.mark_flag_as_required("experiment_path") |
| app.run(main) |
|
|