| """ |
| 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 |
|
|
| |
| if switch_to_vgen: |
| initial_frame = preprocess_for_reward_model(cur_visual_state) |
| initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB) |
| images = pred_video(video_model, initial_frame, task_txts) |
| images = images.unsqueeze(0).to(device) |
| |
|
|
| |
| subgoal_r3m_embs = encode_r3m_batch(images.squeeze(), encoder, device) |
|
|
| |
| |
| |
| |
| |
| |
|
|
| 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])) |
| 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 |
| |
| cur_obs_image = preprocess_for_reward_model(cur_visual_state) |
| next_obs_image = preprocess_for_reward_model(next_visual_state) |
| 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 |
| 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, |
| ) |
| |
| 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) |
|
|
| |
| 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])) |
| |
| observation = next_observation |
| cur_visual_state = next_visual_state |
| subgoal_emb = next_subgoal_emb |
| |
| done = terminated or 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)) |
| |
| |
| if os.path.exists(filename): |
| with open(filename, "r") as f: |
| lines = f.read().splitlines() |
| else: |
| lines = [] |
|
|
| |
| lines.append(new_line) |
| lines = lines[-20:] |
|
|
| |
| 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 |
|
|
| |
| cols = min(3, num_episodes) |
| rows = (num_episodes + cols - 1) // cols |
| fig, axes = plt.subplots(rows, cols, figsize=(5 * cols, 4 * rows), squeeze=False) |
|
|
| |
| axes = axes.flatten() |
|
|
| for i, episode_data in enumerate(all_episodes_data): |
| ax = axes[i] |
| |
| |
| progress_values = [d[0] for d in episode_data] |
| subgoal_indices = [d[1] for d in episode_data] |
| |
| |
| 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) |
|
|
| |
| |
| 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]}') |
|
|
| |
| 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) |
|
|
| |
| for i in range(num_episodes, len(axes)): |
| fig.delaxes(axes[i]) |
|
|
| plt.tight_layout(rect=[0, 0, 1, 0.95]) |
| plt.suptitle("Episode Progress and Subgoal Changes", fontsize=16) |
| plt.savefig(image_path, dpi=300) |
| plt.close() |
|
|
| |
| def preprocess_for_reward_model(visual_obs): |
|
|
| center_crop = A.CenterCrop(height=84, width=84, p=1.0) |
|
|
| image = np.array(visual_obs) |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| image_final = cv2.resize(image, (84, 84), interpolation=cv2.INTER_AREA) |
| |
| image_final = cv2.cvtColor(image_final, cv2.COLOR_BGR2RGB) |
| |
|
|
| return image_final |
|
|
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
|
|
| |
|
|
| |
| @torch.no_grad() |
| def preprocess_for_r3m(image, model, device): |
| """Resize image to 224x224 and convert to R3M input tensor.""" |
|
|
| image = np.array(image) |
|
|
| transform = T.Compose([ |
| T.ToPILImage(), |
| T.Resize(224), |
| T.ToTensor() |
| ]) |
| tensor_image = transform(image) |
| |
| |
| |
| |
|
|
| tensor_image = tensor_image.unsqueeze(0).to(device) |
| r3m_feat = model(tensor_image * 255.0) |
| n_r3m_feat = r3m_feat.squeeze().cpu().numpy() |
| 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) |
| 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) |
| with torch.no_grad(): |
| out = self.model.infer(x, [task]).numpy().embs |
| return out.squeeze((0,1)) if squeeze else out |
|
|
| def compute_progress_to_subgoal( |
| emb, |
| subgoal_emb, |
| scale_factor, |
| segment_scale, |
| epsilon |
| ): |
| g = subgoal_emb.reshape(1, -1) |
| curr, nxt = emb[0], emb[1] |
|
|
| d_t = np.linalg.norm(curr - g, axis=-1) |
| d_tp1 = np.linalg.norm(nxt - g , axis=-1) |
|
|
| |
| if segment_scale is not None: |
| d_t = d_t * segment_scale |
| d_tp1 = d_tp1 * segment_scale |
| progress = d_t - d_tp1 |
|
|
| |
| hit = None |
| if epsilon is not None: |
| hit = (d_tp1 < epsilon) |
|
|
| |
| |
|
|
| return progress, d_t, d_tp1, hit |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
| |
|
|
| |
|
|
| @torch.no_grad() |
| def encode_goals_with_r3m( |
| paths, |
| r3m_model, |
| device, |
| ): |
|
|
| r3m_feature_tensors = [] |
| |
| |
| r3m_transform = T.Compose([ |
| T.ToPILImage(), |
| T.Resize(224), |
| T.ToTensor() |
| ]) |
|
|
| for path in paths: |
| |
| raw_image = np.array(Image.open(path).convert('RGB')) |
| |
| |
| tensor_image = r3m_transform(raw_image) |
| |
| |
| tensor_image = tensor_image.unsqueeze(0).to(device) |
| |
| r3m_feature_tensors.append(tensor_image) |
|
|
| |
| |
| images_batch = torch.cat(r3m_feature_tensors, dim=0) |
|
|
| |
| r3m_feat = r3m_model(images_batch * 255.0) |
| |
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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.") |
|
|
| |
| 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, |
| ) |
|
|
| |
| chunk_len = 1 |
| action_execute_dim = 1 |
|
|
| |
| 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) |
|
|
| |
| |
| |
|
|
| |
| config.sac.obs_dim = 2048+2048 |
| 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 |
|
|
| |
| |
| utils.dump_config(exp_dir, config) |
| config = config_dict.FrozenConfigDict(config) |
|
|
| |
| policy = agent.SAC(device, config.sac) |
| |
| |
| 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() |
|
|
| |
| 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', |
| ) |
|
|
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| subgoal_paths, task_txts = goal_sequence_set.sample_goal_sequence_paths(num_keyframes=config.sample_per_seq) |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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])) |
| |
|
|
| for i in tqdm(range(start, config.num_train_steps // action_execute_dim), initial=start): |
| |
| 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 = action.reshape(chunk_len, -1) |
| action = action.flatten() |
|
|
| 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 |
| |
| |
| next_visual_state = next_observation |
|
|
| |
| cur_obs_image = preprocess_for_reward_model(cur_visual_state) |
| next_obs_image = preprocess_for_reward_model(next_visual_state) |
| 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 |
| 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, |
| ) |
| |
| reward_sum = 0.0 |
| reward_sum += -0.1 * d_tp1 |
| if hit and subgoal_idx < len(subgoal_embs)-1: |
| reward_sum += 7.5 |
| subgoal_idx = min(subgoal_idx + 1, len(subgoal_embs) - 1) |
|
|
| |
| 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])) |
|
|
| |
| |
| 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, |
| next_observation, |
| mask, |
| image_reward, |
| subgoal_emb, |
| ) |
| observation = next_observation |
| cur_visual_state = next_visual_state |
| subgoal_emb = next_subgoal_emb |
| |
|
|
| if done: |
|
|
| |
| |
| 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_r3m_embs = encode_goals_with_r3m( |
| subgoal_paths, |
| r3m, |
| device, |
| ) |
|
|
| |
|
|
| |
| if switch_to_vgen: |
| initial_frame = preprocess_for_reward_model(cur_visual_state) |
| initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB) |
| images = pred_video(video_model, initial_frame, task_txts) |
| images = images.unsqueeze(0).to(device) |
| |
|
|
| |
| subgoal_r3m_embs = encode_r3m_batch(images.squeeze(), 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])) |
|
|
| 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() |
|
|
| |
| 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) |