multi-task-tcc-robosuite / compute_subgoal_embedding.py
Renton-Ren's picture
Upload folder using huggingface_hub
58e7e8d verified
Raw
History Blame Contribute Delete
12.6 kB
# coding=utf-8
# Copyright 2024 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""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
# pylint: disable=logging-fstring-interpolation
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 # Shape: (num_frames, embedding_dim)
# print(batch["frames"].shape, embs.max(), embs.min())
# Compute L2 distance per frame
distances = np.linalg.norm(embs - goal_emb, axis=-1)
# Save distances for this trajectory
traj_name = batch["video_name"][0] # Extract trajectory name
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"]]
# print(batch["frames"].shape)
# assert False
out = model.infer(batch["frames"].to(device), task_txts)
embs = out.numpy().embs # Shape: (num_frames, embedding_dim)
# Get keyframe indices (uniform subsampling)
num_frames = embs.shape[0]
keyframe_idxs = np.linspace(0, num_frames - 1, num=num_keyframes, dtype=int)
# Store selected embeddings for this trajectory
traj_embs.append(embs[keyframe_idxs])
traj_keyframes.append(batch["frames"][0][keyframe_idxs])
# Compute mean embedding per keyframe across all trajectories
subgoal_emb = np.mean(np.stack(traj_embs, axis=0), axis=0)
subgoal_embs.append(subgoal_emb)
sampled_images.append(traj_keyframes)
# Compute final subgoal embeddings across all trajectory classes
final_subgoals = np.mean(np.stack(subgoal_embs, axis=0), axis=0)
# Remove the ambiguous subgoal frame for metaworld, comment out for other tasks.
# print(final_subgoals)
# final_subgoals = np.delete(final_subgoals, 1, axis=0) # For assembly
# print(final_subgoals)
# Save subgoal embeddings
utils.save_pickle(FLAGS.experiment_path, final_subgoals, save_path)
logging.info(f"Saved subgoal embeddings to {save_path}.")
# ================================================================= #
# START: ADD YOUR IMPLEMENTATION HERE #
# ================================================================= #
logging.info("Calculating per-chunk subgoal scale factors.")
subgoal_scale_factors = []
# Iterate through pairs of consecutive subgoals
for i in range(len(final_subgoals) - 1):
subgoal_a = final_subgoals[i]
subgoal_b = final_subgoals[i+1]
# Calculate L2 distance and take the reciprocal for the scale factor
distance = np.linalg.norm(subgoal_b - subgoal_a)
scale_factor = 1.0 / (distance + 1e-8) # Add epsilon for stability
subgoal_scale_factors.append(scale_factor)
subgoal_scale_factors = np.array(subgoal_scale_factors)
print(subgoal_scale_factors)
# Save the calculated scale factors to a new pickle file
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}.")
# ================================================================= #
# END: IMPLEMENTATION #
# ================================================================= #
save_keyframe_visualization(np.array(sampled_images), img_save_path)
return final_subgoals # Return the subgoal embeddings
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():
# 1. Create a subdirectory for the current task (e.g., 'assembly')
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"]]
# Use full sequence inference (assuming batch size of 1 per video)
with torch.no_grad():
out = model.infer(batch["frames"].to(device), task_txts)
embs = out.numpy().embs # shape: (num_frames, embedding_dim)
# 2. Extract trajectory ID from the path (the unique folder name before the frame name)
# We assume the path structure is: .../task_name/traj_id/frame_name.png
path_parts = batch["video_name"][0].split(os.path.sep)
# [-2] is usually frame_name.png, [-3] is traj_id.
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)
# 3. Save the embedding sequence
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] # Handle 1-row case
img = sampled_images[i, j].transpose(1, 2, 0) # Convert (C, H, W) to (H, W, C)
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.
"""
# Compute L2 distances
distances = np.linalg.norm(subgoals - goal_emb, axis=-1)
# Save distances to a text file
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")
# Compute per-frame distances and save
save_path = os.path.join(FLAGS.experiment_path, "frame_distances.txt")
compute_frame_distances(model, downstream_loader, device, goal_emb, save_path)
# Compute and save subgoal embeddings
subgoals = compute_subgoal_embeddings(model, downstream_loader, device,
num_keyframes=8, save_path="subgoals_emb.pkl")
# Compute and save distances between subgoals and the final goal
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)
# save_encoded_trajectories(model, downstream_loader, device, FLAGS.experiment_path)
if __name__ == "__main__":
flags.mark_flag_as_required("experiment_path")
app.run(main)