""" Train a policy using SAC. Env: MetaWorld """ import collections import os import os.path as osp from typing import Optional from absl import app from absl import flags from absl import logging from ml_collections import config_dict from ml_collections import config_flags from torchkit import CheckpointManager from torchkit import experiment from torchkit import Logger from tqdm.auto import tqdm import torch import torch.nn as nn import torchvision.transforms as T import torch.nn.functional as F import numpy as np import albumentations as A import cv2 from PIL import Image from sac import agent from base_configs import validate_config import utils import matplotlib.pyplot as plt from r3m import load_r3m from flowdiffusion.inference_utils import get_video_model, pred_video from datasets import RoboSuiteDataset FLAGS = flags.FLAGS flags.DEFINE_string("experiment_name", None, "Experiment name.") flags.DEFINE_string("env_name", None, "The environment name.") flags.DEFINE_integer("num_envs", 4, "Number of parallel envs for training.") flags.DEFINE_integer("seed", 0, "RNG seed.") flags.DEFINE_string("device", "cuda:0", "The compute device.") flags.DEFINE_boolean("resume", False, "Resume experiment from last checkpoint.") flags.DEFINE_boolean( "randomize_initial_state", False, "If True, each env reset randomizes object positions (and robot init noise). " "Set to False for static initial state (e.g. fixed cube positions in Stack).", ) config_flags.DEFINE_config_file( "config", "base_configs/rl.py", "File path to the training hyperparameter configuration.", ) def evaluate( policy, env, task_txts, switch_to_vgen, encoder, video_model, subgoal_r3m_embs, subgoal_embs, scale_factors, train_step, device, buffer, num_episodes, dist_txt_path, chunk_len, action_execute_dim, epsilon, ): """Evaluate the policy and dump rollout videos to disk.""" policy.eval() stats = collections.defaultdict(list) success = 0 all_episodes_data = [] for num_episode in range(num_episodes): observation, _ = env.reset() for _ in range(10): observation, _, _, _, _ = env.step([0.0] * 6 + [-1.0]) continue done = False subgoal_idx = 1 cur_visual_state = observation # # Running video plan if switch_to_vgen: initial_frame = preprocess_for_reward_model(cur_visual_state) initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB) # (128, 128, 3) images = pred_video(video_model, initial_frame, task_txts) # (8, 3, 128, 128) images = images.unsqueeze(0).to(device) # pixel value range [0., 1.], (1, 8, 3, 128, 128) # subgoal_embs = buffer.model.infer(images, [task_txts] * 8).numpy().embs # Encode generated images with r3m subgoal_r3m_embs = encode_r3m_batch(images.squeeze(), encoder, device) # # Save images: shape (8, 3, 128, 128), values 0..255 # imgs = (images.squeeze().cpu().numpy()*255).astype('uint8') # ensure uint8 # imgs_hwc = np.transpose(imgs, (0, 2, 3, 1)) # (8, 128, 128, 3) # strip = np.concatenate(list(imgs_hwc), axis=1) # (128, 8*128, 3) # Image.fromarray(strip).save(f"episode_{num_episode}.png") # # Video plan done subgoal_emb, normalized_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs) visual_feature = preprocess_for_r3m(cur_visual_state, encoder, device) observation = np.concatenate((visual_feature, subgoal_r3m_embs[subgoal_idx])) #normalized_subgoal_emb info = {'episode_steps': 0} episode_data = [] while not done: action = policy.act(observation.astype(np.float32), sample=False) action = np.clip(action, -1, 1) action_chunk = action.reshape(chunk_len, -1) for act_idx in range(action_execute_dim): act = action_chunk[act_idx] next_observation, reward, terminated, truncated, info = env.step(act) next_visual_state = next_observation # ---- BEGIN progress measure between visual_state and next_visual_state. ---- cur_obs_image = preprocess_for_reward_model(cur_visual_state) # Sent to buffer. next_obs_image = preprocess_for_reward_model(next_visual_state) # Sent to buffer. cur_next_obs_img_pair = [buffer._pixel_to_tensor(obs_img) for obs_img in [cur_obs_image, next_obs_image]] cur_next_obs_img_pair = torch.cat(cur_next_obs_img_pair, dim=1) cur_next_obs_emb_pair = buffer.model.infer(cur_next_obs_img_pair, [task_txts] * 2).numpy().embs # TODO automate env name cur_next_obs_emb_pair = cur_next_obs_emb_pair.squeeze() image_reward = next_obs_image.copy() progress, d_t, d_tp1, hit = compute_progress_to_subgoal( emb=cur_next_obs_emb_pair, subgoal_emb=subgoal_emb.numpy(), scale_factor=scale_factors[subgoal_idx-1], segment_scale=1.0 / np.linalg.norm(subgoal_embs[subgoal_idx]-subgoal_embs[subgoal_idx-1], axis=-1), epsilon=epsilon, ) # Store progress and subgoal index episode_data.append((d_tp1, subgoal_idx)) if hit and subgoal_idx < len(subgoal_embs)-1: subgoal_idx = min(subgoal_idx + 1, len(subgoal_embs) - 1) # ---- END progress measure. ---- next_subgoal_emb, normalized_next_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs) next_visual_feature = preprocess_for_r3m(next_visual_state, encoder, device) next_observation = np.concatenate((next_visual_feature, subgoal_r3m_embs[subgoal_idx])) # normalized_next_subgoal_emb observation = next_observation cur_visual_state = next_visual_state subgoal_emb = next_subgoal_emb done = terminated or truncated #truncated # print(f"Episode {num_episode} reached {subgoal_idx}.") success += info["episode"]["success"] all_episodes_data.append(episode_data) for k, v in info["episode"].items(): stats[k].append(v) if "eval_score" in info: stats["eval_score"].append(info["eval_score"]) plot_distance_log(all_episodes_data, dist_txt_path) stats["success_rate"].append(success/num_episodes) for k, v in stats.items(): stats[k] = np.mean(v) return stats def write_dists_to_file(dists, dist_txt_path): filename = osp.join(dist_txt_path, "dists_log.txt") new_line = ",".join(map(str, dists)) # Load existing lines if the file exists if os.path.exists(filename): with open(filename, "r") as f: lines = f.read().splitlines() else: lines = [] # Append new line and keep only the last 20 lines.append(new_line) lines = lines[-20:] # Write back to the file with open(filename, "w") as f: f.write("\n".join(lines) + "\n") def plot_distance_log(all_episodes_data, file_path): """ Plots the progress for each episode in a separate subplot, with vertical lines to indicate subgoal changes. """ image_path = os.path.join(file_path, "reward.png") num_episodes = len(all_episodes_data) if num_episodes == 0: print("No episode data to plot.") return # Determine grid size for subplots cols = min(3, num_episodes) rows = (num_episodes + cols - 1) // cols fig, axes = plt.subplots(rows, cols, figsize=(5 * cols, 4 * rows), squeeze=False) # Flatten the axes array for easier iteration axes = axes.flatten() for i, episode_data in enumerate(all_episodes_data): ax = axes[i] # Unzip the data into separate lists for progress and subgoal_idx progress_values = [d[0] for d in episode_data] subgoal_indices = [d[1] for d in episode_data] # Plot the progress values ax.plot(progress_values, label="Progress") ax.set_title(f"Episode {i+1}") ax.set_xlabel("Step in Episode") ax.set_ylabel("Distance to Subgoal") ax.grid(True, linestyle='--', alpha=0.6) # Plot vertical lines at each subgoal change # A change occurs when the current subgoal index is different from the next one. change_points = [j for j in range(len(subgoal_indices) - 1) if subgoal_indices[j] != subgoal_indices[j+1]] for j in change_points: ax.axvline(x=j+1, color='r', linestyle=':', linewidth=2, label=f'Subgoal {subgoal_indices[j+1]}') # Add a legend only for the first subplot to avoid clutter if i == 0: handles, labels = ax.get_legend_handles_labels() by_label = dict(zip(labels, handles)) fig.legend(by_label.values(), by_label.keys(), loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=2) # Hide any unused subplots for i in range(num_episodes, len(axes)): fig.delaxes(axes[i]) plt.tight_layout(rect=[0, 0, 1, 0.95]) # Adjust layout to make space for the main title plt.suptitle("Episode Progress and Subgoal Changes", fontsize=16) plt.savefig(image_path, dpi=300) plt.close() ## Can move this utility to utils.py. def preprocess_for_reward_model(visual_obs): center_crop = A.CenterCrop(height=84, width=84, p=1.0) image = np.array(visual_obs) # image_reward = visual_obs#cv2.resize(visual_obs, (360, 360), interpolation=cv2.INTER_AREA) # crop_size = 150 # h, w, _ = image_reward.shape # image_cropped = image_reward[ # (h-crop_size)//2:(h+crop_size)//2, # (w-crop_size)//2:(w+crop_size)//2 # ] # image_cropped = center_crop(image=image)["image"] image_final = cv2.resize(image, (84, 84), interpolation=cv2.INTER_AREA) image_final = cv2.cvtColor(image_final, cv2.COLOR_BGR2RGB) # cv2.imwrite("processed_for_reward.png", image_final) return image_final # ## Can move this utility to utils.py. # def preprocess_for_video_model(visual_obs): # visual_obs = cv2.resize(visual_obs, (320, 240), interpolation=cv2.INTER_AREA) # center_crop = A.CenterCrop(height=128, width=128, p=1.0) # image = np.array(visual_obs) # image_cropped = center_crop(image=image)["image"] # image_final = cv2.resize(image_cropped, (128, 128), interpolation=cv2.INTER_AREA) # return image_final ## Can move this utility to utils.py. @torch.no_grad() def preprocess_for_r3m(image, model, device): """Resize image to 224x224 and convert to R3M input tensor.""" image = np.array(image) # (84,84,3) transform = T.Compose([ T.ToPILImage(), T.Resize(224), T.ToTensor() ]) tensor_image = transform(image) # # Convert back to PIL for saving # image_to_save = T.ToPILImage()(tensor_image) # image_to_save.save('processed_for_observation.png') tensor_image = tensor_image.unsqueeze(0).to(device) r3m_feat = model(tensor_image * 255.0) n_r3m_feat = r3m_feat.squeeze().cpu().numpy() #n_r3m_feat return n_r3m_feat @torch.no_grad() def encode_r3m_batch(images, model, device): """ Encode a batch of images with R3M. Args: images: torch.Tensor or np.ndarray of shape (N, 3, 128, 128), values in [0, 1]. model: R3M model (expects inputs scaled to [0, 255]). device: torch.device to run on. Returns: np.ndarray of shape (N, D) with R3M features. """ if isinstance(images, np.ndarray): images = torch.from_numpy(images) assert images.ndim == 4 and images.shape[1] == 3 and images.shape[2:] == (128, 128), \ f"Expected (N, 3, 128, 128), got {tuple(images.shape)}" images = images.to(device) try: images_224 = F.interpolate(images, size=(224, 224), mode="bilinear", align_corners=False, antialias=True) except TypeError: images_224 = F.interpolate(images, size=(224, 224), mode="bilinear", align_corners=False) feats = model(images_224 * 255.0) # (N, D) return feats.detach().cpu().numpy() def retrieve_goal_with_idx( idx, subgoals, ): assert idx <= len(subgoals) - 1 subgoal = torch.tensor(subgoals[idx]) subgoal_normalized = subgoal / (subgoal.norm(p=2) + 1e-8) return subgoal, subgoal_normalized def encode_reward_image(self, image_reward, task="assembly", squeeze=True): """ image_reward: HxWxC uint8 NumPy array (or anything _pixel_to_tensor supports) returns: (D,) if squeeze else (1,1,D) """ x = self._pixel_to_tensor(image_reward) # -> (1,1,C,H,W) on self.device with torch.no_grad(): out = self.model.infer(x, [task]).numpy().embs # typically (1,1,D) return out.squeeze((0,1)) if squeeze else out def compute_progress_to_subgoal( emb, # shape (2, D): [curr_feat, next_feat] subgoal_emb, # shape (D,) or (1, D) scale_factor, segment_scale, # e.g., 1.0 / ||g_i - g_{i-1}|| if you use segment normalization epsilon # optional: threshold to mark a subgoal hit ): g = subgoal_emb.reshape(1, -1) curr, nxt = emb[0], emb[1] d_t = np.linalg.norm(curr - g, axis=-1) # shape (1,) d_tp1 = np.linalg.norm(nxt - g , axis=-1) # shape (1,) # Optional segment normalization: multiply by 1/||g_i - g_{i-1}|| if segment_scale is not None: d_t = d_t * segment_scale d_tp1 = d_tp1 * segment_scale progress = d_t - d_tp1 # positive means you moved closer to g_i # Optional subgoal hit flag hit = None if epsilon is not None: hit = (d_tp1 < epsilon) # If you're going to use this as a numeric reward, you can detach: # progress = progress.detach() return progress, d_t, d_tp1, hit # @torch.no_grad() # def encode_subgoals_from_paths( # paths, # task_txt, # reward_model, # device, # preprocessor_func, # pixel_to_tensor_func # ): # """Loads images from paths, preprocesses, and encodes them into subgoal embeddings.""" # image_tensors = [] # for path in paths: # # Load raw image from path # raw_image = np.array(Image.open(path).convert('RGB')) # # Apply reward model preprocessing (e.g., cropping/resizing) # processed_img = preprocessor_func(raw_image) # # Convert to model input tensor format: (1, 1, C, H, W) on device # image_tensors.append(pixel_to_tensor_func(processed_img)) # # Concatenate all frame tensors for batched inference (1, N, C, H, W) # images_batch = torch.cat(image_tensors, dim=1) # # Infer embeddings: shape (N, D) # out = reward_model.infer(images_batch, [task_txt] * len(paths)) # subgoal_embs = out.numpy().embs # Shape: (num_keyframes, embedding_dim) # return subgoal_embs @torch.no_grad() def encode_goals_with_r3m( paths, # The list of image file paths r3m_model, device, ): r3m_feature_tensors = [] # R3M-specific preprocessing components (hardcoded from preprocess_for_r3m) r3m_transform = T.Compose([ T.ToPILImage(), T.Resize(224), T.ToTensor() ]) for path in paths: # 1. Load raw image from path raw_image = np.array(Image.open(path).convert('RGB')) # 2. Apply R3M-specific transforms (Tensor operations) tensor_image = r3m_transform(raw_image) # 3. Prepare for batching: (1, C, H, W) tensor_image = tensor_image.unsqueeze(0).to(device) r3m_feature_tensors.append(tensor_image) # Concatenate all frame tensors for batched inference (N, C, H, W) # R3M is an image encoder, so we concatenate along the batch dimension (dim=0) images_batch = torch.cat(r3m_feature_tensors, dim=0) # R3M inference: R3M expects inputs scaled to 0-255 r3m_feat = r3m_model(images_batch * 255.0) # Convert batch of features to final NumPy array (N, D) subgoal_embs_with_r3m = r3m_feat.cpu().numpy() return subgoal_embs_with_r3m @experiment.pdb_fallback def main(_): validate_config(FLAGS.config, mode='rl') config = FLAGS.config exp_dir = osp.join( config.save_dir, FLAGS.experiment_name, str(FLAGS.seed), ) utils.setup_experiment(exp_dir, config, FLAGS.resume) # Setup device. if torch.cuda.is_available(): device = torch.device(FLAGS.device) else: logging.info("No GPU device found. Falling back to CPU.") device = torch.device('cpu') logging.info("Using device: %s", device) # Setup RNG seeds. if FLAGS.seed is not None: logging.info("RL experiment seed: %d", FLAGS.seed) experiment.seed_rngs(FLAGS.seed) experiment.set_cudnn(config.cudnn_deterministic, config.cudnn_benchmark) else: logging.info("No RNG seed has been set for this RL experiment.") # Load train and eval environments. env = utils.make_env( env_name=FLAGS.env_name, seed=FLAGS.seed, save_dir = None, add_episode_monitor = True, action_repeat = config.action_repeat, frame_stack = config.frame_stack, randomize_initial_state=FLAGS.randomize_initial_state, ) eval_env = utils.make_env( env_name=FLAGS.env_name, seed=FLAGS.seed + 10_000, save_dir = osp.join(exp_dir, "video", "eval"), add_episode_monitor = True, action_repeat=config.action_repeat, frame_stack=config.frame_stack, randomize_initial_state=FLAGS.randomize_initial_state, ) # Action chunk chunk_len = 1 action_execute_dim = 1 # Load r3m for visual observations feature extraction. Update obs dim to match. r3m = load_r3m("resnet50") r3m.eval() for p in r3m.parameters(): p.requires_grad = False r3m.to(device) video_model = get_video_model(ckpts_dir='./video_model_ckpts/mw', milestone=36) # dinov2_model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14') # dinov2_model = dinov2_model.to('cuda' if torch.cuda.is_available() else 'cpu') # dinov2_model.eval() # Set observation and action space values. config.sac.obs_dim = 2048+2048 #128 #+4*2 #env.observation_space.shape[0] config.sac.action_dim = env.action_space.shape[0] config.sac.action_range = [ float(env.action_space.low.min()), float(env.action_space.high.max()), ] config.sac.chunk_len = chunk_len camera = "corner2" task_txts = FLAGS.env_name # Resave the config since the dynamic values have been updated at this point # and make it immutable for safety :) utils.dump_config(exp_dir, config) config = config_dict.FrozenConfigDict(config) # Create policy policy = agent.SAC(device, config.sac) # Create buffer and embs of subgoals buffer, subgoal_embs, scale_factors = utils.make_buffer(env, device, config) print(f"---- {len(subgoal_embs)} subgoal frames, {len(scale_factors)} scale factors. ----") avg_subgoal_embs = subgoal_embs.copy() # Create demo data for sampling subgoals goal_sequence_set = RoboSuiteDataset( sample_per_seq=config.sample_per_seq, path="./datasets/mimicgen", task_txt=task_txts, target_size=(84, 84), randomcrop=False, split='train', ) # Create checkpoint manager checkpoint_dir = osp.join(exp_dir, "checkpoints") checkpoint_manager = CheckpointManager( checkpoint_dir, policy=policy, **policy.optim_dict(), ) logger = Logger(osp.join(exp_dir, "tb"), FLAGS.resume) # Training, evaluation, and checkpointing. try: i = -1 start = checkpoint_manager.restore_or_initialize() switch_to_vgen, switch_to_random_seq = False, False observation, _ = env.reset() for _ in range(10): observation, _, _, _, _ = env.step([0.0] * 6 + [-1.0]) continue done = False subgoal_idx = 1 print(observation.shape) cur_visual_state = observation #(84, 84, 3) # print(cur_visual_state.shape) # initial_frame = preprocess_for_reward_model(cur_visual_state) # initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB) # (128, 128, 3) # images = pred_video(video_model, initial_frame, task_txts) # (8, 3, 128, 128) # images = images.unsqueeze(0).to(device) # pixel value range [0., 1.], (1, 8, 3, 128, 128) # # Save images: shape (8, 3, 128, 128), values 0..255 # imgs = (images.squeeze().cpu().numpy()*255).astype('uint8') # ensure uint8 # imgs_hwc = np.transpose(imgs, (0, 2, 3, 1)) # (8, 128, 128, 3) # strip = np.concatenate(list(imgs_hwc), axis=1) # (128, 8*128, 3) # Image.fromarray(strip).save("strip.png") # assert False # # Encode generated video into subgoal features # video_subgoal_features = buffer.model.infer(images, [task_txts] * len(subgoal_embs)).numpy().embs # print(video_subgoal_features.shape, video_subgoal_features.min(1), video_subgoal_features.max(1)) # print(subgoal_embs.shape, subgoal_embs.min(1), subgoal_embs.max(1)) # assert False subgoal_paths, task_txts = goal_sequence_set.sample_goal_sequence_paths(num_keyframes=config.sample_per_seq) # subgoal_embs = encode_subgoals_from_paths( # subgoal_paths, # task_txts, # buffer.model, # device, # preprocess_for_reward_model, # buffer._pixel_to_tensor # Assumes buffer has the _to_tensor utility # ) subgoal_r3m_embs = encode_goals_with_r3m( subgoal_paths, r3m, device, ) visual_feature = preprocess_for_r3m(cur_visual_state, r3m, device) subgoal_emb, normalized_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs) observation = np.concatenate((visual_feature, subgoal_r3m_embs[subgoal_idx])) # normalized_subgoal_emb # print(subgoal_emb.max(), subgoal_emb.min(), normalized_subgoal_emb.max(), normalized_subgoal_emb.min()) for i in tqdm(range(start, config.num_train_steps // action_execute_dim), initial=start): # Random sample / policy inference. if i < config.num_seed_steps // action_execute_dim: action = np.array([env.action_space.sample() for _ in range(chunk_len)]) else: policy.eval() action = policy.act(observation.astype(np.float32), sample=True) # Action chunk post-processing action_chunk = action.reshape(chunk_len, -1) action = action.flatten() # Format for replay buffer. for act_idx in range(action_execute_dim): act = action_chunk[act_idx] next_observation, reward, terminated, truncated, info = env.step(act) done = terminated or truncated #truncated # # Read next observations next_visual_state = next_observation # ---- BEGIN progress measure between visual_state and next_visual_state. ---- cur_obs_image = preprocess_for_reward_model(cur_visual_state) # Sent to buffer. next_obs_image = preprocess_for_reward_model(next_visual_state) # Sent to buffer. cur_next_obs_img_pair = [buffer._pixel_to_tensor(obs_img) for obs_img in [cur_obs_image, next_obs_image]] cur_next_obs_img_pair = torch.cat(cur_next_obs_img_pair, dim=1) # print("Image pair:", cur_next_obs_img_pair.min(), cur_next_obs_img_pair.max(), cur_next_obs_img_pair.shape) cur_next_obs_emb_pair = buffer.model.infer(cur_next_obs_img_pair, [task_txts] * 2).numpy().embs # TODO automate env name cur_next_obs_emb_pair = cur_next_obs_emb_pair.squeeze() image_reward = next_obs_image.copy() progress, d_t, d_tp1, hit = compute_progress_to_subgoal( emb=cur_next_obs_emb_pair, subgoal_emb=subgoal_emb.numpy(), scale_factor=scale_factors[subgoal_idx-1], segment_scale=1.0 / np.linalg.norm(subgoal_embs[subgoal_idx]-subgoal_embs[subgoal_idx-1], axis=-1), epsilon=config.epsilon, ) # ---- END progress measure. ---- reward_sum = 0.0 reward_sum += -0.1 * d_tp1 #1.0 * progress - 0.5 * if hit and subgoal_idx < len(subgoal_embs)-1: reward_sum += 7.5 #/10 #* subgoal_idx subgoal_idx = min(subgoal_idx + 1, len(subgoal_embs) - 1) # Sparse termination reward for action chunk. if done and hit and info["episode"]["success"] == True and subgoal_idx >= len(subgoal_embs) - 2: reward_sum += 15 if done and info["episode"]["success"] == True and subgoal_idx < len(subgoal_embs) - 2: reward_sum -= 100 next_visual_feature = preprocess_for_r3m(next_visual_state, r3m, device) next_subgoal_emb, normalized_next_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs) next_observation = np.concatenate((next_visual_feature, subgoal_r3m_embs[subgoal_idx]))# normalized_next_subgoal_emb # Add to Replay Buffer if not done or 'TimeLimit.truncated' in info: mask = 1.0 else: mask = 0.0 if not config.reward_wrapper.pretrained_path: buffer.insert(observation, action, reward, next_observation, mask) else: buffer.insert( observation, action, reward_sum,#reward, next_observation, mask, image_reward, subgoal_emb, ) observation = next_observation cur_visual_state = next_visual_state subgoal_emb = next_subgoal_emb if done: # Check episode just ended. # if subgoal_idx > 4: print(subgoal_idx) observation, _ = env.reset() for _ in range(10): observation, _, _, _, _ = env.step([0.0] * 6 + [-1.0]) continue done = False subgoal_idx = 1 cur_visual_state = observation subgoal_paths, task_txts = goal_sequence_set.sample_goal_sequence_paths(num_keyframes=config.sample_per_seq) # subgoal_embs = encode_subgoals_from_paths( # subgoal_paths, # task_txts, # buffer.model, # device, # preprocess_for_reward_model, # buffer._pixel_to_tensor # ) subgoal_r3m_embs = encode_goals_with_r3m( subgoal_paths, r3m, device, ) # print("Demo images r3m feature:", subgoal_r3m_embs.shape, subgoal_r3m_embs.min(), subgoal_r3m_embs.max()) # Finetuning on video generated goals if switch_to_vgen: initial_frame = preprocess_for_reward_model(cur_visual_state) initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB) # (128, 128, 3) images = pred_video(video_model, initial_frame, task_txts) # (8, 3, 128, 128) images = images.unsqueeze(0).to(device) # pixel value range [0., 1.], (1, 8, 3, 128, 128) # subgoal_embs = buffer.model.infer(images, [task_txts] * 8).numpy().embs # Encode generated images with r3m subgoal_r3m_embs = encode_r3m_batch(images.squeeze(), r3m, device) # print("Vgen images r3m feature:", subgoal_r3m_embs.shape, subgoal_r3m_embs.min(), subgoal_r3m_embs.max()) # imgs = (images.squeeze().cpu().numpy()*255).astype('uint8') # imgs_hwc = np.transpose(imgs, (0, 2, 3, 1)) # (8, 128, 128, 3) # strip = np.concatenate(list(imgs_hwc), axis=1) # (128, 8*128, 3) # Image.fromarray(strip).save("strip.png") visual_feature = preprocess_for_r3m(cur_visual_state, r3m, device) subgoal_emb, normalized_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs) observation = np.concatenate((visual_feature, subgoal_r3m_embs[subgoal_idx])) #normalized_subgoal_emb for k, v in info["episode"].items(): logger.log_scalar( v, info["total"]["timesteps"], k, "training" ) if i >= config.num_seed_steps // action_execute_dim: if len(buffer) >= config.sac.batch_size: policy.train() train_info = policy.update(buffer, i) else: train_info = {} if (i + 1) % (config.log_frequency // action_execute_dim) == 0: if train_info: for k, v in train_info.items(): logger.log_scalar( v, info["total"]["timesteps"], k, "training" ) logger.flush() if (i + 1) % (config.eval_frequency) == 0: eval_stats = evaluate( policy, eval_env, task_txts, switch_to_vgen, r3m, video_model, subgoal_r3m_embs, subgoal_embs, scale_factors, i, device, buffer, config.num_eval_episodes, exp_dir, chunk_len=chunk_len, action_execute_dim=action_execute_dim, epsilon=config.epsilon, ) for k, v in eval_stats.items(): logger.log_scalar( v, info["total"]["timesteps"], f"average_{k}s", "evaluation", ) logger.flush() # Order of update matters. if (not switch_to_vgen) and eval_stats["success_rate"] > config.threshold_for_vgen: switch_to_vgen = True if (i + 1) % config.checkpoint_frequency == 0: checkpoint_manager.save(i) except KeyboardInterrupt: env.close() del env print("Caught keyboard interrupt. Saving before quitting.") finally: env.close() del env checkpoint_manager.save(i) logger.close() if __name__ == "__main__": app.run(main)