diff --git a/code/policy_models/VPP_policy.py b/code/policy_models/VPP_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2f20a3bec397cc36917c2497176e502c742b1e08 --- /dev/null +++ b/code/policy_models/VPP_policy.py @@ -0,0 +1,688 @@ +import logging +from typing import Dict, Optional, Tuple +from functools import partial +from torch import einsum, nn +from einops import rearrange, repeat +from omegaconf import DictConfig, OmegaConf +import pytorch_lightning as pl +from pytorch_lightning.utilities import rank_zero_only +import einops +from policy_models.edm_diffusion.score_wrappers import GCDenoiser + +from policy_models.module.clip_lang_encoder import LangClip +from policy_models.edm_diffusion.gc_sampling import * +from policy_models.utils.lr_schedulers.tri_stage_scheduler import TriStageLRScheduler +from policy_models.module.Video_Former import Video_Former_2D,Video_Former_3D +from diffusers import StableVideoDiffusionPipeline +from policy_models.module.diffusion_extract import Diffusion_feature_extractor +from transformers import AutoTokenizer, CLIPTextModelWithProjection + + +logger = logging.getLogger(__name__) + +def load_primary_models(pretrained_model_path, eval=False): + if eval: + pipeline = StableVideoDiffusionPipeline.from_pretrained(pretrained_model_path, torch_dtype=torch.float16) + else: + pipeline = StableVideoDiffusionPipeline.from_pretrained(pretrained_model_path) + return pipeline, None, pipeline.feature_extractor, pipeline.scheduler, pipeline.video_processor, \ + pipeline.image_encoder, pipeline.vae, pipeline.unet + + +class VPP_Policy(pl.LightningModule): + """ + The lightning module used for training. + """ + + def __init__( + self, + optimizer: DictConfig, + lr_scheduler: DictConfig, + latent_dim: int = 512, + multistep: int = 10, + sampler_type: str = 'ddim', + num_sampling_steps: int = 10, + sigma_data: float = 0.5, + sigma_min: float = 0.001, + sigma_max: float = 80, + noise_scheduler: str = 'exponential', + sigma_sample_density_type: str = 'loglogistic', + use_lr_scheduler: bool = True, + act_window_size: int = 10, + use_text_not_embedding: bool = False, + seed: int = 42, + pretrained_model_path: str = '/cephfs/shared/gyj/ckpt/svd_pre/checkpoint-100000', + text_encoder_path: str = '/home/disk2/gyj/hyc_ckpt/llm/clip-vit-base-patch32', + use_position_encoding: bool = True, + Former_depth: int = 3, + Former_heads: int = 8, + Former_dim_head: int = 64, + Former_num_time_embeds: int = 1, + num_latents: int = 3, + use_Former: str = '3d', + timestep: int = 20, + max_length: int = 20, + extract_layer_idx: int = 1, + use_all_layer: bool = False, + obs_seq_len: int = 1, + action_dim: int = 7, + action_seq_len: int = 10, + ): + super(VPP_Policy, self).__init__() + self.latent_dim = latent_dim + self.use_all_layer = use_all_layer + self.use_position_encoding = use_position_encoding + + self.act_window_size = act_window_size + self.action_dim = action_dim + + self.timestep = timestep + self.extract_layer_idx = extract_layer_idx + self.use_Former = use_Former + self.Former_num_time_embeds = Former_num_time_embeds + self.max_length = max_length + + condition_dim_list = [1280,1280,1280,640] + sum_dim = 0 + for i in range(extract_layer_idx+1): + sum_dim = sum_dim + condition_dim_list[i+1] + condition_dim = condition_dim_list[extract_layer_idx+1] if not self.use_all_layer else sum_dim + + if use_Former=='3d': + self.Video_Former = Video_Former_3D( + dim=latent_dim, + depth=Former_depth, + dim_head=Former_dim_head, + heads=Former_heads, + num_time_embeds=Former_num_time_embeds, + num_latents=num_latents, + condition_dim=condition_dim, + use_temporal=True, + ) + elif use_Former == '2d': + self.Video_Former = Video_Former_2D( + dim=latent_dim, + depth=Former_depth, + dim_head=Former_dim_head, + heads=Former_heads, + num_time_embeds=Former_num_time_embeds, + num_latents=num_latents, + condition_dim=condition_dim, + ) + else: + self.Video_Former = nn.Linear(condition_dim,latent_dim) + + print('use_Former:', self.use_Former) + print('use_all_layer',self.use_all_layer) + + self.seed = seed + self.use_lr_scheduler = use_lr_scheduler + # goal encoders + self.language_goal = LangClip(model_name='ViT-B/32').to(self.device) + + pipeline, tokenizer, feature_extractor, train_scheduler, vae_processor, text_encoder, vae, unet = load_primary_models( + pretrained_model_path , eval = True) + + #text_encoder = CLIPTextModelWithProjection.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32") + #tokenizer = AutoTokenizer.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32", use_fast=False) + text_encoder = CLIPTextModelWithProjection.from_pretrained(text_encoder_path) + tokenizer = AutoTokenizer.from_pretrained(text_encoder_path, use_fast=False) + + text_encoder = text_encoder.to(self.device).eval() + + for param in pipeline.image_encoder.parameters(): + param.requires_grad = False + for param in text_encoder.parameters(): + param.requires_grad = False + + for param in pipeline.vae.parameters(): + param.requires_grad = False + for param in pipeline.unet.parameters(): + param.requires_grad = False + + pipeline = pipeline.to(self.device) + pipeline.unet.eval() + + self.TVP_encoder = Diffusion_feature_extractor(pipeline=pipeline, + tokenizer=tokenizer, + text_encoder=text_encoder, + position_encoding = self.use_position_encoding) + self.TVP_encoder = self.TVP_encoder.to(self.device) + # policy network + self.model = GCDenoiser(action_dim = action_dim, + obs_dim=latent_dim, + goal_dim=512, + num_tokens=num_latents, + goal_window_size = 1, + obs_seq_len = obs_seq_len, + act_seq_len = action_seq_len, + device=self.device, + sigma_data=0.5).to(self.device) + + self.optimizer_config = optimizer + self.lr_scheduler = lr_scheduler + self.save_hyperparameters() + # diffusion stuff + self.sampler_type = sampler_type + self.num_sampling_steps = num_sampling_steps + self.noise_scheduler = noise_scheduler + self.sigma_data = sigma_data + self.sigma_min = sigma_min + self.sigma_max = sigma_max + self.sigma_sample_density_type = sigma_sample_density_type + # for inference + self.rollout_step_counter = 0 + self.multistep = multistep + self.latent_goal = None + self.plan = None + self.use_text_not_embedding = use_text_not_embedding + # print_model_parameters(self.perceptual_encoder.perceiver_resampler) + # for clip loss ground truth plot + self.ema_callback_idx = None + + for param in self.model.inner_model.proprio_emb.parameters(): + param.requires_grad = False + for param in self.model.inner_model.goal_emb.parameters(): + param.requires_grad = False + self.model.inner_model.pos_emb.requires_grad = False + + def process_device(self): + self.TVP_encoder.pipeline = self.TVP_encoder.pipeline.to(self.device) + self.TVP_encoder.text_encoder = self.TVP_encoder.text_encoder.to(self.device) + + def configure_optimizers(self): + """ + Initialize optimizers and learning rate schedulers based on model configuration. + """ + # Configuration for models using transformer weight decay + '''optim_groups = self.action_decoder.model.inner_model.get_optim_groups( + weight_decay=self.optimizer_config.transformer_weight_decay + )''' + optim_groups = [ + {"params": self.model.inner_model.parameters(), + "weight_decay": self.optimizer_config.transformer_weight_decay}, + {"params": self.Video_Former.parameters(), "weight_decay": self.optimizer_config.transformer_weight_decay}, + ] + + + optimizer = torch.optim.AdamW(optim_groups, lr=self.optimizer_config.learning_rate, + betas=self.optimizer_config.betas) + + # Optionally initialize the scheduler + if self.use_lr_scheduler: + lr_configs = OmegaConf.create(self.lr_scheduler) + scheduler = TriStageLRScheduler(optimizer, lr_configs) + lr_scheduler = { + "scheduler": scheduler, + "interval": 'step', + "frequency": 1, + } + return {"optimizer": optimizer, "lr_scheduler": lr_scheduler} + else: + return optimizer + + def on_before_zero_grad(self, optimizer=None): + total_grad_norm = 0.0 + total_param_norm = 0.0 + for p in self.model.parameters(): + if p.grad is not None: + total_grad_norm += p.grad.norm().item() ** 2 + total_param_norm += p.norm().item() ** 2 + total_grad_norm = total_grad_norm ** 0.5 + total_param_norm = total_param_norm ** 0.5 + + self.log("train/grad_norm", total_grad_norm, on_step=True, on_epoch=False, sync_dist=True) + self.log("train/param_norm", total_param_norm, on_step=True, on_epoch=False, sync_dist=True) + + + def training_step(self, dataset_batch: Dict[str, Dict],) -> torch.Tensor: # type: ignore + """ + Compute and return the training loss for the MDT Agent. + The training loss consists of the score matching loss of the diffusion model + and the contrastive loss of the CLIP model for the multimodal encoder. + + Args: + batch: Dictionary containing the batch data for each modality. + batch_idx: Index of the batch. used for compatibility with pytorch lightning. + dataloader_idx: Index of the dataloader. used for compatibility with pytorch lightning. + + Returns: + loss tensor + """ + total_loss, action_loss = ( + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + ) + + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + act_loss, sigmas, noise = self.diffusion_loss( + predictive_feature, + latent_goal, + dataset_batch["actions"], + ) + + action_loss += act_loss + total_loss += act_loss + + total_bs = dataset_batch["actions"].shape[0] + + self._log_training_metrics(action_loss, total_loss, total_bs) + return total_loss + + @torch.no_grad() + def validation_step(self, dataset_batch: Dict[str, Dict]) -> Dict[ + str, torch.Tensor]: # type: ignore + """ + Compute and log the validation losses and additional metrics. + During the validation step, the diffusion model predicts the next action sequence given the current state + + Args: + batch: Dictionary containing the batch data for each modality. + batch_idx: Index of the batch. used for compatibility with pytorch lightning. + dataloader_idx: Index of the dataloader. used for compatibility with pytorch lightning. + + Returns: + Dictionary containing the sampled plans of plan recognition and plan proposal module, as well as the + episode indices. + """ + output = {} + val_total_act_loss_pp = torch.tensor(0.0).to(self.device) + # Compute the required embeddings + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + # predict the next action sequence + action_pred = self.denoise_actions( + torch.zeros_like(latent_goal).to(latent_goal.device), + predictive_feature, + latent_goal, + inference=True, + ) + dataset_batch["actions"] = dataset_batch["actions"].to(action_pred.device) + # compute the mse action loss + pred_loss = torch.nn.functional.mse_loss(action_pred, dataset_batch["actions"]) + val_total_act_loss_pp += pred_loss + + output[f"idx:"] = dataset_batch["idx"] + output["validation_loss"] = val_total_act_loss_pp + return output + + def extract_predictive_feature(self, dataset_batch): + """ + Compute the required embeddings for the visual ones and the latent goal. + """ + # 1. extract the revelant visual observations + rgb_static = dataset_batch["rgb_obs"]['rgb_static'].to(self.device) + rgb_gripper = dataset_batch["rgb_obs"]['rgb_gripper'].to(self.device) + # 3. we compute the language goal if the language modality is in the scope + modality = "lang" + if self.use_text_not_embedding: + latent_goal = self.language_goal(dataset_batch["lang_text"]).to(rgb_static.dtype) + else: + latent_goal = self.language_goal(dataset_batch["lang"]).to(rgb_static.dtype) + + language = dataset_batch["lang_text"] + + num_frames = self.Former_num_time_embeds + rgb_static = rgb_static.to(self.device) + rgb_gripper = rgb_gripper.to(self.device) + batch = rgb_static.shape[0] + + with torch.no_grad(): + input_rgb = torch.cat([rgb_static, rgb_gripper], dim=0) + language = language + language + perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + self.extract_layer_idx, all_layer=self.use_all_layer, + step_time=1, max_length=self.max_length) + + perceptual_features = einops.rearrange(perceptual_features, 'b f c h w-> b f c (h w)') + perceptual_features = einops.rearrange(perceptual_features, 'b f c l-> b f l c') + perceptual_features = perceptual_features[:, :num_frames, :, :] + #print('perceptual_features_shape:', perceptual_features.shape) + + perceptual_features, gripper_feature = torch.split(perceptual_features, [batch, batch], dim=0) + perceptual_features = torch.cat([perceptual_features, gripper_feature], dim=2) + + perceptual_features = perceptual_features.to(torch.float32) + perceptual_features = self.Video_Former(perceptual_features) + if self.use_Former=='linear': + perceptual_features = rearrange(perceptual_features, 'b T q d -> b (T q) d') + predictive_feature = {'state_images': perceptual_features} + predictive_feature['modality'] = modality + return predictive_feature, latent_goal + + + def _log_training_metrics(self, action_loss, total_loss, total_bs): + """ + Log the training metrics. + """ + self.log("train/action_loss", action_loss, on_step=False, on_epoch=True, sync_dist=True, batch_size=total_bs) + self.log("train/total_loss", total_loss, on_step=False, on_epoch=True, sync_dist=True, batch_size=total_bs) + + def _log_validation_metrics(self, pred_loss, img_gen_loss, val_total_act_loss_pp): + """ + Log the validation metrics. + """ + self.log( + "val_act/action_loss", + val_total_act_loss_pp / len(self.trainer.datamodule.modalities), # type:ignore + sync_dist=True, + ) + self.log(f"val_act/img_gen_loss_pp", img_gen_loss, sync_dist=True) + + def diffusion_loss( + self, + perceptual_emb: torch.Tensor, + latent_goal: torch.Tensor, + actions: torch.Tensor, + ) -> torch.Tensor: + """ + Computes the score matching loss given the perceptual embedding, latent goal, and desired actions. + """ + self.model.train() + sigmas = self.make_sample_density()(shape=(len(actions),), device=self.device).to(self.device) + noise = torch.randn_like(actions).to(self.device) + loss, _ = self.model.loss(perceptual_emb, actions, latent_goal, noise, sigmas) + return loss, sigmas, noise + + def denoise_actions( # type: ignore + self, + latent_plan: torch.Tensor, + perceptual_emb: torch.Tensor, + latent_goal: torch.Tensor, + inference: Optional[bool] = False, + extra_args={} + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Denoise the next sequence of actions + """ + if inference: + sampling_steps = self.num_sampling_steps + else: + sampling_steps = 10 + self.model.eval() + if len(latent_goal.shape) < len( + perceptual_emb['state_images'].shape if isinstance(perceptual_emb, dict) else perceptual_emb.shape): + latent_goal = latent_goal.unsqueeze(1) # .expand(-1, seq_len, -1) + input_state = perceptual_emb + sigmas = self.get_noise_schedule(sampling_steps, self.noise_scheduler) + + x = torch.randn((len(latent_goal), self.act_window_size, self.action_dim), device=self.device) * self.sigma_max + + actions = self.sample_loop(sigmas, x, input_state, latent_goal, latent_plan, self.sampler_type, extra_args) + + return actions + + def make_sample_density(self): + """ + Generate a sample density function based on the desired type for training the model + We mostly use log-logistic as it has no additional hyperparameters to tune. + """ + sd_config = [] + if self.sigma_sample_density_type == 'lognormal': + loc = self.sigma_sample_density_mean # if 'mean' in sd_config else sd_config['loc'] + scale = self.sigma_sample_density_std # if 'std' in sd_config else sd_config['scale'] + return partial(utils.rand_log_normal, loc=loc, scale=scale) + + if self.sigma_sample_density_type == 'loglogistic': + loc = sd_config['loc'] if 'loc' in sd_config else math.log(self.sigma_data) + scale = sd_config['scale'] if 'scale' in sd_config else 0.5 + min_value = sd_config['min_value'] if 'min_value' in sd_config else self.sigma_min + max_value = sd_config['max_value'] if 'max_value' in sd_config else self.sigma_max + return partial(utils.rand_log_logistic, loc=loc, scale=scale, min_value=min_value, max_value=max_value) + + if self.sigma_sample_density_type == 'loguniform': + min_value = sd_config['min_value'] if 'min_value' in sd_config else self.sigma_min + max_value = sd_config['max_value'] if 'max_value' in sd_config else self.sigma_max + return partial(utils.rand_log_uniform, min_value=min_value, max_value=max_value) + + if self.sigma_sample_density_type == 'uniform': + return partial(utils.rand_uniform, min_value=self.sigma_min, max_value=self.sigma_max) + + if self.sigma_sample_density_type == 'v-diffusion': + min_value = self.min_value if 'min_value' in sd_config else self.sigma_min + max_value = sd_config['max_value'] if 'max_value' in sd_config else self.sigma_max + return partial(utils.rand_v_diffusion, sigma_data=self.sigma_data, min_value=min_value, max_value=max_value) + if self.sigma_sample_density_type == 'discrete': + sigmas = self.get_noise_schedule(self.num_sampling_steps * 1e5, 'exponential') + return partial(utils.rand_discrete, values=sigmas) + if self.sigma_sample_density_type == 'split-lognormal': + loc = sd_config['mean'] if 'mean' in sd_config else sd_config['loc'] + scale_1 = sd_config['std_1'] if 'std_1' in sd_config else sd_config['scale_1'] + scale_2 = sd_config['std_2'] if 'std_2' in sd_config else sd_config['scale_2'] + return partial(utils.rand_split_log_normal, loc=loc, scale_1=scale_1, scale_2=scale_2) + else: + raise ValueError('Unknown sample density type') + + def sample_loop( + self, + sigmas, + x_t: torch.Tensor, + state: torch.Tensor, + goal: torch.Tensor, + latent_plan: torch.Tensor, + sampler_type: str, + extra_args={}, + ): + """ + Main method to generate samples depending on the chosen sampler type. DDIM is the default as it works well in all settings. + """ + s_churn = extra_args['s_churn'] if 's_churn' in extra_args else 0 + s_min = extra_args['s_min'] if 's_min' in extra_args else 0 + use_scaler = extra_args['use_scaler'] if 'use_scaler' in extra_args else False + keys = ['s_churn', 'keep_last_actions'] + if bool(extra_args): + reduced_args = {x: extra_args[x] for x in keys} + else: + reduced_args = {} + if use_scaler: + scaler = self.scaler + else: + scaler = None + # ODE deterministic + if sampler_type == 'lms': + x_0 = sample_lms(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True, extra_args=reduced_args) + # ODE deterministic can be made stochastic by S_churn != 0 + elif sampler_type == 'heun': + x_0 = sample_heun(self.model, state, x_t, goal, sigmas, scaler=scaler, s_churn=s_churn, s_tmin=s_min, + disable=True) + # ODE deterministic + elif sampler_type == 'euler': + x_0 = sample_euler(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # SDE stochastic + elif sampler_type == 'ancestral': + x_0 = sample_dpm_2_ancestral(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # SDE stochastic: combines an ODE euler step with an stochastic noise correcting step + elif sampler_type == 'euler_ancestral': + x_0 = sample_euler_ancestral(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # ODE deterministic + elif sampler_type == 'dpm': + x_0 = sample_dpm_2(self.model, state, x_t, goal, sigmas, disable=True) + # ODE deterministic + elif sampler_type == 'dpm_adaptive': + x_0 = sample_dpm_adaptive(self.model, state, x_t, goal, sigmas[-2].item(), sigmas[0].item(), disable=True) + # ODE deterministic + elif sampler_type == 'dpm_fast': + x_0 = sample_dpm_fast(self.model, state, x_t, goal, sigmas[-2].item(), sigmas[0].item(), len(sigmas), + disable=True) + # 2nd order solver + elif sampler_type == 'dpmpp_2s_ancestral': + x_0 = sample_dpmpp_2s_ancestral(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # 2nd order solver + elif sampler_type == 'dpmpp_2m': + x_0 = sample_dpmpp_2m(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'dpmpp_2m_sde': + x_0 = sample_dpmpp_sde(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'ddim': + x_0 = sample_ddim(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'dpmpp_2s': + x_0 = sample_dpmpp_2s(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'dpmpp_2_with_lms': + x_0 = sample_dpmpp_2_with_lms(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + else: + raise ValueError('desired sampler type not found!') + return x_0 + + def get_noise_schedule(self, n_sampling_steps, noise_schedule_type): + """ + Get the noise schedule for the sampling steps. Describes the distribution over the noise levels from sigma_min to sigma_max. + """ + if noise_schedule_type == 'karras': + return get_sigmas_karras(n_sampling_steps, self.sigma_min, self.sigma_max, 7, + self.device) # rho=7 is the default from EDM karras + elif noise_schedule_type == 'exponential': + return get_sigmas_exponential(n_sampling_steps, self.sigma_min, self.sigma_max, self.device) + elif noise_schedule_type == 'vp': + return get_sigmas_vp(n_sampling_steps, device=self.device) + elif noise_schedule_type == 'linear': + return get_sigmas_linear(n_sampling_steps, self.sigma_min, self.sigma_max, device=self.device) + elif noise_schedule_type == 'cosine_beta': + return cosine_beta_schedule(n_sampling_steps, device=self.device) + elif noise_schedule_type == 've': + return get_sigmas_ve(n_sampling_steps, self.sigma_min, self.sigma_max, device=self.device) + elif noise_schedule_type == 'iddpm': + return get_iddpm_sigmas(n_sampling_steps, self.sigma_min, self.sigma_max, device=self.device) + raise ValueError('Unknown noise schedule type') + + def reset(self): + """ + Call this at the beginning of a new rollout when doing inference. + """ + self.plan = None + self.latent_goal = None + self.rollout_step_counter = 0 + + def forward(self,batch): + return self.training_step(batch) + #def training_step(self, batch: Dict[str, Dict], batch_idx: int, + # dataloader_idx: int = 0) -> torch.Tensor + + def eval_forward(self, obs, goal): + """ + Method for doing inference with the model. + """ + if 'lang_text' in goal: + if self.use_text_not_embedding: + # print(goal.keys()) + latent_goal = self.language_goal(goal["lang_text"]) + latent_goal = latent_goal.to(torch.float32) + else: + latent_goal = self.language_goal(goal["lang"]).unsqueeze(0).to(torch.float32).to( + obs["rgb_obs"]['rgb_static'].device) + + rgb_static = obs["rgb_obs"]['rgb_static'] + # rgb_gripper = dataset_batch["rgb_obs"]['rgb_gripper'][:, :-1] + rgb_gripper = obs["rgb_obs"]['rgb_gripper'] + + language = goal["lang_text"] + + num_frames = self.Former_num_time_embeds + rgb_static = rgb_static.to(self.device) + rgb_gripper = rgb_gripper.to(self.device) + batch = rgb_static.shape[0] + + with torch.no_grad(): + input_rgb = torch.cat([rgb_static, rgb_gripper], dim=0) + language = [language] + [language] + perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + self.extract_layer_idx, all_layer=self.use_all_layer, + step_time=1, max_length=self.max_length) + + perceptual_features = einops.rearrange(perceptual_features, 'b f c h w-> b f c (h w)') + perceptual_features = einops.rearrange(perceptual_features, 'b f c l-> b f l c') + perceptual_features = perceptual_features[:, :num_frames, :, :] + + perceptual_features, gripper_feature = torch.split(perceptual_features, [batch, batch], dim=0) + perceptual_features = torch.cat([perceptual_features, gripper_feature], dim=2) + + perceptual_features = perceptual_features.to(torch.float32) + perceptual_features = self.Video_Former(perceptual_features) + if self.use_Former == 'linear': + perceptual_features = rearrange(perceptual_features, 'b T q d -> b (T q) d') + + perceptual_emb = {'state_images': perceptual_features} + + perceptual_emb['modality'] = "lang" + #print('latent_goal_shape:',latent_goal.shape) + #print('perceptual_features_shape:', perceptual_features.shape) + + act_seq = self.denoise_actions( + torch.zeros_like(latent_goal).to(latent_goal.device), + perceptual_emb, + latent_goal, + inference=True, + ) + return act_seq + + def step(self, obs, goal): + """ + Do one step of inference with the model. THis method handles the action chunking case. + Our model is trained to predict a sequence of actions. + We only compute the sequence once every self.multistep steps. + + Args: + obs (dict): Observation from environment. + goal (dict): Goal as visual observation or embedded language instruction. + + Returns: + Predicted action. + """ + if self.rollout_step_counter % self.multistep == 0: + pred_action_seq = self.eval_forward(obs, goal) + + self.pred_action_seq = pred_action_seq + + current_action = self.pred_action_seq[0, self.rollout_step_counter] + if len(current_action.shape) == 2: + current_action = einops.rearrange(current_action, 'b d -> b 1 d') + self.rollout_step_counter += 1 + if self.rollout_step_counter == self.multistep: + self.rollout_step_counter = 0 + + return current_action + + def on_train_start(self) -> None: + + self.model.to(dtype=self.dtype) + + self.Video_Former.to(dtype=self.dtype) + self.language_goal.to(dtype=self.dtype) + #self.vae.to(dtype=self.dtype) + self.TVP_encoder.to(dtype=self.dtype) + + @rank_zero_only + def on_train_epoch_start(self) -> None: + logger.info(f"Start training epoch {self.current_epoch}") + + @rank_zero_only + def on_train_epoch_end(self, unused: Optional = None) -> None: # type: ignore + logger.info(f"Finished training epoch {self.current_epoch}") + + @rank_zero_only + def on_validation_epoch_end(self) -> None: + logger.info(f"Finished validation epoch {self.current_epoch}") + + + def on_validation_epoch_start(self) -> None: + log_rank_0(f"Start validation epoch {self.current_epoch}") + + @rank_zero_only + def on_train_epoch_start(self) -> None: + logger.info(f"Start training epoch {self.current_epoch}") + + @rank_zero_only + def on_train_epoch_end(self, unused: Optional = None) -> None: # type: ignore + logger.info(f"Finished training epoch {self.current_epoch}") + + @rank_zero_only + def on_validation_epoch_end(self) -> None: + logger.info(f"Finished validation epoch {self.current_epoch}") + + def on_validation_epoch_start(self) -> None: + log_rank_0(f"Start validation epoch {self.current_epoch}") + + +@rank_zero_only +def log_rank_0(*args, **kwargs): + # when using ddp, only log with rank 0 process + logger.info(*args, **kwargs) \ No newline at end of file diff --git a/code/policy_models/VPP_policy_xbot.py b/code/policy_models/VPP_policy_xbot.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0f27a4262d7cf475641c681cea73f8da351b14 --- /dev/null +++ b/code/policy_models/VPP_policy_xbot.py @@ -0,0 +1,941 @@ +import logging +from typing import Dict, Optional, Tuple +from functools import partial + +from omegaconf import DictConfig, OmegaConf +import pytorch_lightning as pl +from pytorch_lightning.utilities import rank_zero_only +import einops +from policy_models.edm_diffusion.score_wrappers import GCDenoiser + +from policy_models.module.clip_lang_encoder import LangClip +from policy_models.edm_diffusion.gc_sampling import * +from policy_models.utils.lr_schedulers.tri_stage_scheduler import TriStageLRScheduler +from policy_models.module.Video_Former import Video_Former_2D,Video_Former_3D +from diffusers import StableVideoDiffusionPipeline +from policy_models.module.diffusion_extract import Diffusion_feature_extractor +from transformers import AutoTokenizer, CLIPTextModelWithProjection + + +logger = logging.getLogger(__name__) + +def load_primary_models(pretrained_model_path, eval=False): + print('load primary models from:', pretrained_model_path) + if eval: + pipeline = StableVideoDiffusionPipeline.from_pretrained(pretrained_model_path, torch_dtype=torch.float16) + else: + pipeline = StableVideoDiffusionPipeline.from_pretrained(pretrained_model_path) + return pipeline + + +class VPP_Policy(nn.Module):#pl.LightningModule): + """ + The lightning module used for training. + """ + + def __init__( + self, + optimizer: DictConfig, + lr_scheduler: DictConfig, + latent_dim: int = 512, + multistep: int = 10, + sampler_type: str = 'ddim', + num_sampling_steps: int = 10, + sigma_data: float = 0.5, + sigma_min: float = 0.001, + sigma_max: float = 80, + noise_scheduler: str = 'exponential', + sigma_sample_density_type: str = 'loglogistic', + use_lr_scheduler: bool = True, + act_window_size: int = 10, + use_text_not_embedding: bool = False, + seed: int = 42, + pretrained_model_path: str = '/cephfs/shared/gyj/ckpt/svd_pre/checkpoint-100000', + text_encoder_path: str = '/cephfs/shared/llm/clip-vit-base-patch32', + Former_depth: int = 3, + Former_heads: int = 8, + Former_dim_head: int = 64, + Former_num_time_embeds: int = 1, + num_latents: int = 3, + use_3d_Former: bool = False, + timestep: int = 20, + extract_layer_idx: int = 1, + use_all_layer: bool = False, + obs_seq_len: int = 1, + action_dim: int = 18, + action_seq_len: int = 10, + proprio_dim: int = 19, + device: str = 'cuda', + ): + super(VPP_Policy, self).__init__() + self.device = device + self.dtype = torch.float32 + self.latent_dim = latent_dim + self.use_all_layer = use_all_layer + + self.act_window_size = act_window_size + self.action_dim = action_dim + + self.timestep = timestep + self.extract_layer_idx = extract_layer_idx + self.use_3d_Former = use_3d_Former + + condition_dim_list = [1280,1280,640] + condition_dim = condition_dim_list[extract_layer_idx] + + if use_3d_Former: + self.Video_Former = Video_Former_3D( + dim=latent_dim, + depth=Former_depth, + dim_head=Former_dim_head, + heads=Former_heads, + num_time_embeds=Former_num_time_embeds, + num_latents=num_latents, + condition_dim=condition_dim, + use_temporal=True, + ) + else: + self.Video_Former = Video_Former_2D( + dim=latent_dim, + depth=Former_depth, + dim_head=Former_dim_head, + heads=Former_heads, + num_time_embeds=Former_num_time_embeds, + num_latents=num_latents, + condition_dim=condition_dim, + ) + + print('use_3d_Former:', self.use_3d_Former) + print('use_all_layer',self.use_all_layer) + + self.seed = seed + self.use_lr_scheduler = use_lr_scheduler + # goal encoders + # self.language_goal = LangClip(model_name='ViT-B/32').to(self.device) + + + pipeline = load_primary_models( + pretrained_model_path , eval = True) + + #text_encoder = CLIPTextModelWithProjection.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32") + #tokenizer = AutoTokenizer.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32", use_fast=False) + text_encoder = CLIPTextModelWithProjection.from_pretrained(text_encoder_path) + tokenizer = AutoTokenizer.from_pretrained(text_encoder_path, use_fast=False) + + self.tokenizer = tokenizer + self.text_encoder = text_encoder + + text_encoder = text_encoder.to(self.device).eval() + + for param in pipeline.image_encoder.parameters(): + param.requires_grad = False + for param in text_encoder.parameters(): + param.requires_grad = False + + for param in pipeline.vae.parameters(): + param.requires_grad = False + for param in pipeline.unet.parameters(): + param.requires_grad = False + + pipeline = pipeline.to(self.device) + pipeline.unet.eval() + + self.TVP_encoder = Diffusion_feature_extractor(pipeline=pipeline, + tokenizer=tokenizer, + text_encoder=text_encoder, ) + self.TVP_encoder = self.TVP_encoder.to(self.device) + # policy network + self.model = GCDenoiser(action_dim = action_dim, + obs_dim=latent_dim, + proprio_dim=proprio_dim, + goal_dim=512, + num_tokens=num_latents, + goal_window_size = 1, + obs_seq_len = obs_seq_len, + act_seq_len = action_seq_len, + device=self.device, + sigma_data=0.5).to(self.device) + + self.optimizer_config = optimizer + self.lr_scheduler = lr_scheduler + # self.save_hyperparameters() + # diffusion stuff + self.sampler_type = sampler_type + self.num_sampling_steps = num_sampling_steps + self.noise_scheduler = noise_scheduler + self.sigma_data = sigma_data + self.sigma_min = sigma_min + self.sigma_max = sigma_max + self.sigma_sample_density_type = sigma_sample_density_type + # for inference + self.rollout_step_counter = 0 + self.multistep = multistep + self.latent_goal = None + self.plan = None + self.use_text_not_embedding = use_text_not_embedding + # print_model_parameters(self.perceptual_encoder.perceiver_resampler) + # for clip loss ground truth plot + self.ema_callback_idx = None + + for param in self.model.inner_model.proprio_emb.parameters(): + param.requires_grad = False + for param in self.model.inner_model.goal_emb.parameters(): + param.requires_grad = False + self.model.inner_model.pos_emb.requires_grad = False + + def process_device(self): + self.TVP_encoder.pipeline = self.TVP_encoder.pipeline.to(self.device) + self.TVP_encoder.text_encoder = self.TVP_encoder.text_encoder.to(self.device) + + def configure_optimizers(self): + """ + Initialize optimizers and learning rate schedulers based on model configuration. + """ + # Configuration for models using transformer weight decay + '''optim_groups = self.action_decoder.model.inner_model.get_optim_groups( + weight_decay=self.optimizer_config.transformer_weight_decay + )''' + optim_groups = [ + {"params": self.model.inner_model.parameters(), + "weight_decay": self.optimizer_config.transformer_weight_decay}, + {"params": self.Video_Former.parameters(), "weight_decay": self.optimizer_config.transformer_weight_decay}, + ] + + + optimizer = torch.optim.AdamW(optim_groups, lr=self.optimizer_config.learning_rate, + betas=self.optimizer_config.betas) + + # Optionally initialize the scheduler + if self.use_lr_scheduler: + lr_configs = OmegaConf.create(self.lr_scheduler) + scheduler = TriStageLRScheduler(optimizer, lr_configs) + lr_scheduler = { + "scheduler": scheduler, + "interval": 'step', + "frequency": 1, + } + return {"optimizer": optimizer, "lr_scheduler": lr_scheduler} + else: + return optimizer + + def on_before_zero_grad(self, optimizer=None): + total_grad_norm = 0.0 + total_param_norm = 0.0 + for p in self.model.parameters(): + if p.grad is not None: + total_grad_norm += p.grad.norm().item() ** 2 + total_param_norm += p.norm().item() ** 2 + total_grad_norm = total_grad_norm ** 0.5 + total_param_norm = total_param_norm ** 0.5 + + self.log("train/grad_norm", total_grad_norm, on_step=True, on_epoch=False, sync_dist=True) + self.log("train/param_norm", total_param_norm, on_step=True, on_epoch=False, sync_dist=True) + + + def training_step(self, dataset_batch: Dict[str, Dict],) -> torch.Tensor: # type: ignore + """ + Compute and return the training loss for the MDT Agent. + The training loss consists of the score matching loss of the diffusion model + and the contrastive loss of the CLIP model for the multimodal encoder. + + Args: + batch: Dictionary containing the batch data for each modality. + batch_idx: Index of the batch. used for compatibility with pytorch lightning. + dataloader_idx: Index of the dataloader. used for compatibility with pytorch lightning. + + Returns: + loss tensor + """ + total_loss, action_loss = ( + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + ) + + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + target, model_output = self.diffusion_loss( + predictive_feature, + latent_goal, + dataset_batch["actions"], + ) + act_loss = (model_output - target).pow(2).flatten(1).mean(), + + action_loss += act_loss + total_loss += act_loss + + total_bs = dataset_batch["actions"].shape[0] + + self._log_training_metrics(action_loss, total_loss, total_bs) + return total_loss + + + @torch.no_grad() + def validation_step(self, dataset_batch: Dict[str, Dict]) -> Dict[ + str, torch.Tensor]: # type: ignore + """ + Compute and log the validation losses and additional metrics. + During the validation step, the diffusion model predicts the next action sequence given the current state + + Args: + batch: Dictionary containing the batch data for each modality. + batch_idx: Index of the batch. used for compatibility with pytorch lightning. + dataloader_idx: Index of the dataloader. used for compatibility with pytorch lightning. + + Returns: + Dictionary containing the sampled plans of plan recognition and plan proposal module, as well as the + episode indices. + """ + output = {} + val_total_act_loss_pp = torch.tensor(0.0).to(self.device) + # Compute the required embeddings + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + # predict the next action sequence + action_pred = self.denoise_actions( + torch.zeros_like(latent_goal).to(latent_goal.device), + predictive_feature, + latent_goal, + inference=True, + ) + dataset_batch["actions"] = dataset_batch["actions"].to(action_pred.device) + # compute the mse action loss + pred_loss = torch.nn.functional.mse_loss(action_pred, dataset_batch["actions"]) + val_total_act_loss_pp += pred_loss + + output[f"idx:"] = dataset_batch["idx"] + output["validation_loss"] = val_total_act_loss_pp + return output + + def training_step_xbot(self, dataset_batch: Dict[str, Dict],): + total_loss, action_loss, loss_xyz, loss_rot, loss_hand = ( + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + ) + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + target, model_output = self.diffusion_loss( + predictive_feature, + latent_goal, + dataset_batch["actions"], + ) + loss_dict = {} + loss_dict['loss_xyz'] = (model_output[:,:,:3] - target[:,:,:3]).pow(2).mean()*3/38+(model_output[:,:,19:22] - target[:,:,19:22]).pow(2).mean()*3/38 + loss_dict['loss_rot'] = (model_output[:,:,3:7] - target[:,:,3:7]).pow(2).mean()*4/38+(model_output[:,:,22:26] - target[:,:,22:26]).pow(2).mean()*4/38 + loss_dict['loss_hand'] = (model_output[:,:,7:19] - target[:,:,7:19]).pow(2).mean()*12/38+(model_output[:,:,26:38] - target[:,:,26:38]).pow(2).mean()*12/38 + + act_loss = loss_dict['loss_xyz']+loss_dict['loss_rot']+loss_dict['loss_hand'] + loss_dict['loss'] = act_loss + + action_loss += act_loss + loss_xyz += loss_dict['loss_xyz'] + loss_rot += loss_dict['loss_rot'] + loss_hand += loss_dict['loss_hand'] + + total_loss += act_loss + + return total_loss, loss_xyz, loss_rot, loss_hand + + @torch.no_grad() + def validation_step_xbot(self, dataset_batch: Dict[str, Dict], print_it=False) -> Dict[ + str, torch.Tensor]: # type: ignore + output = {} + val_total_act_loss_pp = torch.tensor(0.0).to(self.device) + # Compute the required embeddings + # perceptual_emb, latent_goal, image_latent_goal = self.compute_input_embeddings(dataset_batch) + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + # predict the next action sequence + action_pred = self.denoise_actions( + torch.zeros_like(latent_goal).to(latent_goal.device), + predictive_feature, + latent_goal, + inference=True, + ) + dataset_batch["actions"] = dataset_batch["actions"].to(action_pred.device) #(batch, time, dim) + # loss_xyz = torch.nn.functional.mse_loss(action_pred[:, :, :3], dataset_batch["actions"][:, :, :3])*3/18 + # loss_rot = torch.nn.functional.mse_loss(action_pred[:, :, 3:-12], dataset_batch["actions"][:, :, 3:-12])*3/18 + # loss_hand = torch.nn.functional.mse_loss(action_pred[:, :, -12:], dataset_batch["actions"][:, :, -12:])*12/18 + model_output = action_pred + target = dataset_batch["actions"] + loss_xyz = (model_output[:,:,:3] - target[:,:,:3]).pow(2).mean()*3/38+(model_output[:,:,19:22] - target[:,:,19:22]).pow(2).mean()*3/38 + loss_rot = (model_output[:,:,3:7] - target[:,:,3:7]).pow(2).mean()*4/38+(model_output[:,:,22:26] - target[:,:,22:26]).pow(2).mean()*4/38 + loss_hand = (model_output[:,:,7:19] - target[:,:,7:19]).pow(2).mean()*12/38+(model_output[:,:,26:38] - target[:,:,26:38]).pow(2).mean()*12/38 + pred_loss = loss_xyz + loss_rot + loss_hand + + # pred_loss = torch.nn.functional.mse_loss(action_pred, dataset_batch["actions"]) + # loss_xyz, loss_rot, loss_hand = 0, 0, 0 + + latent_encoder_emb = self.model.inner_model.latent_encoder_emb + val_total_act_loss_pp += pred_loss + + + # output[f"idx_{self.modality_scope}"] = dataset_batch["idx"] + output["validation_loss"] = val_total_act_loss_pp + output["loss_xyz"] = loss_xyz + output["loss_rot"] = loss_rot + output["loss_hand"] = loss_hand + + if print_it: + # print(dataset_batch['frame_ids']) + # print(dataset_batch['ann_file']) + # print("action_pred_shape:", action_pred.shape) + frame_ids = [idx.cpu().numpy() for idx in dataset_batch['frame_ids']] + frame_ids = np.array(frame_ids) + # print("frame_ids:", frame_ids) + for i in range(action_pred.shape[0]): + print('data info', dataset_batch['ann_file'][i], frame_ids[:,i]) + # print("true_action:", dataset_batch["actions"][i].flatten()[:19]) + # print("pred_action:", action_pred[i].flatten()[:19]) + print("true_action:", dataset_batch["actions"][i][:4, :7].flatten()) + print("pred_action:", action_pred[i][:4, :7].flatten()) + + print("true_hand:", dataset_batch["actions"][i][:1, -12:].flatten()) + print("pred_hand:", action_pred[i][:1, -12:].flatten()) + print('-----------------------------------------------') + return output + + def training_step_xhand(self, dataset_batch: Dict[str, Dict],): + total_loss, action_loss, loss_xyz, loss_rot, loss_hand = ( + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + torch.tensor(0.0).to(self.device), + ) + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + target, model_output = self.diffusion_loss( + predictive_feature, + latent_goal, + dataset_batch["actions"], + ) + loss_dict = {} + loss_dict['loss_xyz'] = (model_output[:,:,:3] - target[:,:,:3]).pow(2).mean()*3/18 + loss_dict['loss_rot'] = (model_output[:,:,3:-12] - target[:,:,3:-12]).pow(2).mean()*3/18 + loss_dict['loss_hand'] = (model_output[:,:,-12:] - target[:,:,-12:]).pow(2).mean()*12/18 + act_loss = loss_dict['loss_xyz']+loss_dict['loss_rot']+loss_dict['loss_hand'] + loss_dict['loss'] = act_loss + + action_loss += act_loss + loss_xyz += loss_dict['loss_xyz'] + loss_rot += loss_dict['loss_rot'] + loss_hand += loss_dict['loss_hand'] + + total_loss += act_loss + + return total_loss, loss_xyz, loss_rot, loss_hand + + @torch.no_grad() + def validation_step_xhand(self, dataset_batch: Dict[str, Dict], print_it=False) -> Dict[ + str, torch.Tensor]: # type: ignore + """ + Compute and log the validation losses and additional metrics. + During the validation step, the diffusion model predicts the next action sequence given the current state + + Args: + batch: Dictionary containing the batch data for each modality. + batch_idx: Index of the batch. used for compatibility with pytorch lightning. + dataloader_idx: Index of the dataloader. used for compatibility with pytorch lightning. + + Returns: + Dictionary containing the sampled plans of plan recognition and plan proposal networks, as well as the + episode indices. + """ + output = {} + val_total_act_loss_pp = torch.tensor(0.0).to(self.device) + # Compute the required embeddings + # perceptual_emb, latent_goal, image_latent_goal = self.compute_input_embeddings(dataset_batch) + predictive_feature, latent_goal= self.extract_predictive_feature(dataset_batch) + + # predict the next action sequence + action_pred = self.denoise_actions( + torch.zeros_like(latent_goal).to(latent_goal.device), + predictive_feature, + latent_goal, + inference=True, + ) + dataset_batch["actions"] = dataset_batch["actions"].to(action_pred.device) #(batch, time, dim) + # print("action_pred_shape:", action_pred.shape) + # print("action_truth_shape:", dataset_batch["actions"].shape) + + # compute the mse action loss + loss_xyz = torch.nn.functional.mse_loss(action_pred[:, :, :3], dataset_batch["actions"][:, :, :3])*3/18 + loss_rot = torch.nn.functional.mse_loss(action_pred[:, :, 3:-12], dataset_batch["actions"][:, :, 3:-12])*3/18 + loss_hand = torch.nn.functional.mse_loss(action_pred[:, :, -12:], dataset_batch["actions"][:, :, -12:])*12/18 + pred_loss = loss_xyz + loss_rot + loss_hand + + # pred_loss = torch.nn.functional.mse_loss(action_pred, dataset_batch["actions"]) + # loss_xyz, loss_rot, loss_hand = 0, 0, 0 + + latent_encoder_emb = self.model.inner_model.latent_encoder_emb + val_total_act_loss_pp += pred_loss + + + # output[f"idx_{self.modality_scope}"] = dataset_batch["idx"] + output["validation_loss"] = val_total_act_loss_pp + output["loss_xyz"] = loss_xyz + output["loss_rot"] = loss_rot + output["loss_hand"] = loss_hand + + if print_it: + # print(dataset_batch['frame_ids']) + # print(dataset_batch['ann_file']) + # print("action_pred_shape:", action_pred.shape) + frame_ids = [idx.cpu().numpy() for idx in dataset_batch['frame_ids']] + frame_ids = np.array(frame_ids) + # print("frame_ids:", frame_ids) + for i in range(action_pred.shape[0]): + print('data info', dataset_batch['ann_file'][i], frame_ids[:,i]) + # print("true_action:", dataset_batch["actions"][i].flatten()[:19]) + # print("pred_action:", action_pred[i].flatten()[:19]) + print("true_action:", dataset_batch["actions"][i][:4, :-12].flatten()) + print("pred_action:", action_pred[i][:4, :-12].flatten()) + + print("true_hand:", dataset_batch["actions"][i][:1, -12:].flatten()) + print("pred_hand:", action_pred[i][:1, -12:].flatten()) + print('-----------------------------------------------') + return output + + def extract_predictive_feature(self, dataset_batch): + """ + Compute the required embeddings for the visual ones and the latent goal. + """ + # 1. extract the revelant visual observations + rgb_static = dataset_batch["rgb_obs"]['rgb_static'].to(self.device) + rgb_gripper = dataset_batch["rgb_obs"]['rgb_gripper'].to(self.device) + if 'rgb_gripper2' in dataset_batch["rgb_obs"]: + rgb_gripper2 = dataset_batch["rgb_obs"]['rgb_gripper2'].to(self.device) + # 3. we compute the language goal if the language modality is in the scope + modality = "lang" + + assert self.use_text_not_embedding == True + if self.use_text_not_embedding: + inputs = self.tokenizer(text=dataset_batch["lang_text"], padding='max_length', return_tensors="pt",truncation=True).to(self.text_encoder.device) + outputs = self.text_encoder(**inputs) + latent_goal = outputs.text_embeds + + language = dataset_batch["lang_text"] + + batch = rgb_static.shape[0] + + if 'rgb_gripper2' not in dataset_batch["rgb_obs"]: + with torch.no_grad(): + input_rgb = torch.cat([rgb_static, rgb_gripper], dim=0) + language = language + language + # print("input_rgb_shape:", input_rgb.shape) + # print("language_shape:", len(language)) + perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + self.extract_layer_idx) + # perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + # self.extract_layer_idx, all_layer=self.use_all_layer, + # step_time=1) + + perceptual_features = einops.rearrange(perceptual_features, 'b f c h w-> b f c (h w)') + perceptual_features = einops.rearrange(perceptual_features, 'b f c l-> b f l c') + + perceptual_features, gripper_feature = torch.split(perceptual_features, [batch, batch], dim=0) + perceptual_features = torch.cat([perceptual_features, gripper_feature], dim=2) + + else: + with torch.no_grad(): + input_rgb = torch.cat([rgb_static, rgb_gripper, rgb_gripper2], dim=0) + language = language + language + language + perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + self.extract_layer_idx) + + perceptual_features = einops.rearrange(perceptual_features, 'b f c h w-> b f c (h w)') + perceptual_features = einops.rearrange(perceptual_features, 'b f c l-> b f l c') + + perceptual_features, gripper_feature1, gripper_feature2 = torch.split(perceptual_features, [batch, batch, batch], dim=0) + perceptual_features = torch.cat([perceptual_features, gripper_feature1, gripper_feature2], dim=2) + + + perceptual_features = perceptual_features.to(torch.float32) + perceptual_features = self.Video_Former(perceptual_features) + + predictive_feature = {'state_images': perceptual_features} + predictive_feature['modality'] = modality + if 'state_obs' in dataset_batch.keys(): + predictive_feature['state_obs'] = dataset_batch['state_obs'].to(self.device) + + return predictive_feature, latent_goal + + + def _log_training_metrics(self, action_loss, total_loss, total_bs): + """ + Log the training metrics. + """ + self.log("train/action_loss", action_loss, on_step=False, on_epoch=True, sync_dist=True, batch_size=total_bs) + self.log("train/total_loss", total_loss, on_step=False, on_epoch=True, sync_dist=True, batch_size=total_bs) + + def _log_validation_metrics(self, pred_loss, img_gen_loss, val_total_act_loss_pp): + """ + Log the validation metrics. + """ + self.log( + "val_act/action_loss", + val_total_act_loss_pp / len(self.trainer.datamodule.modalities), # type:ignore + sync_dist=True, + ) + self.log(f"val_act/img_gen_loss_pp", img_gen_loss, sync_dist=True) + + def diffusion_loss( + self, + perceptual_emb: torch.Tensor, + latent_goal: torch.Tensor, + actions: torch.Tensor, + ) -> torch.Tensor: + """ + Computes the score matching loss given the perceptual embedding, latent goal, and desired actions. + """ + self.model.train() + sigmas = self.make_sample_density()(shape=(len(actions),), device=self.device).to(self.device) + noise = torch.randn_like(actions).to(self.device) + target, model_output = self.model.loss(perceptual_emb, actions, latent_goal, noise, sigmas) + return target, model_output + + def denoise_actions( # type: ignore + self, + latent_plan: torch.Tensor, + perceptual_emb: torch.Tensor, + latent_goal: torch.Tensor, + inference: Optional[bool] = False, + extra_args={} + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Denoise the next sequence of actions + """ + if inference: + sampling_steps = self.num_sampling_steps + else: + sampling_steps = 10 + self.model.eval() + if len(latent_goal.shape) < len( + perceptual_emb['state_images'].shape if isinstance(perceptual_emb, dict) else perceptual_emb.shape): + latent_goal = latent_goal.unsqueeze(1) # .expand(-1, seq_len, -1) + input_state = perceptual_emb + sigmas = self.get_noise_schedule(sampling_steps, self.noise_scheduler) + + x = torch.randn((len(latent_goal), self.act_window_size, self.action_dim), device=self.device) * self.sigma_max + + actions = self.sample_loop(sigmas, x, input_state, latent_goal, latent_plan, self.sampler_type, extra_args) + + return actions + + def make_sample_density(self): + """ + Generate a sample density function based on the desired type for training the model + We mostly use log-logistic as it has no additional hyperparameters to tune. + """ + sd_config = [] + if self.sigma_sample_density_type == 'lognormal': + loc = self.sigma_sample_density_mean # if 'mean' in sd_config else sd_config['loc'] + scale = self.sigma_sample_density_std # if 'std' in sd_config else sd_config['scale'] + return partial(utils.rand_log_normal, loc=loc, scale=scale) + + if self.sigma_sample_density_type == 'loglogistic': + loc = sd_config['loc'] if 'loc' in sd_config else math.log(self.sigma_data) + scale = sd_config['scale'] if 'scale' in sd_config else 0.5 + min_value = sd_config['min_value'] if 'min_value' in sd_config else self.sigma_min + max_value = sd_config['max_value'] if 'max_value' in sd_config else self.sigma_max + return partial(utils.rand_log_logistic, loc=loc, scale=scale, min_value=min_value, max_value=max_value) + + if self.sigma_sample_density_type == 'loguniform': + min_value = sd_config['min_value'] if 'min_value' in sd_config else self.sigma_min + max_value = sd_config['max_value'] if 'max_value' in sd_config else self.sigma_max + return partial(utils.rand_log_uniform, min_value=min_value, max_value=max_value) + + if self.sigma_sample_density_type == 'uniform': + return partial(utils.rand_uniform, min_value=self.sigma_min, max_value=self.sigma_max) + + if self.sigma_sample_density_type == 'v-diffusion': + min_value = self.min_value if 'min_value' in sd_config else self.sigma_min + max_value = sd_config['max_value'] if 'max_value' in sd_config else self.sigma_max + return partial(utils.rand_v_diffusion, sigma_data=self.sigma_data, min_value=min_value, max_value=max_value) + if self.sigma_sample_density_type == 'discrete': + sigmas = self.get_noise_schedule(self.num_sampling_steps * 1e5, 'exponential') + return partial(utils.rand_discrete, values=sigmas) + if self.sigma_sample_density_type == 'split-lognormal': + loc = sd_config['mean'] if 'mean' in sd_config else sd_config['loc'] + scale_1 = sd_config['std_1'] if 'std_1' in sd_config else sd_config['scale_1'] + scale_2 = sd_config['std_2'] if 'std_2' in sd_config else sd_config['scale_2'] + return partial(utils.rand_split_log_normal, loc=loc, scale_1=scale_1, scale_2=scale_2) + else: + raise ValueError('Unknown sample density type') + + def sample_loop( + self, + sigmas, + x_t: torch.Tensor, + state: torch.Tensor, + goal: torch.Tensor, + latent_plan: torch.Tensor, + sampler_type: str, + extra_args={}, + ): + """ + Main method to generate samples depending on the chosen sampler type. DDIM is the default as it works well in all settings. + """ + s_churn = extra_args['s_churn'] if 's_churn' in extra_args else 0 + s_min = extra_args['s_min'] if 's_min' in extra_args else 0 + use_scaler = extra_args['use_scaler'] if 'use_scaler' in extra_args else False + keys = ['s_churn', 'keep_last_actions'] + if bool(extra_args): + reduced_args = {x: extra_args[x] for x in keys} + else: + reduced_args = {} + if use_scaler: + scaler = self.scaler + else: + scaler = None + # ODE deterministic + if sampler_type == 'lms': + x_0 = sample_lms(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True, extra_args=reduced_args) + # ODE deterministic can be made stochastic by S_churn != 0 + elif sampler_type == 'heun': + x_0 = sample_heun(self.model, state, x_t, goal, sigmas, scaler=scaler, s_churn=s_churn, s_tmin=s_min, + disable=True) + # ODE deterministic + elif sampler_type == 'euler': + x_0 = sample_euler(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # SDE stochastic + elif sampler_type == 'ancestral': + x_0 = sample_dpm_2_ancestral(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # SDE stochastic: combines an ODE euler step with an stochastic noise correcting step + elif sampler_type == 'euler_ancestral': + x_0 = sample_euler_ancestral(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # ODE deterministic + elif sampler_type == 'dpm': + x_0 = sample_dpm_2(self.model, state, x_t, goal, sigmas, disable=True) + # ODE deterministic + elif sampler_type == 'dpm_adaptive': + x_0 = sample_dpm_adaptive(self.model, state, x_t, goal, sigmas[-2].item(), sigmas[0].item(), disable=True) + # ODE deterministic + elif sampler_type == 'dpm_fast': + x_0 = sample_dpm_fast(self.model, state, x_t, goal, sigmas[-2].item(), sigmas[0].item(), len(sigmas), + disable=True) + # 2nd order solver + elif sampler_type == 'dpmpp_2s_ancestral': + x_0 = sample_dpmpp_2s_ancestral(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + # 2nd order solver + elif sampler_type == 'dpmpp_2m': + x_0 = sample_dpmpp_2m(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'dpmpp_2m_sde': + x_0 = sample_dpmpp_sde(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'ddim': + x_0 = sample_ddim(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'dpmpp_2s': + x_0 = sample_dpmpp_2s(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + elif sampler_type == 'dpmpp_2_with_lms': + x_0 = sample_dpmpp_2_with_lms(self.model, state, x_t, goal, sigmas, scaler=scaler, disable=True) + else: + raise ValueError('desired sampler type not found!') + return x_0 + + def get_noise_schedule(self, n_sampling_steps, noise_schedule_type): + """ + Get the noise schedule for the sampling steps. Describes the distribution over the noise levels from sigma_min to sigma_max. + """ + if noise_schedule_type == 'karras': + return get_sigmas_karras(n_sampling_steps, self.sigma_min, self.sigma_max, 7, + self.device) # rho=7 is the default from EDM karras + elif noise_schedule_type == 'exponential': + return get_sigmas_exponential(n_sampling_steps, self.sigma_min, self.sigma_max, self.device) + elif noise_schedule_type == 'vp': + return get_sigmas_vp(n_sampling_steps, device=self.device) + elif noise_schedule_type == 'linear': + return get_sigmas_linear(n_sampling_steps, self.sigma_min, self.sigma_max, device=self.device) + elif noise_schedule_type == 'cosine_beta': + return cosine_beta_schedule(n_sampling_steps, device=self.device) + elif noise_schedule_type == 've': + return get_sigmas_ve(n_sampling_steps, self.sigma_min, self.sigma_max, device=self.device) + elif noise_schedule_type == 'iddpm': + return get_iddpm_sigmas(n_sampling_steps, self.sigma_min, self.sigma_max, device=self.device) + raise ValueError('Unknown noise schedule type') + + def reset(self): + """ + Call this at the beginning of a new rollout when doing inference. + """ + self.plan = None + self.latent_goal = None + self.rollout_step_counter = 0 + + def forward(self,batch, xhand=False, xbot=False): + if xhand: + return self.training_step_xhand(batch) + elif xbot: + return self.training_step_xbot(batch) + else: + return self.training_step(batch) + + + def eval_forward(self, obs, goal, xhand=False, xbot=False): + """ + Method for doing inference with the model. + """ + if 'lang_text' in goal: + assert self.use_text_not_embedding == True + if self.use_text_not_embedding: + inputs = self.tokenizer(text=goal["lang_text"], padding='max_length', return_tensors="pt",truncation=True).to(self.text_encoder.device) + outputs = self.text_encoder(**inputs) + latent_goal = outputs.text_embeds + + # if self.use_text_not_embedding: + # # print(goal.keys()) + # latent_goal = self.language_goal(goal["lang_text"]) + # latent_goal = latent_goal.to(torch.float32) + # else: + # latent_goal = self.language_goal(goal["lang"]).unsqueeze(0).to(torch.float32).to( + # obs["rgb_obs"]['rgb_static'].device) + + rgb_static = obs["rgb_obs"]['rgb_static'].to(self.device) + rgb_gripper = obs["rgb_obs"]['rgb_gripper'].to(self.device) + if 'rgb_gripper2' in obs["rgb_obs"]: + rgb_gripper2 = obs["rgb_obs"]['rgb_gripper2'].to(self.device) + + language = goal["lang_text"] + batch = rgb_static.shape[0] + + if 'rgb_gripper2' not in obs["rgb_obs"]: + with torch.no_grad(): + input_rgb = torch.cat([rgb_static, rgb_gripper], dim=0) + language = [language] + [language] + print("input_rgb_shape:", input_rgb.shape) + print("language_shape:", len(language)) + perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + self.extract_layer_idx) + # perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + # self.extract_layer_idx, all_layer=self.use_all_layer, + # step_time=1) + print("perceptual_features_shape:", perceptual_features.shape) + perceptual_features = einops.rearrange(perceptual_features, 'b f c h w-> b f c (h w)') + perceptual_features = einops.rearrange(perceptual_features, 'b f c l-> b f l c') + + perceptual_features, gripper_feature = torch.split(perceptual_features, [batch, batch], dim=0) + perceptual_features = torch.cat([perceptual_features, gripper_feature], dim=2) + else: + with torch.no_grad(): + input_rgb = torch.cat([rgb_static, rgb_gripper, rgb_gripper2], dim=0) + language = [language] + [language] + [language] + perceptual_features = self.TVP_encoder(input_rgb, language, self.timestep, + self.extract_layer_idx) + + perceptual_features = einops.rearrange(perceptual_features, 'b f c h w-> b f c (h w)') + perceptual_features = einops.rearrange(perceptual_features, 'b f c l-> b f l c') + + perceptual_features, gripper_feature1, gripper_feature2 = torch.split(perceptual_features, [batch, batch, batch], dim=0) + perceptual_features = torch.cat([perceptual_features, gripper_feature1, gripper_feature2], dim=2) + + perceptual_features = perceptual_features.to(torch.float32) + perceptual_features = self.Video_Former(perceptual_features) + + perceptual_emb = {'state_images': perceptual_features} + + perceptual_emb['modality'] = "lang" + + if 'state_obs' in obs.keys(): + perceptual_emb['state_obs'] = obs['state_obs'].to(self.device) + + act_seq = self.denoise_actions( + torch.zeros_like(latent_goal).to(latent_goal.device), + perceptual_emb, + latent_goal, + inference=True, + ) + return act_seq + + def step(self, obs, goal): + """ + Do one step of inference with the model. THis method handles the action chunking case. + Our model is trained to predict a sequence of actions. + We only compute the sequence once every self.multistep steps. + + Args: + obs (dict): Observation from environment. + goal (dict): Goal as visual observation or embedded language instruction. + + Returns: + Predicted action. + """ + if self.rollout_step_counter % self.multistep == 0: + pred_action_seq = self.eval_forward(obs, goal) + + self.pred_action_seq = pred_action_seq + + current_action = self.pred_action_seq[0, self.rollout_step_counter] + if len(current_action.shape) == 2: + current_action = einops.rearrange(current_action, 'b d -> b 1 d') + self.rollout_step_counter += 1 + if self.rollout_step_counter == self.multistep: + self.rollout_step_counter = 0 + + return current_action + + def step_real(self, obs, goal): + """ + Do one step of inference with the model. THis method handles the action chunking case. + Our model is trained to predict a sequence of actions. + We only compute the sequence once every self.multistep steps. + + Args: + obs (dict): Observation from environment. + goal (dict): Goal as visual observation or embedded language instruction. + + Returns: + Predicted action. + """ + + pred_action_seq = self.eval_forward(obs, goal) + self.pred_action_seq = pred_action_seq + + return pred_action_seq + + def on_train_start(self) -> None: + + self.model.to(dtype=self.dtype) + + self.Video_Former.to(dtype=self.dtype) + self.text_encoder.to(dtype=self.dtype) + #self.vae.to(dtype=self.dtype) + self.TVP_encoder.to(dtype=self.dtype) + + @rank_zero_only + def on_train_epoch_start(self) -> None: + logger.info(f"Start training epoch {self.current_epoch}") + + @rank_zero_only + def on_train_epoch_end(self, unused: Optional = None) -> None: # type: ignore + logger.info(f"Finished training epoch {self.current_epoch}") + + @rank_zero_only + def on_validation_epoch_end(self) -> None: + logger.info(f"Finished validation epoch {self.current_epoch}") + + + def on_validation_epoch_start(self) -> None: + log_rank_0(f"Start validation epoch {self.current_epoch}") + + @rank_zero_only + def on_train_epoch_start(self) -> None: + logger.info(f"Start training epoch {self.current_epoch}") + + @rank_zero_only + def on_train_epoch_end(self, unused: Optional = None) -> None: # type: ignore + logger.info(f"Finished training epoch {self.current_epoch}") + + @rank_zero_only + def on_validation_epoch_end(self) -> None: + logger.info(f"Finished validation epoch {self.current_epoch}") + + def on_validation_epoch_start(self) -> None: + log_rank_0(f"Start validation epoch {self.current_epoch}") + + +@rank_zero_only +def log_rank_0(*args, **kwargs): + # when using ddp, only log with rank 0 process + logger.info(*args, **kwargs) \ No newline at end of file diff --git a/code/policy_models/__init__.py b/code/policy_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/__pycache__/VPP_policy.cpython-310.pyc b/code/policy_models/__pycache__/VPP_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87015f650fc84046ac76349296effe744414f3cf Binary files /dev/null and b/code/policy_models/__pycache__/VPP_policy.cpython-310.pyc differ diff --git a/code/policy_models/__pycache__/__init__.cpython-310.pyc b/code/policy_models/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83c904d5d96939f51be371ed2e379320cb37b8f9 Binary files /dev/null and b/code/policy_models/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/__pycache__/__init__.cpython-39.pyc b/code/policy_models/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..781f728649effca452914f74f1aa53a449dfbe36 Binary files /dev/null and b/code/policy_models/__pycache__/__init__.cpython-39.pyc differ diff --git a/code/policy_models/callbacks/__init__.py b/code/policy_models/callbacks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/callbacks/ema.py b/code/policy_models/callbacks/ema.py new file mode 100644 index 0000000000000000000000000000000000000000..ec275bd0bc76371897894d8b5b65711b785a70b0 --- /dev/null +++ b/code/policy_models/callbacks/ema.py @@ -0,0 +1,211 @@ +# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +# +# 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. +import os.path +import warnings +from typing import Any, Dict, List, Optional +import logging + +import pytorch_lightning as pl +import torch +from pytorch_lightning import Callback +from pytorch_lightning.utilities import rank_zero_warn +from pytorch_lightning.utilities.exceptions import MisconfigurationException +from pytorch_lightning.utilities.types import STEP_OUTPUT + +logger = logging.getLogger(__name__) + +try: + import amp_C + + apex_available = True +except Exception: + apex_available = False + + +class EMA(Callback): + """ + Implements Exponential Moving Averaging (EMA). + When training a model, this callback will maintain moving averages of the trained parameters. + When evaluating, we use the moving averages copy of the trained parameters. + When saving, we save an additional set of parameters with the prefix `ema`. + Args: + decay: The exponential decay used when calculating the moving average. Has to be between 0-1. + apply_ema_every_n_steps: Apply EMA every n global steps. + start_step: Start applying EMA from ``start_step`` global step onwards. + evaluate_ema_weights_instead: Validate the EMA weights instead of the original weights. + Note this means that when saving the model, the validation metrics are calculated with the EMA weights. + save_ema_weights_in_callback_state: Enable saving ema weights in callback state. + This is not required when using NeMo as the experiment manager handles saving weights. + """ + + def __init__( + self, + decay: float, + apply_ema_every_n_steps: int = 1, + start_step: int = 0, + save_ema_weights_in_callback_state: bool = False, + evaluate_ema_weights_instead: bool = False, + inv_gamma: float = 1.0, + power: float = 2 / 3, + min_value: float = 0.0, + max_value: float = 0.9999, + ): + if not apex_available: + rank_zero_warn( + "EMA has better performance when Apex is installed: https://github.com/NVIDIA/apex#installation." + ) + if not (0 <= decay <= 1): + raise MisconfigurationException("EMA decay value must be between 0 and 1") + self._ema_model_weights: Optional[List[torch.Tensor]] = None + self._overflow_buf: Optional[torch.Tensor] = None + self._cur_step: Optional[int] = None + self._weights_buffer: Optional[List[torch.Tensor]] = None + self.apply_ema_every_n_steps = apply_ema_every_n_steps + self.start_step = start_step + self.save_ema_weights_in_callback_state = save_ema_weights_in_callback_state + self.evaluate_ema_weights_instead = evaluate_ema_weights_instead + self.decay = decay + self.inv_gamma = inv_gamma + self.power = power + self.min_value = min_value + self.max_value = max_value + + def get_decay(self, optimization_step): + step = max(0, optimization_step - self.start_step - 1) + value = 1 - (1 + step / self.inv_gamma) ** -self.power + + # clamp the value between min_value and max_value + value = max(min(value, self.max_value), self.min_value) + + return value + + def on_train_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + logging.info('Creating EMA weights copy.') + if self._ema_model_weights is None: + self._ema_model_weights = [p.detach().clone() for p in pl_module.state_dict().values()] + # ensure that all the weights are on the correct device + self._ema_model_weights = [p.to(pl_module.device) for p in self._ema_model_weights] + self._overflow_buf = torch.IntTensor([0]).to(pl_module.device) + + def ema(self, pl_module: "pl.LightningModule") -> None: + if apex_available and pl_module.device.type == "cuda": + return self.apply_multi_tensor_ema(pl_module) + return self.apply_ema(pl_module) + + def apply_multi_tensor_ema(self, pl_module: "pl.LightningModule") -> None: + model_weights = list(pl_module.state_dict().values()) + amp_C.multi_tensor_axpby( + 65536, # todo (sean): chunk size, should we expose? + self._overflow_buf, + [self._ema_model_weights, model_weights, self._ema_model_weights], + self.decay, + 1 - self.decay, + -1, + ) + + def apply_ema(self, pl_module: "pl.LightningModule") -> None: + decay = self.get_decay(self._cur_step) + for orig_weight, ema_weight in zip(list(pl_module.state_dict().values()), self._ema_model_weights): + if orig_weight.dtype == torch.uint8 or orig_weight.dtype == torch.int64: + ema_weight.data = orig_weight.data.clone() + else: + diff = ema_weight.data - orig_weight.data + diff.mul_(1.0 - decay) + ema_weight.sub_(diff) + self.log("train/ema_rate", decay, on_step=True, on_epoch=False, prog_bar=True) + + def should_apply_ema(self, step: int) -> bool: + return step != self._cur_step and step >= self.start_step and step % self.apply_ema_every_n_steps == 0 + + def on_train_batch_end( + self, + trainer: "pl.Trainer", + pl_module: "pl.LightningModule", + outputs: STEP_OUTPUT, + batch: Any, + batch_idx: int, + # dataloader_idx: int, + ) -> None: + if self.should_apply_ema(trainer.global_step): + self._cur_step = trainer.global_step + self.ema(pl_module) + + def state_dict(self) -> Dict[str, Any]: + if self.save_ema_weights_in_callback_state: + return dict(cur_step=self._cur_step, ema_weights=self._ema_model_weights) + return dict(cur_step=self._cur_step) + + def load_state_dict(self, state_dict: Dict[str, Any]) -> None: + self._cur_step = state_dict['cur_step'] + # when loading using NeMo, ema weights will be loaded by the experiment manager separately. + if self._ema_model_weights is None: + self._ema_model_weights = state_dict.get('ema_weights') + + def on_load_checkpoint( + self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", checkpoint: Dict[str, Any] + ) -> None: + checkpoint_callback = trainer.checkpoint_callback + + if trainer.ckpt_path and checkpoint_callback is not None and 'NeMo' in type(checkpoint_callback).__name__: + ext = checkpoint_callback.FILE_EXTENSION + if trainer.ckpt_path.endswith(f'-EMA{ext}'): + logging.info( + "loading EMA based weights. " + "The callback will treat the loaded EMA weights as the main weights" + " and create a new EMA copy when training." + ) + return + ema_path = trainer.ckpt_path.replace(ext, f'-EMA{ext}') + if os.path.exists(ema_path): + ema_state_dict = torch.load(ema_path, map_location=torch.device('cpu')) + self._ema_model_weights = ema_state_dict['state_dict'].values() + del ema_state_dict + logging.info("EMA weights have been loaded successfully. Continuing training with saved EMA weights.") + else: + warnings.warn( + "we were unable to find the associated EMA weights when re-loading, " + "training will start with new EMA weights.", + UserWarning, + ) + + def replace_model_weights(self, pl_module: "pl.LightningModule") -> None: + self._weights_buffer = [p.detach().clone().to('cpu') for p in pl_module.state_dict().values()] + new_state_dict = {k: v for k, v in zip(pl_module.state_dict().keys(), self._ema_model_weights)} + pl_module.load_state_dict(new_state_dict) + + def restore_original_weights(self, pl_module: "pl.LightningModule") -> None: + state_dict = pl_module.state_dict() + new_state_dict = {k: v for k, v in zip(state_dict.keys(), self._weights_buffer)} + pl_module.load_state_dict(new_state_dict) + del self._weights_buffer + + @property + def ema_initialized(self) -> bool: + return self._ema_model_weights is not None + + def on_validation_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + if self.ema_initialized and self.evaluate_ema_weights_instead: + self.replace_model_weights(pl_module) + + def on_validation_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + if self.ema_initialized and self.evaluate_ema_weights_instead: + self.restore_original_weights(pl_module) + + def on_test_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + if self.ema_initialized and self.evaluate_ema_weights_instead: + self.replace_model_weights(pl_module) + + def on_test_end(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None: + if self.ema_initialized and self.evaluate_ema_weights_instead: + self.restore_original_weights(pl_module) \ No newline at end of file diff --git a/code/policy_models/datasets/__pycache__/base_dataset.cpython-310.pyc b/code/policy_models/datasets/__pycache__/base_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..446534bfc4b60e96a6839d1a0cf8f69706c0ff38 Binary files /dev/null and b/code/policy_models/datasets/__pycache__/base_dataset.cpython-310.pyc differ diff --git a/code/policy_models/datasets/__pycache__/disk_dataset.cpython-310.pyc b/code/policy_models/datasets/__pycache__/disk_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ed2036d09db6f3a240028f94ceed87589bda1f1 Binary files /dev/null and b/code/policy_models/datasets/__pycache__/disk_dataset.cpython-310.pyc differ diff --git a/code/policy_models/datasets/__pycache__/hulc_data_module.cpython-310.pyc b/code/policy_models/datasets/__pycache__/hulc_data_module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12279e7d2414d94a60ce54d40219165b5842c39d Binary files /dev/null and b/code/policy_models/datasets/__pycache__/hulc_data_module.cpython-310.pyc differ diff --git a/code/policy_models/datasets/__pycache__/shm_dataset.cpython-310.pyc b/code/policy_models/datasets/__pycache__/shm_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..011c432c7e2758caaf64e5da276a1dd7d599c39f Binary files /dev/null and b/code/policy_models/datasets/__pycache__/shm_dataset.cpython-310.pyc differ diff --git a/code/policy_models/datasets/base_dataset.py b/code/policy_models/datasets/base_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..024f19bb7551b9577dc7e8e5075c48b2057c59a0 --- /dev/null +++ b/code/policy_models/datasets/base_dataset.py @@ -0,0 +1,296 @@ +import logging +from pathlib import Path +from typing import Dict, Tuple, Union + +import numpy as np +from omegaconf import DictConfig +import pyhash +import torch +from torch.utils.data import Dataset + +from policy_models.datasets.utils.episode_utils import ( + get_state_info_dict, + process_actions, + process_depth, + process_language, + process_rgb, + process_state, +) + +hasher = pyhash.fnv1_32() +logger = logging.getLogger(__name__) + + +def get_validation_window_size(idx: int, min_window_size: int, max_window_size: int) -> int: + """ + In validation step, use hash function instead of random sampling for consistent window sizes across epochs. + + Args: + idx: Sequence index. + min_window_size: Minimum window size. + max_window_size: Maximum window size. + + Returns: + Window size computed with hash function. + """ + window_range = max_window_size - min_window_size + 1 + return min_window_size + hasher(str(idx)) % window_range + + +class BaseDataset(Dataset): + """ + Abstract dataset base class. + + Args: + datasets_dir: Path of folder containing episode files (string must contain 'validation' or 'training'). + obs_space: DictConfig of observation space. + proprio_state: DictConfig with shape of prioprioceptive state. + key: 'vis' or 'lang'. + lang_folder: Name of the subdirectory of the dataset containing the language annotations. + num_workers: Number of dataloading workers for this dataset. + transforms: Dict with pytorch data transforms. + batch_size: Batch size. + min_window_size: Minimum window length of loaded sequences. + max_window_size: Maximum window length of loaded sequences. + pad: If True, repeat last frame such that all sequences have length 'max_window_size'. + aux_lang_loss_window: How many sliding windows to consider for auxiliary language losses, counted from the end + of an annotated language episode. + """ + + def __init__( + self, + datasets_dir: Path, + obs_space: DictConfig, + proprio_state: DictConfig, + key: str, + lang_folder: str, + num_workers: int, + transforms: Dict = {}, + batch_size: int = 32, + min_window_size: int = 16, + max_window_size: int = 32, + pad: bool = True, + aux_lang_loss_window: int = 1, + window_sampling_strategy: str = 'random', + geometric_p_value: float = 0.1, + ): + self.observation_space = obs_space + self.proprio_state = proprio_state + self.transforms = transforms + self.with_lang = key == "lang" + self.relative_actions = "rel_actions" in self.observation_space["actions"] + assert window_sampling_strategy in ('random', 'geometric') + self.window_sampling_strategy = window_sampling_strategy + self.geometric_p_value = geometric_p_value # only needed for geomtric sampling + self.pad = pad + self.batch_size = batch_size + self.num_workers = num_workers + self.min_window_size = min_window_size + self.max_window_size = max_window_size + self.abs_datasets_dir = datasets_dir + self.lang_folder = lang_folder # if self.with_lang else None + self.aux_lang_loss_window = aux_lang_loss_window + assert "validation" in self.abs_datasets_dir.as_posix() or "training" in self.abs_datasets_dir.as_posix() + self.validation = "validation" in self.abs_datasets_dir.as_posix() + assert self.abs_datasets_dir.is_dir() + logger.info(f"loading dataset at {self.abs_datasets_dir}") + logger.info("finished loading dataset") + + def __getitem__(self, idx: Union[int, Tuple[int, int]]) -> Dict: + """ + Get sequence of dataset. + + Args: + idx: Index of the sequence. + + Returns: + Loaded sequence. + """ + if isinstance(idx, int): + # When max_ws_size and min_ws_size are equal, avoid unnecessary padding + # acts like Constant dataset. Currently, used for language data + if self.min_window_size == self.max_window_size: + window_size = self.max_window_size + elif self.min_window_size < self.max_window_size: + window_size = self._get_window_size(idx) + else: + logger.error(f"min_window_size {self.min_window_size} > max_window_size {self.max_window_size}") + raise ValueError + else: + idx, window_size = idx + sequence = self._get_sequences(idx, window_size) + if self.pad: + pad_size = self._get_pad_size(sequence) + sequence = self._pad_sequence(sequence, pad_size) + return sequence + + def _get_sequences(self, idx: int, window_size: int) -> Dict: + """ + Load sequence of length window_size. + + Args: + idx: Index of starting frame. + window_size: Length of sampled episode. + + Returns: + dict: Dictionary of tensors of loaded sequence with different input modalities and actions. + """ + + episode = self._load_episode(idx, window_size) + + seq_state_obs = process_state(episode, self.observation_space, self.transforms, self.proprio_state) + seq_rgb_obs = process_rgb(episode, self.observation_space, self.transforms) + #seq_depth_obs = process_depth(episode, self.observation_space, self.transforms) + seq_acts = process_actions(episode, self.observation_space, self.transforms) + info = get_state_info_dict(episode) + seq_lang = process_language(episode, self.transforms, self.with_lang) + info = self._add_language_info(info, idx) + seq_dict = {**seq_state_obs, **seq_rgb_obs, **seq_acts, **info, **seq_lang} # type:ignore + seq_dict["idx"] = idx # type:ignore + return seq_dict + + def _load_episode(self, idx: int, window_size: int) -> Dict[str, np.ndarray]: + raise NotImplementedError + + def _get_window_size(self, idx: int) -> int: + """ + Sample a window size taking into account the episode limits. + + Args: + idx: Index of the sequence to load. + + Returns: + Window size. + """ + window_diff = self.max_window_size - self.min_window_size + if len(self.episode_lookup) <= idx + window_diff: + # last episode + max_window = self.min_window_size + len(self.episode_lookup) - idx - 1 + elif self.episode_lookup[idx + window_diff] != self.episode_lookup[idx] + window_diff: + # less than max_episode steps until next episode + steps_to_next_episode = int( + np.nonzero( + self.episode_lookup[idx : idx + window_diff + 1] + - (self.episode_lookup[idx] + np.arange(window_diff + 1)) + )[0][0] + ) + max_window = min(self.max_window_size, (self.min_window_size + steps_to_next_episode - 1)) + else: + max_window = self.max_window_size + + if self.validation: + # in validation step, repeat the window sizes for each epoch. + return get_validation_window_size(idx, self.min_window_size, max_window) + else: + if self.window_sampling_strategy == 'geometric': + p = self.geometric_p_value # Choose a suitable value for p + while True: + sampled_window_size = 1 + np.random.geometric(p) + if self.min_window_size <= sampled_window_size <= max_window: + return sampled_window_size + else: + return np.random.randint(self.min_window_size, max_window + 1) + + def __len__(self) -> int: + """ + Returns: + Size of the dataset. + """ + return len(self.episode_lookup) + + def _get_pad_size(self, sequence: Dict) -> int: + """ + Determine how many frames to append to end of the sequence + + Args: + sequence: Loaded sequence. + + Returns: + Number of frames to pad. + """ + return self.max_window_size - len(sequence["actions"]) + + def _pad_sequence(self, seq: Dict, pad_size: int) -> Dict: + """ + Pad a sequence by repeating the last frame. + + Args: + seq: Sequence to pad. + pad_size: Number of frames to pad. + + Returns: + Padded sequence. + """ + seq.update({"robot_obs": self._pad_with_repetition(seq["robot_obs"], pad_size)}) + seq.update({"rgb_obs": {k: self._pad_with_repetition(v, pad_size) for k, v in seq["rgb_obs"].items()}}) + seq.update({"depth_obs": {k: self._pad_with_repetition(v, pad_size) for k, v in seq["depth_obs"].items()}}) + # todo: find better way of distinguishing rk and play action spaces + if not self.relative_actions: + # repeat action for world coordinates action space + seq.update({"actions": self._pad_with_repetition(seq["actions"], pad_size)}) + else: + # for relative actions zero pad all but the last action dims and repeat last action dim (gripper action) + seq_acts = torch.cat( + [ + self._pad_with_zeros(seq["actions"][..., :-1], pad_size), + self._pad_with_repetition(seq["actions"][..., -1:], pad_size), + ], + dim=-1, + ) + seq.update({"actions": seq_acts}) + seq.update({"state_info": {k: self._pad_with_repetition(v, pad_size) for k, v in seq["state_info"].items()}}) + return seq + + @staticmethod + def _pad_with_repetition(input_tensor: torch.Tensor, pad_size: int) -> torch.Tensor: + """ + Pad a sequence Tensor by repeating last element pad_size times. + + Args: + input_tensor: Sequence to pad. + pad_size: Number of frames to pad. + + Returns: + Padded Tensor. + """ + last_repeated = torch.repeat_interleave(torch.unsqueeze(input_tensor[-1], dim=0), repeats=pad_size, dim=0) + padded = torch.vstack((input_tensor, last_repeated)) + return padded + + @staticmethod + def _pad_with_zeros(input_tensor: torch.Tensor, pad_size: int) -> torch.Tensor: + """ + Pad a Tensor with zeros. + + Args: + input_tensor: Sequence to pad. + pad_size: Number of frames to pad. + + Returns: + Padded Tensor. + """ + zeros_repeated = torch.repeat_interleave( + torch.unsqueeze(torch.zeros(input_tensor.shape[-1]), dim=0), repeats=pad_size, dim=0 + ) + padded = torch.vstack((input_tensor, zeros_repeated)) + return padded + + def _add_language_info(self, info: Dict, idx: int) -> Dict: + """ + If dataset contains language, add info to determine if this sequence will be used for the auxiliary losses. + + Args: + info: Info dictionary. + idx: Sequence index. + + Returns: + Info dictionary with updated information. + """ + if not self.with_lang: + return info + use_for_aux_lang_loss = ( + idx + self.aux_lang_loss_window >= len(self.lang_lookup) + or self.lang_lookup[idx] < self.lang_lookup[idx + self.aux_lang_loss_window] + ) + info["use_for_aux_lang_loss"] = use_for_aux_lang_loss + return info diff --git a/code/policy_models/datasets/disk_dataset.py b/code/policy_models/datasets/disk_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..37e7e09992aed2786629ebd8e73497ab292a2fa3 --- /dev/null +++ b/code/policy_models/datasets/disk_dataset.py @@ -0,0 +1,280 @@ +import os.path +from itertools import chain +import logging +from pathlib import Path +import pickle +from typing import Any, Dict, List, Tuple +import random + +from concurrent.futures import ThreadPoolExecutor, as_completed +import concurrent.futures +import numpy as np + +from policy_models.datasets.base_dataset import BaseDataset +from policy_models.datasets.utils.episode_utils import lookup_naming_pattern + +logger = logging.getLogger(__name__) + + +def load_pkl(filename: Path) -> Dict[str, np.ndarray]: + with open(filename, "rb") as f: + return pickle.load(f) + + +def load_npz(filename: Path) -> Dict[str, np.ndarray]: + return np.load(filename.as_posix()) + + +class DiskDataset(BaseDataset): + """ + Dataset that loads episodes as individual files from disk. + + Args: + skip_frames: Skip this amount of windows for language dataset. + save_format: File format in datasets_dir (pkl or npz). + pretrain: Set to True when pretraining. + """ + + def __init__( + self, + *args: Any, + skip_frames: int = 1, + save_format: str = "npz", + pretrain: bool = False, + **kwargs: Any, + ): + super().__init__(*args, **kwargs) + self.save_format = save_format + if self.save_format == "pkl": + self.load_file = load_pkl + elif self.save_format == "npz": + self.load_file = load_npz + else: + raise NotImplementedError + self.pretrain = pretrain + self.skip_frames = skip_frames + + if self.with_lang: + self.episode_lookup, self.lang_lookup, self.lang_ann, self.lang_text = self._build_file_indices_lang(self.abs_datasets_dir) + else: + self.episode_lookup = self._build_file_indices(self.abs_datasets_dir) + + self.naming_pattern, self.n_digits = lookup_naming_pattern(self.abs_datasets_dir, self.save_format) + + def _get_episode_name(self, file_idx: int) -> Path: + """ + Convert file idx to file path. + + Args: + file_idx: index of starting frame. + + Returns: + Path to file. + """ + return Path(f"{self.naming_pattern[0]}{file_idx:0{self.n_digits}d}{self.naming_pattern[1]}") + + def _load_episode(self, idx: int, window_size: int) -> Dict[str, np.ndarray]: + """ + Load consecutive frames saved as individual files on disk and combine to episode dict. + + Args: + idx: Index of first frame. + window_size: Length of sampled episode. + + Returns: + episode: Dict of numpy arrays containing the episode where keys are the names of modalities. + """ + start_idx = self.episode_lookup[idx] + end_idx = start_idx + window_size + keys = list(chain(*self.observation_space.values())) + keys.remove("language") + keys.append("scene_obs") + episodes = [self.load_file(self._get_episode_name(file_idx)) for file_idx in range(start_idx, end_idx)] + episode = {key: np.stack([ep[key] for ep in episodes]) for key in keys} + if self.with_lang: + episode["language"] = self.lang_ann[self.lang_lookup[idx]][0] # TODO check [0] + return episode + + def _build_file_indices_lang(self, abs_datasets_dir: Path) -> Tuple[np.ndarray, List, np.ndarray]: + """ + This method builds the mapping from index to file_name used for loading the episodes of the language dataset. + + Args: + abs_datasets_dir: Absolute path of the directory containing the dataset. + + Returns: + episode_lookup: Mapping from training example index to episode (file) index. + lang_lookup: Mapping from training example to index of language instruction. + lang_ann: Language embeddings. + """ + assert abs_datasets_dir.is_dir() + + episode_lookup = [] + + try: + print("trying to load lang data from: ", abs_datasets_dir / self.lang_folder / "auto_lang_ann.npy") + lang_data = np.load(abs_datasets_dir / self.lang_folder / "auto_lang_ann.npy", allow_pickle=True).item() + except Exception: + print("Exception, trying to load lang data from: ", abs_datasets_dir / "auto_lang_ann.npy") + lang_data = np.load(abs_datasets_dir / "auto_lang_ann.npy", allow_pickle=True).item() + + ep_start_end_ids = lang_data["info"]["indx"] # each of them are 64 + lang_ann = lang_data["language"]["emb"] # length total number of annotations + lang_text = lang_data["language"]["ann"] # length total number of annotations + lang_lookup = [] + for i, (start_idx, end_idx) in enumerate(ep_start_end_ids): + if self.pretrain: + start_idx = max(start_idx, end_idx + 1 - self.min_window_size - self.aux_lang_loss_window) + assert end_idx >= self.max_window_size + cnt = 0 + for idx in range(start_idx, end_idx + 1 - self.min_window_size): + if cnt % self.skip_frames == 0: + lang_lookup.append(i) + episode_lookup.append(idx) + cnt += 1 + + return np.array(episode_lookup), lang_lookup, lang_ann, lang_text + + def _build_file_indices(self, abs_datasets_dir: Path) -> np.ndarray: + """ + This method builds the mapping from index to file_name used for loading the episodes of the non language + dataset. + + Args: + abs_datasets_dir: Absolute path of the directory containing the dataset. + + Returns: + episode_lookup: Mapping from training example index to episode (file) index. + """ + assert abs_datasets_dir.is_dir() + + episode_lookup = [] + ep_start_end_ids = np.load(abs_datasets_dir / "ep_start_end_ids.npy") + logger.info(f'Found "ep_start_end_ids.npy" with {len(ep_start_end_ids)} episodes.') + for start_idx, end_idx in ep_start_end_ids: + assert end_idx > self.max_window_size + for idx in range(start_idx, end_idx + 1 - self.min_window_size): + episode_lookup.append(idx) + return np.array(episode_lookup) + + +class ExtendedDiskDataset(DiskDataset): + def __init__( + self, + *args: Any, + obs_seq_len: int, + action_seq_len: int, + future_range: int, + img_gen_frame_diff: int = 3, + **kwargs: Any, + ): + super().__init__(*args, **kwargs) + self.obs_seq_len = obs_seq_len + self.action_seq_len = action_seq_len + self.future_range = future_range # Number of steps into the future to sample goals + self.ep_start_end_ids = np.load(self.abs_datasets_dir / "ep_start_end_ids.npy") # Load sequence boundaries + self.img_gen_frame_diff = img_gen_frame_diff + self.random_frame_diff = False if img_gen_frame_diff > -1 else True + # self.min_window_size = self.action_seq_len + # self.max_window_size = self.action_seq_len + self.future_range + + def find_sequence_boundaries(self, idx: int) -> Tuple[int, int]: + for start_idx, end_idx in self.ep_start_end_ids: + if start_idx <= idx < end_idx: + return start_idx, end_idx + raise ValueError(f"Index {idx} does not belong to any sequence.") + + def _load_episode(self, idx: int, window_size: int) -> Dict[str, np.ndarray]: + """ + Load consecutive frames saved as individual files on disk and combine to episode dict. + + Args: + idx: Index of first frame. + window_size: Length of sampled episode. + + Returns: + episode: Dict of numpy arrays containing the episode where keys are the names of modalities. + """ + start_idx = self.episode_lookup[idx] + end_idx = start_idx + self.action_seq_len + self.obs_seq_len-1 + keys = list(chain(*self.observation_space.values())) + keys.remove("language") + keys.append("scene_obs") + episodes = [self.load_file(self._get_episode_name(file_idx)) for file_idx in range(start_idx, end_idx)] + + episode = {} + for key in keys: + if 'gen' in key: + continue + stacked_data = np.stack([ep[key] for ep in episodes]) + if key == "rel_actions" or key == 'actions': + episode[key] = stacked_data[(self.obs_seq_len-1):((self.obs_seq_len-1) + self.action_seq_len), :] + else: + episode[key] = stacked_data[:self.obs_seq_len, :] + + if self.with_lang: + episode["language"] = self.lang_ann[self.lang_lookup[idx]][0] # TODO check [0] + episode["language_text"] = self.lang_text[self.lang_lookup[idx]] #[0] # TODO check [0] + + # get the random future state as goal + # goal_idx = end_idx + window_size + # # print(start_idx, end_idx, goal_idx) + # eps_start_idx, eps_end_idx = self.find_sequence_boundaries(end_idx) + # + # # Check if future goal can be sampled + # + # if eps_end_idx < goal_idx: + # goal_idx = eps_end_idx + + # goal_episodes = self.load_file(self._get_episode_name(goal_idx)) + # goal_episode = {} + # for key in keys: + # if 'gen' in key: + # continue + # goal_stacked_data = np.stack([goal_episodes[key]]) + # if key == "rel_actions" or key == 'actions': + # pass + # else: + # goal_episode[key] = goal_stacked_data[:self.obs_seq_len, :] + # # store for merging + # + # episode = self.merge_episodes(episode, goal_episode) + return episode + + + def merge_episodes(self, episode1: Dict[str, np.ndarray], episode2: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]: + merged_episode = {} + all_keys = set(episode1.keys()).union(set(episode2.keys())) + for key in all_keys: + if key in episode1 and key in episode2: + # Merge logic here, for example: + merged_episode[key] = np.concatenate([episode1[key], episode2[key]], axis=0) + elif key in episode1: + merged_episode[key] = episode1[key] + else: + merged_episode[key] = episode2[key] + return merged_episode + + def _build_file_indices(self, abs_datasets_dir: Path) -> np.ndarray: + """ + This method builds the mapping from index to file_name used for loading the episodes of the non language + dataset. + + Args: + abs_datasets_dir: Absolute path of the directory containing the dataset. + + Returns: + episode_lookup: Mapping from training example index to episode (file) index. + """ + assert abs_datasets_dir.is_dir() + + episode_lookup = [] + + ep_start_end_ids = np.load(abs_datasets_dir / "ep_start_end_ids.npy") + logger.info(f'Found "ep_start_end_ids.npy" with {len(ep_start_end_ids)} episodes.') + for start_idx, end_idx in ep_start_end_ids: + assert end_idx > self.max_window_size + for idx in range(start_idx, end_idx + 1 - self.min_window_size): + episode_lookup.append(idx) + return np.array(episode_lookup) + diff --git a/code/policy_models/datasets/hulc_data_module.py b/code/policy_models/datasets/hulc_data_module.py new file mode 100644 index 0000000000000000000000000000000000000000..458af7bd75a565b002f89feec844cffbf1f09744 --- /dev/null +++ b/code/policy_models/datasets/hulc_data_module.py @@ -0,0 +1,160 @@ +import logging +import os +from pathlib import Path +from typing import Dict, List + +import hydra +import numpy as np +from omegaconf import DictConfig, OmegaConf + +from torch.utils.data import DataLoader +import torchvision +import pytorch_lightning as pl + +import policy_models +from policy_models.datasets.utils.episode_utils import load_dataset_statistics +from policy_models.datasets.utils.shared_memory_utils import load_shm_lookup, save_shm_lookup, SharedMemoryLoader + +logger = logging.getLogger(__name__) +DEFAULT_TRANSFORM = OmegaConf.create({"train": None, "val": None}) +ONE_EP_DATASET_URL = "http://www.informatik.uni-freiburg.de/~meeso/50steps.tar.xz" + + +class HulcDataModule(pl.LightningDataModule): + def __init__( + self, + datasets: DictConfig, + root_data_dir: str = "data", + num_workers: int = 8, + transforms: DictConfig = DEFAULT_TRANSFORM, + shuffle_val: bool = False, + **kwargs: Dict, + ): + super().__init__() + self.datasets_cfg = datasets + self.train_datasets = None + self.val_datasets = None + self.train_sampler = None + self.val_sampler = None + self.num_workers = num_workers + root_data_path = Path(root_data_dir) + if not root_data_path.is_absolute(): + root_data_path = Path(policy_models.__file__).parent / root_data_path + self.training_dir = root_data_path / "training" + self.val_dir = root_data_path / "validation" + self.shuffle_val = shuffle_val + self.modalities: List[str] = [] + self.transforms = transforms + self.use_shm = False + + #if 'lang_dataset' in self.datasets_cfg: + # if "shm_dataset" in self.datasets_cfg.lang_dataset._target_: + # self.use_shm = "shm_dataset" in self.datasets_cfg.lang_dataset._target_ + # else: + # self.use_shm = False + #elif 'shm_dataset' in self.datasets_cfg.vision_dataset._target_: + # self.use_shm = True + #else: + # self.use_shm = False + + def prepare_data(self, *args, **kwargs): + # check if files already exist + dataset_exist = np.any([len(list(self.training_dir.glob(extension))) for extension in ["*.npz", "*.pkl"]]) + + # download and unpack images + if not dataset_exist: + if "CI" not in os.environ: + print(f"No dataset found in {self.training_dir}.") + print("For information how to download to full CALVIN dataset, please visit") + print("https://github.com/mees/calvin/tree/main/dataset") + print("Do you wish to download small debug dataset to continue training?") + s = input("YES / no") + if s == "no": + exit() + logger.info(f"downloading dataset to {self.training_dir} and {self.val_dir}") + torchvision.datasets.utils.download_and_extract_archive(ONE_EP_DATASET_URL, self.training_dir) + torchvision.datasets.utils.download_and_extract_archive(ONE_EP_DATASET_URL, self.val_dir) + + # if self.use_shm: + # # When using shared memory dataset, initialize lookups + # train_shmem_loader = SharedMemoryLoader(self.datasets_cfg, self.training_dir) + # train_shm_lookup = train_shmem_loader.load_data_in_shared_memory() + # + # val_shmem_loader = SharedMemoryLoader(self.datasets_cfg, self.val_dir) + # val_shm_lookup = val_shmem_loader.load_data_in_shared_memory() + # + # save_shm_lookup(train_shm_lookup, val_shm_lookup) + + def setup(self, stage=None): + transforms = load_dataset_statistics(self.training_dir, self.val_dir, self.transforms) + + # self.train_transforms = { + # cam: [hydra.utils.instantiate(transform) for transform in transforms.train[cam]] for cam in transforms.train + #} + self.train_transforms = {} + for cam in transforms.train: + # print("Processing camera:", cam) + cam_transforms = [] + for transform in transforms.train[cam]: + # print("Instantiating transform for camera", cam, ":", transform) + if transform._target_ == "torchvision.transforms.ColorJitter": + instantiated_transform = torchvision.transforms.ColorJitter( + brightness=transform.brightness, + contrast=tuple(transform.contrast), + saturation=tuple(transform.saturation), + ) + else: + instantiated_transform = hydra.utils.instantiate(transform) + cam_transforms.append(instantiated_transform) + self.train_transforms[cam] = cam_transforms + + self.val_transforms = { + cam: [hydra.utils.instantiate(transform) for transform in transforms.val[cam]] for cam in transforms.val + } + self.train_transforms = {key: torchvision.transforms.Compose(val) for key, val in self.train_transforms.items()} + self.val_transforms = {key: torchvision.transforms.Compose(val) for key, val in self.val_transforms.items()} + self.train_datasets, self.train_sampler, self.val_datasets, self.val_sampler = {}, {}, {}, {} + + # if self.use_shm: + # train_shm_lookup, val_shm_lookup = load_shm_lookup() + + for _, dataset in self.datasets_cfg.items(): + if dataset == 'lang_paraphrase-MiniLM-L3-v2': + continue + else: + train_dataset = hydra.utils.instantiate( + dataset, datasets_dir=self.training_dir, transforms=self.train_transforms + ) + val_dataset = hydra.utils.instantiate(dataset, datasets_dir=self.val_dir, transforms=self.val_transforms) + # if self.use_shm: + # train_dataset.setup_shm_lookup(train_shm_lookup) + # val_dataset.setup_shm_lookup(val_shm_lookup) + key = dataset.key + self.train_datasets[key] = train_dataset + self.val_datasets[key] = val_dataset + self.modalities.append(key) + + def train_dataloader(self): + return { + key: DataLoader( + dataset, + batch_size=dataset.batch_size, + num_workers=dataset.num_workers, + pin_memory=True, + shuffle=True, + prefetch_factor=2, + ) + for key, dataset in self.train_datasets.items() + } + + def val_dataloader(self): + return { + key: DataLoader( + dataset, + batch_size=dataset.batch_size, + num_workers=dataset.num_workers, + pin_memory=True, + ) + for key, dataset in self.val_datasets.items() + } + diff --git a/code/policy_models/datasets/mvlibero_dataset.py b/code/policy_models/datasets/mvlibero_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..0e587591a8eaf8701e4af060616812f641f1b36f --- /dev/null +++ b/code/policy_models/datasets/mvlibero_dataset.py @@ -0,0 +1,230 @@ +# Copyright (2024) Bytedance Ltd. and/or its affiliates + +# 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. + +import json +import os +import random +import warnings +import traceback +import argparse +from omegaconf import OmegaConf +from tqdm import tqdm +from torchvision import transforms as T +import torch +from torch.utils.data import Dataset,DataLoader +import numpy as np +import imageio +from decord import VideoReader, cpu +from concurrent.futures import ThreadPoolExecutor, as_completed +from einops import rearrange + +# from mdt.datasets.utils.dataset_util import euler2rotm, rotm2euler +# from mdt.datasets.utils.video_transforms import Resize_Preprocess, ToTensorVideo +# from mdt.datasets.utils.util import update_paths +from scipy.spatial.transform import Rotation as R +import decord + +class Dataset_mvlibero(Dataset): + def __init__( + self, + args, + mode = 'val', + ): + """Constructor.""" + super().__init__() + self.args = args + self.mode = mode + data_json_path = args.data_json_path + data_root_path = args.data_root_path + + # dataset stucture + # dataset_dir/dataset_name/annotation_name/mode/traj + # dataset_dir/dataset_name/video/mode/traj + # dataset_dir/dataset_name/latent_video/mode/traj + + # samles:{'ann_file':xxx, 'frame_idx':xxx, 'dataset_name':xxx} + + # prepare all datasets path + self.video_path = [] + data_json_path = f'{data_json_path}/{mode}_all.json' + with open(data_json_path, "r") as f: + self.samples = json.load(f) + self.video_path = [os.path.join(data_root_path, sample['dataset_name']) for sample in self.samples] + + print(f"ALL dataset, {len(self.samples)} samples in total") + + # with open(f'{self.args.action_json}', "r") as f: + # self.stat = json.load(f) + self.a_min = np.array(args.action_01)[None,:] + self.a_max = np.array(args.action_99)[None,:] + self.s_min = np.array(args.state_01)[None,:] + self.s_max = np.array(args.state_99)[None,:] + print(f"action min: {self.a_min.shape}, action max: {self.a_max.shape}") + + def __len__(self): + return len(self.samples) + + def _load_latent_video(self, video_path, frame_ids): + # video_path = video_path.split('/')[:-1] + # video_path = '/'.join(video_path)+'/0.pt' + + # print(video_path) + with open(video_path,'rb') as file: + video_tensor = torch.load(file) + video_tensor.requires_grad = False + # vr = VideoReader(video_path, ctx=cpu(0), num_threads=2) + # print(video_tensor.size(),np.array(frame_ids)) + try: + assert (np.array(frame_ids) < video_tensor.size()[0]).all() + assert (np.array(frame_ids) >= 0).all() + except: + assert False + frame_data = video_tensor[frame_ids] + return frame_data + + def _get_frames(self, label, frame_ids, cam_id, pre_encode, video_dir, use_img_cond=False): + # directly load videos latent after svd-vae encoder + assert cam_id is not None + assert pre_encode == True + if pre_encode: + video_path = label['latent_videos'][cam_id]['latent_video_path'] + try: + video_path = os.path.join(video_dir,video_path) + frames = self._load_latent_video(video_path, frame_ids) + except: + video_path = video_path.replace("latent_videos", "latent_videos_svd") + frames = self._load_latent_video(video_path, frame_ids) + # load original videos + else: + if use_img_cond: + frame_ids = frame_ids[0] + video_path = label['videos'][cam_id]['video_path'] + video_path = os.path.join(video_dir,video_path) + # frames = self._load_video(video_path, frame_ids) + # frames = mediapy.read_video(video_path) + vr = decord.VideoReader(video_path) + frames = vr[frame_ids].asnumpy() + frames = torch.from_numpy(frames).permute(2,0,1).unsqueeze(0) # (frame, h, w, c) -> (frame, c, h, w) + # resize the video to self.args.video_size + frames = self.preprocess(frames) + return frames + + def _get_obs(self, label, frame_ids, cam_id, pre_encode, video_dir): + if cam_id is None: + temp_cam_id = random.choice(self.cam_ids) + else: + temp_cam_id = cam_id + frames = self._get_frames(label, frame_ids, cam_id = temp_cam_id, pre_encode = pre_encode, video_dir=video_dir) + return frames, temp_cam_id + + def normalize_bound( + self, + data: np.ndarray, + data_min: np.ndarray, + data_max: np.ndarray, + clip_min: float = -1, + clip_max: float = 1, + eps: float = 1e-8, + ) -> np.ndarray: + ndata = 2 * (data - data_min) / (data_max - data_min + eps) - 1 + return np.clip(ndata, clip_min, clip_max) + + def denormalize_bound( + self, + data: np.ndarray, + data_min: np.ndarray, + data_max: np.ndarray, + clip_min: float = -1, + clip_max: float = 1, + eps=1e-8, + ) -> np.ndarray: + clip_range = clip_max - clip_min + rdata = (data - clip_min) / clip_range * (data_max - data_min) + data_min + return rdata + + def process_action_xhand(self, label,frame_ids, rel = False): + num_frames = len(frame_ids) + frame_ids = frame_ids[:int(self.args.num_frames)] # (f) + states = np.array(label['states'])[frame_ids] #(f, 38) + command = np.array(label['actions'])[frame_ids] + + # print(f'states: {states.shape}, actions: {command.shape}') + + state = states[0:1] # current state + + a_dim = command.shape[-1] + action_base = state[:,:a_dim] #(1,38) + actions = command - action_base #(self.args.num_frames,38) + + # normalize + action_scaled = self.normalize_bound(actions, self.a_min, self.a_max) + state_scaled = self.normalize_bound(state, self.s_min, self.s_max) + return torch.from_numpy(action_scaled).float(), torch.from_numpy(state_scaled).float() + + def __getitem__(self, index, cam_id = None, return_video = False): + + sample = self.samples[index] + sampled_video_dir = self.video_path[index] + + ann_file = sample['ann_file'] + # dataset_name = sample['dataset_name'] + ann_file = f'{sampled_video_dir}/{ann_file}' + frame_ids = sample['frame_ids'] + with open(ann_file, "r") as f: + label = json.load(f) + + data = dict() + # action + data['actions'], data['state_obs'] = self.process_action_xhand(label,frame_ids,rel=self.args.relative) + # instructions + data['lang_text'] = label['texts'][0] + # observation + static_latent, cam_id = self._get_obs(label, frame_ids[0], cam_id=0, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + gripper_latent, cam_id = self._get_obs(label, frame_ids[0], cam_id=1, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + gripper_latent2, cam_id = self._get_obs(label, frame_ids[0], cam_id=2, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + static_latent = static_latent.unsqueeze(0) + gripper_latent = gripper_latent.unsqueeze(0) # (1,4,32,32) + gripper_latent2 = gripper_latent2.unsqueeze(0) + + # one sample + rgb_obs = {'rgb_static': static_latent, 'rgb_gripper': gripper_latent, 'rgb_gripper2': gripper_latent2} + data['rgb_obs'] = rgb_obs + data['ann_file'] = ann_file + data['frame_ids'] = frame_ids + + return data + + +if __name__ == "__main__": + from hydra import compose, initialize + from omegaconf import OmegaConf + with initialize(config_path="../../conf", job_name="VPP_xbot_train.yaml"): + cfg = compose(config_name="VPP_xbot_train") + + # import sys + # sys.path.append('/cephfs/cjyyj/code/video_robot_svd-main/mdt') + # from utils.util import get_args + # train_args = get_args(cfg.datamodule.args) + # print(train_args) + train_dataset = Dataset_xbot(cfg.dataset_args,mode="val") + train_loader = torch.utils.data.DataLoader( + train_dataset, + batch_size=cfg.dataset_args.batch_size, + shuffle=cfg.dataset_args.shuffle, + ) + for data in tqdm(train_loader,total=len(train_loader)): + print(data['ann_file']) + print(len(data['rgb_obs'])) + + \ No newline at end of file diff --git a/code/policy_models/datasets/real_dataset.py b/code/policy_models/datasets/real_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ffae6a076643fc1e6dd4134dddb9e9319f4042 --- /dev/null +++ b/code/policy_models/datasets/real_dataset.py @@ -0,0 +1,287 @@ +# Copyright (2024) Bytedance Ltd. and/or its affiliates + +# 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. + +import json +import os +import random +import warnings +import traceback +import argparse +from omegaconf import OmegaConf +from tqdm import tqdm +from torchvision import transforms as T +import torch +from torch.utils.data import Dataset,DataLoader +import numpy as np +import imageio +from decord import VideoReader, cpu +from concurrent.futures import ThreadPoolExecutor, as_completed +from einops import rearrange + +# from mdt.datasets.utils.dataset_util import euler2rotm, rotm2euler +# from mdt.datasets.utils.video_transforms import Resize_Preprocess, ToTensorVideo +# from mdt.datasets.utils.util import update_paths +from scipy.spatial.transform import Rotation as R +import decord + +class Dataset_policy(Dataset): + def __init__( + self, + args, + mode = 'val', + data_json_path = '/localssd/gyj/opensource_robotdata/annotation_all/0407', + data_root_path = '/localssd/gyj/opensource_robotdata/', + ): + """Constructor.""" + super().__init__() + self.args = args + self.mode = mode + + # dataset stucture + # dataset_dir/dataset_name/annotation_name/mode/traj + # dataset_dir/dataset_name/video/mode/traj + # dataset_dir/dataset_name/latent_video/mode/traj + + # samles:{'ann_file':xxx, 'frame_idx':xxx, 'dataset_name':xxx} + + # prepare all datasets path + self.video_path = [] + data_json_path = f'{data_json_path}/{mode}_all.json' + with open(data_json_path, "r") as f: + self.samples = json.load(f) + self.video_path = [os.path.join(data_root_path, sample['dataset_name']) for sample in self.samples] + + print(f"ALL dataset, {len(self.samples)} samples in total") + + self.a_min = np.array(args.action_01)[None,:] + self.a_max = np.array(args.action_99)[None,:] + self.s_min = np.array(args.state_01)[None,:] + self.s_max = np.array(args.state_99)[None,:] + + def __len__(self): + return len(self.samples) + + def _load_latent_video(self, video_path, frame_ids): + # video_path = video_path.split('/')[:-1] + # video_path = '/'.join(video_path)+'/0.pt' + + # print(video_path) + with open(video_path,'rb') as file: + video_tensor = torch.load(file) + video_tensor.requires_grad = False + # vr = VideoReader(video_path, ctx=cpu(0), num_threads=2) + # print(video_tensor.size(),np.array(frame_ids)) + try: + assert (np.array(frame_ids) < video_tensor.size()[0]).all() + assert (np.array(frame_ids) >= 0).all() + except: + assert False + frame_data = video_tensor[frame_ids] + return frame_data + + def _get_frames(self, label, frame_ids, cam_id, pre_encode, video_dir, use_img_cond=False): + # directly load videos latent after svd-vae encoder + assert cam_id is not None + assert pre_encode == True + if pre_encode: + video_path = label['latent_videos'][cam_id]['latent_video_path'] + try: + video_path = os.path.join(video_dir,video_path) + frames = self._load_latent_video(video_path, frame_ids) + except: + video_path = video_path.replace("latent_videos", "latent_videos_svd") + frames = self._load_latent_video(video_path, frame_ids) + # load original videos + else: + if use_img_cond: + frame_ids = frame_ids[0] + video_path = label['videos'][cam_id]['video_path'] + video_path = os.path.join(video_dir,video_path) + # frames = self._load_video(video_path, frame_ids) + # frames = mediapy.read_video(video_path) + vr = decord.VideoReader(video_path) + frames = vr[frame_ids].asnumpy() + frames = torch.from_numpy(frames).permute(2,0,1).unsqueeze(0) # (frame, h, w, c) -> (frame, c, h, w) + # resize the video to self.args.video_size + frames = self.preprocess(frames) + return frames + + def _get_obs(self, label, frame_ids, cam_id, pre_encode, video_dir): + if cam_id is None: + temp_cam_id = random.choice(self.cam_ids) + else: + temp_cam_id = cam_id + frames = self._get_frames(label, frame_ids, cam_id = temp_cam_id, pre_encode = pre_encode, video_dir=video_dir) + return frames, temp_cam_id + + def process_action_xhand(self, label,frame_ids, rel = False): + num_frames = len(frame_ids) + frame_ids = frame_ids[:int(self.args.num_frames+1)] # (10,) + states = np.array(label['states'])[frame_ids] + command = np.array(label['actions'])[frame_ids] + + state_input = states[0:1] #(1,19) + # always use the set the first item of quat >0 + if state_input[0,3] <0: + state_input[0,3:7] *= -1 + + states_raw = states if not self.args.learn_command else command + + if not rel: + state_next = states_raw[:-1] # command + mu = np.array(self.args.mu) + std = np.array(self.args.std) + + state_input = (state_input-mu)/std + action_sclaed = (state_next-mu)/std + + else: # relative ro fiest frame + xyz, rot, hand = states_raw[:,:3], states_raw[:,3:7], states_raw[:,7:] + # xyz + current_xyz = state_input[:,:3] + delta_xyz = (xyz[:-1]-current_xyz)*self.args.rel_xyz_scale + # rot + current_quat = state_input[:,3:7] + rotm = [R.from_quat(rot[i]).as_matrix() for i in range(len(rot-1))] + current_rotm = R.from_quat(current_quat[0]).as_matrix() + rel_rotm = [current_rotm.T @ next_rotm for next_rotm in rotm[:-1]] + rel_rpy = [R.from_matrix(rot).as_euler('xyz', degrees=False) for rot in rel_rotm] + + rel_rpy = np.array(rel_rpy)*self.args.rel_rot_scale + # hand + hand = hand[:-1]*self.args.rel_hand_scale + + action_sclaed = np.concatenate([delta_xyz,rel_rpy,hand],axis=1) # (10,18) + + if self.args.norm_input: + mu = np.array(self.args.mu) + std = np.array(self.args.std) + state_input = (state_input-mu)/std + + return torch.from_numpy(action_sclaed).float(), torch.from_numpy(state_input).float() + + def normalize_bound( + self, + data: np.ndarray, + data_min: np.ndarray, + data_max: np.ndarray, + clip_min: float = -1, + clip_max: float = 1, + eps: float = 1e-8, + ) -> np.ndarray: + ndata = 2 * (data - data_min) / (data_max - data_min + eps) - 1 + return np.clip(ndata, clip_min, clip_max) + + def denormalize_bound( + self, + data: np.ndarray, + data_min: np.ndarray, + data_max: np.ndarray, + clip_min: float = -1, + clip_max: float = 1, + eps=1e-8, + ) -> np.ndarray: + clip_range = clip_max - clip_min + rdata = (data - clip_min) / clip_range * (data_max - data_min) + data_min + return rdata + + def process_action_xhand_v2(self, label,frame_ids, rel = False): + frame_ids = frame_ids[:int(self.args.num_frames)] + states = np.array(label['states'])[frame_ids] + command = np.array(label['actions'])[frame_ids] + + state_input = states[0:1] #(1,19) + # always use the set the first item of quat >0 + if state_input[0,3] <0: + state_input[0,3:7] *= -1 + + states_raw = states if not self.args.learn_command else command + + xyz, rot, hand = states_raw[:,:3], states_raw[:,3:7], states_raw[:,7:] + # xyz + current_xyz = state_input[:,:3] + delta_xyz = (xyz-current_xyz) + # rot + current_quat = state_input[:,3:7] + rotm = [R.from_quat(rot[i]).as_matrix() for i in range(len(rot))] + current_rotm = R.from_quat(current_quat[0]).as_matrix() + rel_rotm = [current_rotm.T @ next_rotm for next_rotm in rotm] + rel_rpy = [R.from_matrix(rot).as_euler('xyz', degrees=False) for rot in rel_rotm] + # hand + hand = hand + + action = np.concatenate([delta_xyz,rel_rpy,hand],axis=1) # (10,18) + state = state_input + + action_scaled = self.normalize_bound(action, self.a_min, self.a_max) + state_scaled = self.normalize_bound(state, self.s_min, self.s_max) + + return torch.from_numpy(action_scaled).float(), torch.from_numpy(state_scaled).float() + + def __getitem__(self, index, cam_id = None, return_video = False): + + sample = self.samples[index] + sampled_video_dir = self.video_path[index] + + ann_file = sample['ann_file'] + # dataset_name = sample['dataset_name'] + ann_file = f'{sampled_video_dir}/{ann_file}' + frame_ids = sample['frame_ids'] + with open(ann_file, "r") as f: + label = json.load(f) + + data = dict() + # action + if self.args.action_v2: + data['actions'], data['state_obs'] = self.process_action_xhand_v2(label,frame_ids,rel=self.args.relative) + else: + data['actions'], data['state_obs'] = self.process_action_xhand(label,frame_ids,rel=self.args.relative) + # instructions + data['lang_text'] = label['texts'][0] + # observation + static_latent, cam_id = self._get_obs(label, frame_ids[0], cam_id=0, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + gripper_latent, cam_id = self._get_obs(label, frame_ids[0], cam_id=1, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + static_latent = static_latent.unsqueeze(0) + gripper_latent = gripper_latent.unsqueeze(0) # (1,4,32,32) + + # one sample + rgb_obs = {'rgb_static': static_latent, 'rgb_gripper': gripper_latent} + data['rgb_obs'] = rgb_obs + data['ann_file'] = ann_file + data['frame_ids'] = frame_ids + + return data + + +if __name__ == "__main__": + from hydra import compose, initialize + from omegaconf import OmegaConf + with initialize(config_path="../../conf", job_name="VPP_xhand_train.yaml"): + cfg = compose(config_name="VPP_xhand_train") + + # import sys + # sys.path.append('/cephfs/cjyyj/code/video_robot_svd-main/mdt') + # from utils.util import get_args + # train_args = get_args(cfg.datamodule.args) + # print(train_args) + train_dataset = Dataset_policy(cfg.dataset_args,mode="val") + train_loader = torch.utils.data.DataLoader( + train_dataset, + batch_size=cfg.dataset_args.batch_size, + shuffle=cfg.dataset_args.shuffle, + ) + for data in tqdm(train_loader,total=len(train_loader)): + print(data['ann_file']) + + \ No newline at end of file diff --git a/code/policy_models/datasets/shm_dataset.py b/code/policy_models/datasets/shm_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..656ec7930d31f5e4f984c7eb59d17bd0c8492c32 --- /dev/null +++ b/code/policy_models/datasets/shm_dataset.py @@ -0,0 +1,176 @@ +import logging +from multiprocessing.shared_memory import SharedMemory +from typing import Dict, List, Optional + +import numpy as np + +from policy_models.datasets.base_dataset import BaseDataset + +logger = logging.getLogger(__name__) + + +class ShmDataset(BaseDataset): + """ + Dataset that loads episodes from shared memory. + """ + + def __init__(self, *args, **kwargs): # type: ignore + super().__init__(*args, **kwargs) + self.episode_lookup_dict: Dict[str, List] = {} + self.episode_lookup: Optional[np.ndarray] = None + self.lang_lookup = None + self.lang_ann = None + self.shapes = None + self.sizes = None + self.dtypes = None + self.dataset_type = None + self.shared_memories = None + + def setup_shm_lookup(self, shm_lookup: Dict) -> None: + """ + Initialize episode lookups. + + Args: + shm_lookup: Dictionary containing precomputed lookups. + """ + if self.with_lang: + self.episode_lookup_dict = shm_lookup["episode_lookup_lang"] + self.lang_lookup = shm_lookup["lang_lookup"] + self.lang_ann = shm_lookup["lang_ann"] + else: + self.episode_lookup_dict = shm_lookup["episode_lookup_vision"] + key = list(self.episode_lookup_dict.keys())[0] + self.episode_lookup = np.array(self.episode_lookup_dict[key])[:, 1] + self.shapes = shm_lookup["shapes"] + self.sizes = shm_lookup["sizes"] + self.dtypes = shm_lookup["dtypes"] + self.dataset_type = "train" if "training" in self.abs_datasets_dir.as_posix() else "val" + # attach to shared memories + self.shared_memories = { + key: SharedMemory(name=f"{self.dataset_type}_{key}") for key in self.episode_lookup_dict + } + + def _load_episode(self, idx: int, window_size: int) -> Dict[str, np.ndarray]: + """ + Load consecutive frames from shared memory and combine to episode dict. + + Args: + idx: Index of first frame. + window_size: Length of sampled episode. + + Returns: + episode: Dict of numpy arrays containing the episode where keys are the names of modalities. + """ + episode = {} + for key, lookup in self.episode_lookup_dict.items(): + offset, j = lookup[idx] + shape = (window_size + j,) + self.shapes[key] + array = np.ndarray(shape, dtype=self.dtypes[key], buffer=self.shared_memories[key].buf, offset=offset)[j:] # type: ignore + episode[key] = array + if self.with_lang: + episode["language"] = self.lang_ann[self.lang_lookup[idx]][0] # TODO check [0] + return episode + + + +class BesoSHmDataset(BaseDataset): + + def __init__( + self, + obs_seq_len: int, + action_seq_len: int, + future_range: int, + *args, + **kwargs): # type: ignore + super().__init__(*args, **kwargs) + self.episode_lookup_dict: Dict[str, List] = {} + self.episode_lookup: Optional[np.ndarray] = None + self.lang_lookup = None + self.lang_ann = None + self.shapes = None + self.sizes = None + self.dtypes = None + self.dataset_type = None + self.shared_memories = None + + # new stuff for our dataset + self.obs_seq_len = obs_seq_len + self.action_seq_len = action_seq_len + self.future_range = future_range + + def setup_shm_lookup(self, shm_lookup: Dict) -> None: + """ + Initialize episode lookups. + + Args: + shm_lookup: Dictionary containing precomputed lookups. + """ + if self.with_lang: + self.episode_lookup_dict = shm_lookup["episode_lookup_lang"] + self.lang_lookup = shm_lookup["lang_lookup"] + self.lang_ann = shm_lookup["lang_ann"] + else: + self.episode_lookup_dict = shm_lookup["episode_lookup_vision"] + key = list(self.episode_lookup_dict.keys())[0] + self.episode_lookup = np.array(self.episode_lookup_dict[key])[:, 1] + self.shapes = shm_lookup["shapes"] + self.sizes = shm_lookup["sizes"] + self.dtypes = shm_lookup["dtypes"] + self.dataset_type = "train" if "training" in self.abs_datasets_dir.as_posix() else "val" + # attach to shared memories + self.shared_memories = { + key: SharedMemory(name=f"{self.dataset_type}_{key}") for key in self.episode_lookup_dict + } + + def _load_episode(self, idx: int, window_size: int) -> Dict[str, np.ndarray]: + episode = {} + keys = list(chain(*self.observation_space.values())) + keys.remove("language") + keys.append("scene_obs") + + # Load main episode data from shared memory + for key, lookup in self.episode_lookup_dict.items(): + offset, j = lookup[idx] + shape = (window_size + j,) + self.shapes[key] + array = np.ndarray(shape, dtype=self.dtypes[key], buffer=self.shared_memories[key].buf, offset=offset)[j:] + + # Slice the data to match action_seq_len and obs_seq_len + if key == "rel_actions" or key == 'actions': + episode[key] = array[:self.action_seq_len, :] + else: + episode[key] = array[:self.obs_seq_len, :] + + if self.with_lang: + episode["language"] = self.lang_ann[self.lang_lookup[idx]][0] # TODO check [0] + + # Logic for future goal + delta = np.random.randint(self.future_range) + goal_idx = self.episode_lookup[idx] + self.action_seq_len + delta + eps_start_idx, eps_end_idx = self.find_sequence_boundaries(goal_idx) + if eps_end_idx < goal_idx: + goal_idx = eps_end_idx + + # Load future goal from shared memory + offset, j = self.episode_lookup_dict['scene_obs'][goal_idx] # Assuming 'scene_obs' is the key for goals + shape = (1,) + self.shapes['scene_obs'] + goal_array = np.ndarray(shape, dtype=self.dtypes['scene_obs'], buffer=self.shared_memories['scene_obs'].buf, offset=offset)[j:] + + goal_episode = {'scene_obs': goal_array[:self.obs_seq_len, :]} + + # Merge episodes + episode = self.merge_episodes(episode, goal_episode) + + return episode + + def merge_episodes(self, episode1: Dict[str, np.ndarray], episode2: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]: + merged_episode = {} + all_keys = set(episode1.keys()).union(set(episode2.keys())) + for key in all_keys: + if key in episode1 and key in episode2: + # Merge logic here, for example: + merged_episode[key] = np.concatenate([episode1[key], episode2[key]], axis=0) + elif key in episode1: + merged_episode[key] = episode1[key] + else: + merged_episode[key] = episode2[key] + return merged_episode \ No newline at end of file diff --git a/code/policy_models/datasets/utils/__init__.py b/code/policy_models/datasets/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/datasets/utils/__pycache__/__init__.cpython-310.pyc b/code/policy_models/datasets/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d2bd0efbd90b4f41ddbcda91231ae8679690b27 Binary files /dev/null and b/code/policy_models/datasets/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/datasets/utils/__pycache__/episode_utils.cpython-310.pyc b/code/policy_models/datasets/utils/__pycache__/episode_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfedf8a04b3ccfd364401cc2851518caf104a202 Binary files /dev/null and b/code/policy_models/datasets/utils/__pycache__/episode_utils.cpython-310.pyc differ diff --git a/code/policy_models/datasets/utils/__pycache__/shared_memory_utils.cpython-310.pyc b/code/policy_models/datasets/utils/__pycache__/shared_memory_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..481971480966127f57845061daaf356a6f952bdd Binary files /dev/null and b/code/policy_models/datasets/utils/__pycache__/shared_memory_utils.cpython-310.pyc differ diff --git a/code/policy_models/datasets/utils/episode_utils.py b/code/policy_models/datasets/utils/episode_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0635e759de960dba8c6d8390e67955d45150807d --- /dev/null +++ b/code/policy_models/datasets/utils/episode_utils.py @@ -0,0 +1,237 @@ +import logging +import os +from pathlib import Path +import re +from typing import Dict, Tuple + +import numpy as np +from omegaconf import DictConfig, ListConfig, OmegaConf +import torch + +logger = logging.getLogger(__name__) + + +def process_state( + episode: Dict[str, np.ndarray], + observation_space: DictConfig, + transforms: Dict, + proprio_state: DictConfig, + seq_idx: int = 0, + window_size: int = 0, +) -> Dict[str, torch.Tensor]: + state_obs_keys = observation_space["state_obs"] + state_obs_list_normalized = [] + state_obs_list_unnormalized = [] + for state_ob in state_obs_keys: + if window_size == 0 and seq_idx == 0: # single file loader + state_tensor = torch.from_numpy(episode[state_ob]).float() + else: # episode loader + state_tensor = torch.from_numpy(episode[state_ob][seq_idx : seq_idx + window_size]).float() + # expand dims for single environment obs + if len(state_tensor.shape) != 2: + state_tensor = state_tensor.unsqueeze(0) + # shape: (BxN_state_obs) + assert len(state_tensor.shape) == 2 + if state_ob in transforms: + state_tensor_normalized = transforms[state_ob](state_tensor) + state_obs_list_normalized.append(state_tensor_normalized) + else: + state_obs_list_normalized.append(state_tensor) + state_obs_list_unnormalized.append(state_tensor) + seq_state_obs = torch.cat(state_obs_list_normalized, dim=1) + seq_state_obs_unnormalized = torch.cat(state_obs_list_unnormalized, dim=1) + + if not proprio_state.normalize_robot_orientation and "robot_orientation_idx" in proprio_state: + seq_state_obs[:, slice(*proprio_state.robot_orientation_idx)] = seq_state_obs_unnormalized[ + :, slice(*proprio_state.robot_orientation_idx) + ] + + if not proprio_state.normalize: + seq_state_obs = seq_state_obs_unnormalized + + # slice the specified parts of the proprioception state + state_obs_sliced = [] + for slice_ids in proprio_state.keep_indices: + seq_state_obs_ = seq_state_obs[:, slice(*slice_ids)] + state_obs_sliced.append(seq_state_obs_) + seq_state_obs = torch.cat(state_obs_sliced, dim=1) + + return {"robot_obs": seq_state_obs} + + +def process_rgb( + episode: Dict[str, np.ndarray], + observation_space: DictConfig, + transforms: Dict, + seq_idx: int = 0, + window_size: int = 0, +) -> Dict[str, Dict[str, torch.Tensor]]: + rgb_obs_keys = observation_space["rgb_obs"] + seq_rgb_obs_dict = {} + for _, rgb_obs_key in enumerate(rgb_obs_keys): + if rgb_obs_key not in episode: + # If the key is not found, skip to the next iteration + continue + rgb_obs = episode[rgb_obs_key] + # expand dims for single environment obs + if len(rgb_obs.shape) != 4: + rgb_obs = np.expand_dims(rgb_obs, axis=0) + assert len(rgb_obs.shape) == 4 + if window_size == 0 and seq_idx == 0: # single file loader + # To Square image + seq_rgb_obs_ = torch.from_numpy(rgb_obs).byte().permute(0, 3, 1, 2) + else: # episode loader + seq_rgb_obs_ = torch.from_numpy(rgb_obs[seq_idx : seq_idx + window_size]).byte().permute(0, 3, 1, 2) + # we might have different transformations for the different cameras + if rgb_obs_key in transforms: + seq_rgb_obs_ = transforms[rgb_obs_key](seq_rgb_obs_) + seq_rgb_obs_dict[rgb_obs_key] = seq_rgb_obs_ + # shape: N_rgb_obs x (BxCxHxW) + return {"rgb_obs": seq_rgb_obs_dict} + + + +def process_depth( + episode: Dict[str, np.ndarray], + observation_space: DictConfig, + transforms: Dict, + seq_idx: int = 0, + window_size: int = 0, +) -> Dict[str, Dict[str, torch.Tensor]]: + # expand dims for single environment obs + def exp_dim(depth_img): + if len(depth_img.shape) != 3: + depth_img = np.expand_dims(depth_img, axis=0) + return depth_img + + depth_obs_keys = observation_space["depth_obs"] + seq_depth_obs_dict = {} + for _, depth_obs_key in enumerate(depth_obs_keys): + depth_ob = exp_dim(episode[depth_obs_key]) + assert len(depth_ob.shape) == 3 + if window_size == 0 and seq_idx == 0: # single file loader + depth_ob_ = torch.from_numpy(depth_ob).float() + else: # episode loader + depth_ob_ = torch.from_numpy(depth_ob[seq_idx : seq_idx + window_size]).float() + # we might have different transformations for the different cameras + if depth_obs_key in transforms: + depth_ob_ = transforms[depth_obs_key](depth_ob_) + seq_depth_obs_dict[depth_obs_key] = depth_ob_ + # shape: N_depth_obs x(BxHxW) + return {"depth_obs": seq_depth_obs_dict} + + +def process_actions( + episode: Dict[str, np.ndarray], + observation_space: DictConfig, + transforms: Dict, + seq_idx: int = 0, + window_size: int = 0, +) -> Dict[str, torch.Tensor]: + # shape: (N_actions) + action_keys = observation_space["actions"] + if len(action_keys) != 1: + raise NotImplementedError + action_key = action_keys[0] + if window_size == 0 and seq_idx == 0: # single file loader + action = episode[action_key] + if "actions" in transforms: + action = transforms["actions"]((action, episode["robot_obs"])) + seq_acts = torch.from_numpy(action).float() + else: # episode loader + seq_acts = torch.from_numpy(episode[action_key][seq_idx : seq_idx + window_size]).float() + return {"actions": seq_acts} + + +def process_language(episode: Dict[str, np.ndarray], transforms: Dict, with_lang: bool) -> Dict[str, torch.Tensor]: + seq_lang = {"lang": torch.empty(0)} + if with_lang: + lang = torch.from_numpy(episode["language"]).float() + if "language" in transforms: + lang = transforms["language"](lang) + seq_lang["lang"] = lang + seq_lang['lang_text'] = episode['language_text'] + return seq_lang + + +def get_state_info_dict(episode: Dict[str, np.ndarray]) -> Dict[str, Dict[str, torch.Tensor]]: + """ + Create a dictionary with raw state observations for environment resets. + + Args: + episode: Sequence dictionary. + + Returns: + Info dict of full robot and scene state (for env resets). + """ + return { + "state_info": { + "robot_obs": torch.from_numpy(episode["robot_obs"]), + "scene_obs": torch.from_numpy(episode["scene_obs"]), + } + } + + +def load_dataset_statistics(train_dataset_dir, val_dataset_dir, transforms): + """ + Tries to load statistics.yaml in every dataset folder in order to update the transforms hardcoded in the + hydra config file. If no statistics.yaml exists, nothing is changed + + Args: + train_dataset_dir: path of the training folder + val_dataset_dir: path of the validation folder + transforms: transforms loaded from hydra conf + + Returns: + transforms: potentially updated transforms + """ + paths = {"train": train_dataset_dir, "val": val_dataset_dir} + for dataset_type in ["train", "val"]: + try: + statistics = OmegaConf.load(Path(paths[dataset_type]) / "statistics.yaml") + # Hack for maintaining two repositories with transforms + statistics = OmegaConf.create(OmegaConf.to_yaml(statistics).replace("calvin_agent", "policy_models")) + # this ugly piece of code only exists because OmegaConf actually can't merge ListConfigs. + # we do not want to override everything, but just the transforms that are specified in both + # see https://stackoverflow.com/questions/61315623/omegaconf-can-i-influence-how-lists-are-merged + for modality in transforms[dataset_type]: + if modality in statistics: + conf_transforms = transforms[dataset_type][modality] + dataset_transforms = statistics[modality] + for dataset_trans in dataset_transforms: + exists = False + for i, conf_trans in enumerate(conf_transforms): + if dataset_trans["_target_"] == conf_trans["_target_"]: + exists = True + transforms[dataset_type][modality][i] = dataset_trans + break + if not exists: + transforms[dataset_type][modality] = ListConfig([*conf_transforms, dataset_trans]) + except FileNotFoundError: + logger.warning("Could not load statistics.yaml") + return transforms + + +def lookup_naming_pattern(dataset_dir: Path, save_format: str) -> Tuple[Tuple[Path, str], int]: + """ + Check naming pattern of dataset files. + + Args: + dataset_dir: Path to dataset. + save_format: File format (CALVIN default is npz). + + Returns: + naming_pattern: 'file_0000001.npz' -> ('file_', '.npz') + n_digits: Zero padding of file enumeration. + """ + it = os.scandir(dataset_dir) + while True: + filename = Path(next(it)) + if save_format in filename.suffix: + break + aux_naming_pattern = re.split(r"\d+", filename.stem) + naming_pattern = (filename.parent / aux_naming_pattern[0], filename.suffix) + n_digits = len(re.findall(r"\d+", filename.stem)[0]) + assert len(naming_pattern) == 2 + assert n_digits > 0 + return naming_pattern, n_digits diff --git a/code/policy_models/datasets/utils/shared_memory_utils.py b/code/policy_models/datasets/utils/shared_memory_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..05cbe50362e491445db5b4119976969aa7f61e14 --- /dev/null +++ b/code/policy_models/datasets/utils/shared_memory_utils.py @@ -0,0 +1,336 @@ +from collections import defaultdict +from functools import partial +from itertools import chain +import logging +import multiprocessing +from multiprocessing.shared_memory import SharedMemory +import os +from pathlib import Path +import signal +from typing import Dict, Optional, Tuple + +import numpy as np +from omegaconf import DictConfig +from pytorch_lightning import Callback, LightningModule, Trainer +from tqdm import tqdm + +from policy_models.datasets.shm_dataset import ShmDataset +from policy_models.datasets.utils.episode_utils import lookup_naming_pattern + +log = logging.getLogger(__name__) + + +def gather_results(return_dict: Dict) -> Tuple[Dict, Dict]: + """ + Combine results of worker processes. + + Args: + return_dict: Dictionary with results of worker processes. + + Returns: + episode_lookup_vision: Combined results of vision lookup. + lang_episode_dict: Combined results of lanugage lookup. + """ + episode_lookup_vision: Dict = defaultdict(list) + lang_episode_dict: Dict = defaultdict(dict) + for proc in sorted(return_dict): + for key in return_dict[proc][0]: + episode_lookup_vision[key] += return_dict[proc][0][key] + lang_episode_dict[key].update(return_dict[proc][1][key]) + return episode_lookup_vision, lang_episode_dict + + +def check_shm_lookup_exists(dataset_type: str) -> Optional[Dict]: + """ + Check if there is already a shared memory lookup file saved on the disk. + + Args: + dataset_type: 'train' or 'val'. + + Returns: + Lookup file if exists, None otherwise. + """ + load_path = Path("/tmp/") if "TMPDIR" not in os.environ else Path(os.environ["TMPDIR"]) + try: + data: Dict = np.load(load_path / f"{dataset_type}_shm_lookup.npy", allow_pickle=True).item() + return data + except FileNotFoundError: + return None + + +def save_shm_lookup(train_shm_lookup: Dict, val_shm_lookup: Dict) -> None: + """ + Save shared memory lookups to disk, such that they can be reused by ddp subprocesses. + + Args: + train_shm_lookup: Shared memory lookup for training data. + val_shm_lookup: Shared memory lookup for validation data. + """ + save_path = Path("/tmp/") if "TMPDIR" not in os.environ else Path(os.environ["TMPDIR"]) + np.save(save_path / "train_shm_lookup.npy", train_shm_lookup) # type: ignore + np.save(save_path / "val_shm_lookup.npy", val_shm_lookup) # type: ignore + + +def load_shm_lookup() -> Tuple[Dict, Dict]: + """ + Load shared memory lookup. + + Returns: + train_shm_lookup: Shared memory lookup for training data. + val_shm_lookup: Shared memory lookup for validation data. + """ + load_path = Path("/tmp/") if "TMPDIR" not in os.environ else Path(os.environ["TMPDIR"]) + train_shm_lookup: Dict = np.load(load_path / "train_shm_lookup.npy", allow_pickle=True).item() + val_shm_lookup: Dict = np.load(load_path / "val_shm_lookup.npy", allow_pickle=True).item() + return train_shm_lookup, val_shm_lookup + + +class SharedMemoryLoader: + """ + Helper class for loading dataset into shared memory. + + Args: + datasets_cfg: Hydra config of datasets. + dataset_dir: Path to dataset. + """ + + def __init__(self, datasets_cfg: DictConfig, dataset_dir: Path): + self.obs_space = datasets_cfg.lang_dataset.obs_space if "lang" in datasets_cfg else datasets_cfg.vision_dataset.obs_space + self.dataset_dir = dataset_dir + self.dataset_type = "train" if "training" in dataset_dir.as_posix() else "val" + self.lang_folder = datasets_cfg.lang_dataset.lang_folder if "lang" in datasets_cfg else datasets_cfg.vision_dataset.lang_folder # lang_folder: "lang_paraphrase-MiniLM-L3-v2" + self.naming_pattern, self.n_digits = lookup_naming_pattern(self.dataset_dir, "npz") + self.min_window_size_vision = datasets_cfg.vision_dataset.min_window_size + self.min_window_size_lang = datasets_cfg.lang_dataset.min_window_size if "lang" in datasets_cfg else datasets_cfg.vision_dataset.min_window_size + self.n_proc = 8 + + def _worker_process(self, proc_num, ep_start_end_ids, offsets, shmem, lang_ep_start_end_ids, return_dict): + """ + Multiprocessing worker to speed up the loading of the data into shared memory. + + Args: + proc_num: Process number. + ep_start_end_ids: Episode start and end indices for this worker. + offsets: Offset for addressing right portion of shared array. + shmem: Shared memory handles. + lang_ep_start_end_ids: Episode start and end indices of language data for this worker. + return_dict: Dictionary for saving the results. + """ + episode_lookup_vision = defaultdict(list) + lang_episode_dict = defaultdict(dict) + if proc_num == 0: + pbar = tqdm(total=np.sum(np.diff(ep_start_end_ids)), leave=False) + else: + pbar = None + for i, (start_idx, end_idx) in enumerate(ep_start_end_ids): + seq = self._zip_sequence(start_idx, end_idx, pbar) + for key, array in seq.items(): + shared_array = np.ndarray(array.shape, dtype=array.dtype, buffer=shmem[key].buf, offset=offsets[key]) + shared_array[:] = array[:] + + for j, idx in enumerate(range(start_idx, end_idx + 1 - self.min_window_size_vision)): + episode_lookup_vision[key].append((offsets[key], j)) + if idx in lang_ep_start_end_ids[:, 0]: + lang_episode_dict[key][idx] = (offsets[key], j) + offsets[key] += array.nbytes + return_dict[proc_num] = episode_lookup_vision, lang_episode_dict + if pbar is not None: + pbar.close() + + def load_data_in_shared_memory(self): + """ + Load the dataset from disk into shared memory once at the beginning of the training to speed up data loading. + + Returns: + Shared memory lookup dict. + """ + lang_data = np.load(self.dataset_dir / self.lang_folder / "auto_lang_ann.npy", allow_pickle=True).item() if self.lang_folder is not None else None + ep_start_end_ids = np.load(self.dataset_dir / "ep_start_end_ids.npy") + lang_ep_start_end_ids = np.array(lang_data["info"]["indx"]) if self.lang_folder is not None else None #np.array(vision_data["info"]["indx"]) + lang_ann = lang_data["language"]["emb"] if self.lang_folder is not None else None + shmem, shapes, sizes, dtypes, shmem_lookup = self._init_shmem(ep_start_end_ids) + + if shmem_lookup is not None: + pass + # using existing shared memory + # log.info("Using existing shared memory without reloading it.") + # return shmem_lookup + + lang_lookup = [] + + episode_lookup_lang = defaultdict(list) + log.info( + f"Loading {self.dataset_type} language episodes into shared memory. " + f"(progress bar shows only worker process 0)." + ) + + if self.n_proc > len(ep_start_end_ids): + self.n_proc = len(ep_start_end_ids) + split_indices = np.array_split(ep_start_end_ids, self.n_proc, axis=0) + split_lens = [np.sum(np.diff(split_indices[i])) for i in range(len(split_indices))] + obs_size = {key: dtypes[key].itemsize * np.prod(shapes[key]) for key in dtypes} + offsets = [{key: n * obs_size[key] for key in dtypes} for n in np.cumsum([0] + split_lens[:-1])] + + manager = multiprocessing.Manager() + return_dict = manager.dict() + processes = [] + # load vision data with multiple processes + for i in range(self.n_proc): + p = multiprocessing.Process( + target=self._worker_process, + args=(i, split_indices[i], offsets[i], shmem, lang_ep_start_end_ids, return_dict), + ) + processes.append(p) + p.start() + for proc in processes: + proc.join() + + episode_lookup_vision, lang_episode_dict = gather_results(return_dict) + + # lang data + if lang_ep_start_end_ids is not None: + for i, (start_idx, end_idx) in enumerate(tqdm(lang_ep_start_end_ids)): + for key in lang_episode_dict: + offset, step = lang_episode_dict[key][start_idx] + for j, idx in enumerate(range(start_idx, end_idx + 1 - self.min_window_size_lang)): + episode_lookup_lang[key].append((offset, step + j)) + for idx in range(start_idx, end_idx + 1 - self.min_window_size_lang): + lang_lookup.append(i) + result = { + "episode_lookup_vision": episode_lookup_vision, + "episode_lookup_lang": episode_lookup_lang, + "lang_lookup": lang_lookup, + "lang_ann": lang_ann, + "shapes": shapes, + "sizes": sizes, + "dtypes": dtypes, + } + return result + + def _init_shmem(self, ep_start_end_ids: np.ndarray) -> Tuple[Dict, Dict, Dict, Dict, Optional[Dict]]: + """ + Initialize shared memory. + + Args: + ep_start_end_ids: Episode start and end indices of dataset. + + Returns: + shmem: Dictionary with shared memory handles for each dataset key (rgb_static, etc ...). + shapes: Dictionary with the shape of one datapoint for each dataset key. + sizes: Dictionary with the memory size of one datapoint for each dataset key. + dtypes: Dictionary with the dtype of data for each dataset key. + shm_lookup: If shared memory lookup dict already exists, return it here. + """ + # load first episode to determine memory usage + seq = self._zip_sequence(ep_start_end_ids[0][0], ep_start_end_ids[0][0] + 1) + total_size = np.sum(ep_start_end_ids[:, 1] - ep_start_end_ids[:, 0]) + shmem: Dict[str, SharedMemory] = {} + shapes: Dict[str, Tuple] = {} + sizes: Dict[str, int] = {} + dtypes: Dict[str, str] = {} + + shm_lookup = check_shm_lookup_exists(self.dataset_type) + # check if all necessary shared memories are already loaded + if shm_lookup is not None: + print("shm_lookup exists") + try: + if np.all( + [ + SharedMemory(name=f"{self.dataset_type}_{key}").size == size * total_size + for key, size in shm_lookup["sizes"].items() + ] + ): + return shmem, shapes, sizes, dtypes, shm_lookup + except FileNotFoundError as e: + pass + for key, array in seq.items(): + try: + # see if exists + s = SharedMemory(name=f"{self.dataset_type}_{key}") + s.close() + s.unlink() + log.warning( + f"Found existing shared memory {self.dataset_type}_{key}, freeing up memory." + "In case of multiple training runs on the same node, this will lead to problems." + ) + except FileNotFoundError: + pass + shmem[key] = SharedMemory(create=True, size=array.nbytes * total_size, name=f"{self.dataset_type}_{key}") + shapes[key] = array.shape[1:] + sizes[key] = array.nbytes + dtypes[key] = array.dtype + + # register signal handler for the case that shm data loading process gets interrupted. + signal.signal(signal.SIGTERM, partial(delete_shm, shmem.keys())) + + return shmem, shapes, sizes, dtypes, None + + def _zip_sequence(self, start_idx, end_idx, pbar=None): + """ + Load consecutive frames saved as individual files on disk and combine to episode dict. + + Args: + start_idx: Start index of file. + end_idx: End index of file. + pbar: Tqdm progress bar. + + Returns: + Episode dict. + """ + keys = list(chain(*self.obs_space.values())) + keys.remove("language") + keys.append("scene_obs") + n_items = end_idx - start_idx + episode = {} + data = np.load(self._get_episode_name(start_idx)) + for key in keys: + shape = (n_items,) + data[key].shape + dtype = data[key].dtype + episode[key] = np.empty(shape=shape, dtype=dtype) + for i, file_idx in enumerate(range(start_idx, end_idx)): + with np.load(self._get_episode_name(file_idx)) as data: + for key in keys: + episode[key][i] = data[key] + if pbar is not None: + pbar.update(1) + return episode + + def _get_episode_name(self, file_idx): + """ + Convert file idx to file path. + + Args: + file_idx: index of starting frame. + + Returns: + Path to file. + """ + return Path(f"{self.naming_pattern[0]}{file_idx:0{self.n_digits}d}{self.naming_pattern[1]}") + + +def delete_shm(shm_keys, signal, frame): + """ + Close and unlink the shared memories. + """ + for dataset_type in ["train", "val"]: + for shm_key in shm_keys: + try: + s = SharedMemory(name=f"{dataset_type}_{shm_key}") + s.close() + s.unlink() + print(f"successfully unlinked {shm_key}") + except Exception as e: + print(e) + exit() + + +class SignalCallback(Callback): + """ + Register a signal handler for closing and unlinking the shared memory that get's activated with a SIGTERM signal. + """ + + def on_fit_start(self, trainer: Trainer, pl_module: LightningModule) -> None: + if isinstance(trainer.datamodule.train_dataloader()["vis"].dataset, ShmDataset): # type: ignore + shm_keys = trainer.datamodule.train_dataloader()["vis"].dataset.episode_lookup_dict.keys() # type: ignore + signal.signal(signal.SIGTERM, partial(delete_shm, shm_keys)) + print("Registered shared memory signal handler.") diff --git a/code/policy_models/datasets/xbot_dataset.py b/code/policy_models/datasets/xbot_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea667a101e192385344926074619e4efb4e457b --- /dev/null +++ b/code/policy_models/datasets/xbot_dataset.py @@ -0,0 +1,230 @@ +# Copyright (2024) Bytedance Ltd. and/or its affiliates + +# 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. + +import json +import os +import random +import warnings +import traceback +import argparse +from omegaconf import OmegaConf +from tqdm import tqdm +from torchvision import transforms as T +import torch +from torch.utils.data import Dataset,DataLoader +import numpy as np +import imageio +from decord import VideoReader, cpu +from concurrent.futures import ThreadPoolExecutor, as_completed +from einops import rearrange + +# from mdt.datasets.utils.dataset_util import euler2rotm, rotm2euler +# from mdt.datasets.utils.video_transforms import Resize_Preprocess, ToTensorVideo +# from mdt.datasets.utils.util import update_paths +from scipy.spatial.transform import Rotation as R +import decord + +class Dataset_xbot(Dataset): + def __init__( + self, + args, + mode = 'val', + ): + """Constructor.""" + super().__init__() + self.args = args + self.mode = mode + data_json_path = args.data_json_path + data_root_path = args.data_root_path + + # dataset stucture + # dataset_dir/dataset_name/annotation_name/mode/traj + # dataset_dir/dataset_name/video/mode/traj + # dataset_dir/dataset_name/latent_video/mode/traj + + # samles:{'ann_file':xxx, 'frame_idx':xxx, 'dataset_name':xxx} + + # prepare all datasets path + self.video_path = [] + data_json_path = f'{data_json_path}/{mode}_all.json' + with open(data_json_path, "r") as f: + self.samples = json.load(f) + self.video_path = [os.path.join(data_root_path, sample['dataset_name']) for sample in self.samples] + + print(f"ALL dataset, {len(self.samples)} samples in total") + + # with open(f'{self.args.action_json}', "r") as f: + # self.stat = json.load(f) + self.a_min = np.array(args.action_01)[None,:] + self.a_max = np.array(args.action_99)[None,:] + self.s_min = np.array(args.state_01)[None,:] + self.s_max = np.array(args.state_99)[None,:] + print(f"action min: {self.a_min.shape}, action max: {self.a_max.shape}") + + def __len__(self): + return len(self.samples) + + def _load_latent_video(self, video_path, frame_ids): + # video_path = video_path.split('/')[:-1] + # video_path = '/'.join(video_path)+'/0.pt' + + # print(video_path) + with open(video_path,'rb') as file: + video_tensor = torch.load(file) + video_tensor.requires_grad = False + # vr = VideoReader(video_path, ctx=cpu(0), num_threads=2) + # print(video_tensor.size(),np.array(frame_ids)) + try: + assert (np.array(frame_ids) < video_tensor.size()[0]).all() + assert (np.array(frame_ids) >= 0).all() + except: + assert False + frame_data = video_tensor[frame_ids] + return frame_data + + def _get_frames(self, label, frame_ids, cam_id, pre_encode, video_dir, use_img_cond=False): + # directly load videos latent after svd-vae encoder + assert cam_id is not None + assert pre_encode == True + if pre_encode: + video_path = label['latent_videos'][cam_id]['latent_video_path'] + try: + video_path = os.path.join(video_dir,video_path) + frames = self._load_latent_video(video_path, frame_ids) + except: + video_path = video_path.replace("latent_videos", "latent_videos_svd") + frames = self._load_latent_video(video_path, frame_ids) + # load original videos + else: + if use_img_cond: + frame_ids = frame_ids[0] + video_path = label['videos'][cam_id]['video_path'] + video_path = os.path.join(video_dir,video_path) + # frames = self._load_video(video_path, frame_ids) + # frames = mediapy.read_video(video_path) + vr = decord.VideoReader(video_path) + frames = vr[frame_ids].asnumpy() + frames = torch.from_numpy(frames).permute(2,0,1).unsqueeze(0) # (frame, h, w, c) -> (frame, c, h, w) + # resize the video to self.args.video_size + frames = self.preprocess(frames) + return frames + + def _get_obs(self, label, frame_ids, cam_id, pre_encode, video_dir): + if cam_id is None: + temp_cam_id = random.choice(self.cam_ids) + else: + temp_cam_id = cam_id + frames = self._get_frames(label, frame_ids, cam_id = temp_cam_id, pre_encode = pre_encode, video_dir=video_dir) + return frames, temp_cam_id + + def normalize_bound( + self, + data: np.ndarray, + data_min: np.ndarray, + data_max: np.ndarray, + clip_min: float = -1, + clip_max: float = 1, + eps: float = 1e-8, + ) -> np.ndarray: + ndata = 2 * (data - data_min) / (data_max - data_min + eps) - 1 + return np.clip(ndata, clip_min, clip_max) + + def denormalize_bound( + self, + data: np.ndarray, + data_min: np.ndarray, + data_max: np.ndarray, + clip_min: float = -1, + clip_max: float = 1, + eps=1e-8, + ) -> np.ndarray: + clip_range = clip_max - clip_min + rdata = (data - clip_min) / clip_range * (data_max - data_min) + data_min + return rdata + + def process_action_xhand(self, label,frame_ids, rel = False): + num_frames = len(frame_ids) + frame_ids = frame_ids[:int(self.args.num_frames)] # (f) + states = np.array(label['states'])[frame_ids] #(f, 38) + command = np.array(label['actions'])[frame_ids] + + # print(f'states: {states.shape}, actions: {command.shape}') + + state = states[0:1] # current state + + a_dim = command.shape[-1] + action_base = state[:,:a_dim] #(1,38) + actions = command - action_base #(self.args.num_frames,38) + + # normalize + action_scaled = self.normalize_bound(actions, self.a_min, self.a_max) + state_scaled = self.normalize_bound(state, self.s_min, self.s_max) + return torch.from_numpy(action_scaled).float(), torch.from_numpy(state_scaled).float() + + def __getitem__(self, index, cam_id = None, return_video = False): + + sample = self.samples[index] + sampled_video_dir = self.video_path[index] + + ann_file = sample['ann_file'] + # dataset_name = sample['dataset_name'] + ann_file = f'{sampled_video_dir}/{ann_file}' + frame_ids = sample['frame_ids'] + with open(ann_file, "r") as f: + label = json.load(f) + + data = dict() + # action + data['actions'], data['state_obs'] = self.process_action_xhand(label,frame_ids,rel=self.args.relative) + # instructions + data['lang_text'] = label['texts'][0] + # observation + static_latent, cam_id = self._get_obs(label, frame_ids[0], cam_id=0, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + gripper_latent, cam_id = self._get_obs(label, frame_ids[0], cam_id=1, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + gripper_latent2, cam_id = self._get_obs(label, frame_ids[0], cam_id=2, pre_encode=self.args.pre_encode,video_dir=sampled_video_dir) + static_latent = static_latent.unsqueeze(0) + gripper_latent = gripper_latent.unsqueeze(0) # (1,4,32,32) + gripper_latent2 = gripper_latent2.unsqueeze(0) + + # one sample + rgb_obs = {'rgb_static': static_latent, 'rgb_gripper': gripper_latent, 'rgb_gripper2': gripper_latent2} + data['rgb_obs'] = rgb_obs + data['ann_file'] = ann_file + data['frame_ids'] = frame_ids + + return data + + +if __name__ == "__main__": + from hydra import compose, initialize + from omegaconf import OmegaConf + with initialize(config_path="../../conf", job_name="VPP_xbot_train.yaml"): + cfg = compose(config_name="VPP_xbot_train") + + # import sys + # sys.path.append('/cephfs/cjyyj/code/video_robot_svd-main/mdt') + # from utils.util import get_args + # train_args = get_args(cfg.datamodule.args) + # print(train_args) + train_dataset = Dataset_xbot(cfg.dataset_args,mode="val") + train_loader = torch.utils.data.DataLoader( + train_dataset, + batch_size=cfg.dataset_args.batch_size, + shuffle=cfg.dataset_args.shuffle, + ) + for data in tqdm(train_loader,total=len(train_loader)): + print(data['ann_file']) + print(len(data['rgb_obs'])) + + \ No newline at end of file diff --git a/code/policy_models/edm_diffusion/__init__.py b/code/policy_models/edm_diffusion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/edm_diffusion/__pycache__/__init__.cpython-310.pyc b/code/policy_models/edm_diffusion/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d98d292dbdd6faf93fe16378871a5b0921605ae Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/edm_diffusion/__pycache__/__init__.cpython-39.pyc b/code/policy_models/edm_diffusion/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..043ba60a923d8a9f65d6d498a381f3faab158749 Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/__init__.cpython-39.pyc differ diff --git a/code/policy_models/edm_diffusion/__pycache__/gc_sampling.cpython-310.pyc b/code/policy_models/edm_diffusion/__pycache__/gc_sampling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47163cc0d8c4fff09842c36f303e74ff35035b40 Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/gc_sampling.cpython-310.pyc differ diff --git a/code/policy_models/edm_diffusion/__pycache__/gc_sampling.cpython-39.pyc b/code/policy_models/edm_diffusion/__pycache__/gc_sampling.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73ee4b4dedf1cc85ce4f298fa82808535ac07972 Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/gc_sampling.cpython-39.pyc differ diff --git a/code/policy_models/edm_diffusion/__pycache__/score_wrappers.cpython-310.pyc b/code/policy_models/edm_diffusion/__pycache__/score_wrappers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b99af8240c742d9c47bf6f9145d2f66d5083c73b Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/score_wrappers.cpython-310.pyc differ diff --git a/code/policy_models/edm_diffusion/__pycache__/score_wrappers.cpython-39.pyc b/code/policy_models/edm_diffusion/__pycache__/score_wrappers.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f3807c2d141982b3cf76b4ae530cde159f3f143 Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/score_wrappers.cpython-39.pyc differ diff --git a/code/policy_models/edm_diffusion/__pycache__/utils.cpython-310.pyc b/code/policy_models/edm_diffusion/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4d0587a9fd86f830b650d95aeb47ebe6f28a77e Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/utils.cpython-310.pyc differ diff --git a/code/policy_models/edm_diffusion/__pycache__/utils.cpython-39.pyc b/code/policy_models/edm_diffusion/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8390f102dc059c2f319f8d1a5a86a9723c8c4cb8 Binary files /dev/null and b/code/policy_models/edm_diffusion/__pycache__/utils.cpython-39.pyc differ diff --git a/code/policy_models/edm_diffusion/gc_sampling.py b/code/policy_models/edm_diffusion/gc_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3084e8cf2673e7160ae54cf1cba5f4b591d123 --- /dev/null +++ b/code/policy_models/edm_diffusion/gc_sampling.py @@ -0,0 +1,1007 @@ +import math +import os + +from scipy import integrate +import torch +from torch import nn +import torchsde +from torchdiffeq import odeint +from tqdm.auto import trange, tqdm +from matplotlib import pyplot as plt +import numpy as np + +from . import utils + + +''' +Code adapted for state-action based sampling with/without goal-conditioning: + +https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py +''' + +def append_zero(action): + return torch.cat([action, action.new_zeros([1])]) + + +def get_sigmas_karras(n, sigma_min, sigma_max, rho=7., device='cpu'): + """Constructs the noise schedule of Karras et al. (2022).""" + ramp = torch.linspace(0, 1, n) + min_inv_rho = sigma_min ** (1 / rho) + max_inv_rho = sigma_max ** (1 / rho) + sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho + return append_zero(sigmas).to(device) + + +def get_sigmas_exponential(n, sigma_min, sigma_max, device='cpu'): + """Constructs an exponential noise schedule.""" + sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), n, device=device).exp() + return append_zero(sigmas) + + +def get_sigmas_linear(n, sigma_min, sigma_max, device='cpu'): + """Constructs an linear noise schedule.""" + sigmas = torch.linspace(sigma_max, sigma_min, n, device=device) + return append_zero(sigmas) + + +def cosine_beta_schedule(n, s=0.008, device='cpu'): + """ + cosine schedule + as proposed in https://openreview.net/forum?id=-NEXDKk8gZ + """ + steps = n + 1 + x = np.linspace(0, steps, steps) + alphas_cumprod = np.cos(((x / steps) + s) / (1 + s) * np.pi * 0.5) ** 2 + alphas_cumprod = alphas_cumprod / alphas_cumprod[0] + betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) + betas_clipped = np.clip(betas, a_min=0, a_max=0.999) + return append_zero(torch.tensor(np.flip(betas_clipped).copy(), device=device, dtype=torch.float32)) + + +def get_sigmas_ve(n, sigma_min=0.02, sigma_max=100, device='cpu'): + """Constructs a continuous VP noise schedule.""" + # (sigma_max ** 2) * ((sigma_min ** 2 / sigma_max ** 2) ** (step_indices / (num_steps - 1))) + steps = n + 1 + t = torch.linspace(0, steps, n, device=device) + t = (sigma_max ** 2) * ((sigma_min ** 2 / sigma_max ** 2) ** (t / (n - 1))) + sigmas = torch.sqrt(t) + return append_zero(sigmas) + + +def get_iddpm_sigmas(n, sigma_min=0.02, sigma_max=100, M=1000, j_0=0, C_1=0.001, C_2=0.008, device='cpu'): + """Constructs a continuous VP noise schedule.""" + # (sigma_max ** 2) * ((sigma_min ** 2 / sigma_max ** 2) ** (step_indices / (num_steps - 1))) + step_indices = torch.arange(n, dtype=torch.float64, device=device) + u = torch.zeros(M + 1, dtype=torch.float64, device=device) + alpha_bar = lambda j: (0.5 * np.pi * j / M / (C_2 + 1)).sin() ** 2 + for j in torch.arange(M, j_0, -1, device=device): # M, ..., 1 + u[j - 1] = ((u[j] ** 2 + 1) / (alpha_bar(j - 1) / alpha_bar(j)).clip(min=C_1) - 1).sqrt() + u_filtered = u[torch.logical_and(u >= sigma_min, u <= sigma_max)] + sigmas = u_filtered[((len(u_filtered) - 1) / (n - 1) * step_indices).round().to(torch.int64)] + return append_zero(sigmas).to(torch.float32) + + +def get_sigmas_vp(n, beta_d=19.9, beta_min=0.1, eps_s=1e-3, device='cpu'): + """Constructs a continuous VP noise schedule.""" + t = torch.linspace(1, eps_s, n, device=device) + sigmas = torch.sqrt(torch.exp(beta_d * t ** 2 / 2 + beta_min * t) - 1) + return append_zero(sigmas) + + +def to_d(action, sigma, denoised): + """Converts a denoiser output to a Karras ODE derivative.""" + return (action- denoised) / utils.append_dims(sigma, action.ndim) + + + +def default_noise_sampler(x): + return lambda sigma, sigma_next: torch.randn_like(x) + + + +def get_ancestral_step(sigma_from, sigma_to, eta=1.): + """Calculates the noise level (sigma_down) to step down to and the amount + of noise to add (sigma_up) when doing an ancestral sampling step.""" + if not eta: + return sigma_to, 0. + sigma_up = min(sigma_to, eta * (sigma_to ** 2 * (sigma_from ** 2 - sigma_to ** 2) / sigma_from ** 2) ** 0.5) + sigma_down = (sigma_to ** 2 - sigma_up ** 2) ** 0.5 + return sigma_down, sigma_up + + +class BatchedBrownianTree: + """A wrapper around torchsde.BrownianTree that enables batches of entropy.""" + + def __init__(self, x, t0, t1, seed=None, **kwargs): + t0, t1, self.sign = self.sort(t0, t1) + w0 = kwargs.get('w0', torch.zeros_like(x)) + if seed is None: + seed = torch.randint(0, 2 ** 63 - 1, []).item() + self.batched = True + try: + assert len(seed) == x.shape[0] + w0 = w0[0] + except TypeError: + seed = [seed] + self.batched = False + self.trees = [torchsde.BrownianTree(t0, w0, t1, entropy=s, **kwargs) for s in seed] + + @staticmethod + def sort(a, b): + return (a, b, 1) if a < b else (b, a, -1) + + def __call__(self, t0, t1): + t0, t1, sign = self.sort(t0, t1) + w = torch.stack([tree(t0, t1) for tree in self.trees]) * (self.sign * sign) + return w if self.batched else w[0] + + +class BrownianTreeNoiseSampler: + """A noise sampler backed by a torchsde.BrownianTree. + Args: + x (Tensor): The tensor whose shape, device and dtype to use to generate + random samples. + sigma_min (float): The low end of the valid interval. + sigma_max (float): The high end of the valid interval. + seed (int or List[int]): The random seed. If a list of seeds is + supplied instead of a single integer, then the noise sampler will + use one BrownianTree per batch item, each with its own seed. + transform (callable): A function that maps sigma to the sampler's + internal timestep. + """ + + def __init__(self, x, sigma_min, sigma_max, seed=None, transform=lambda x: x): + self.transform = transform + t0, t1 = self.transform(torch.as_tensor(sigma_min)), self.transform(torch.as_tensor(sigma_max)) + self.tree = BatchedBrownianTree(x, t0, t1, seed) + + def __call__(self, sigma, sigma_next): + t0, t1 = self.transform(torch.as_tensor(sigma)), self.transform(torch.as_tensor(sigma_next)) + return self.tree(t0, t1) / (t1 - t0).abs().sqrt() + + + +@torch.no_grad() +def sample_euler( + model, + state: torch.Tensor, + action: torch.Tensor, + goal: torch.Tensor, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + s_churn=0., + s_tmin=0., + s_tmax=float('inf'), + s_noise=1. +): + """ + Implements a variant of Algorithm 2 (Euler steps) from Karras et al. (2022). + Stochastic sampler, which combines a first order ODE solver with explicit Langevin-like "churn" + of adding and removing noise. + Every update consists of these substeps: + 1. Addition of noise given the factor eps + 2. Solving the ODE dx/dt at timestep t using the score model + 3. Take Euler step from t -> t+1 to get x_{i+1} + + In contrast to the Heun variant, this variant does not compute a 2nd order correction step + For S_churn=0 the solver is an ODE solver + """ + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + for i in trange(len(sigmas) - 1, disable=disable): + gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0. + eps = torch.randn_like(action) * s_noise # sample current noise depnding on S_noise + sigma_hat = sigmas[i] * (gamma + 1) # add noise to sigma + # print(action[:, -1, :]) + if gamma > 0: # if gamma > 0, use additional noise level for computation + action = action + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5 + denoised = model(state, action, goal, sigma_hat * s_in, **extra_args) # compute denoised action + d = to_d(action, sigma_hat, denoised) # compute derivative + if callback is not None: + callback({'x': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised}) + dt = sigmas[i + 1] - sigma_hat # compute timestep + # Euler method + action = action + d * dt # take Euler step + if scaler is not None: + action = scaler.clip_output(action) + return action + + +@torch.no_grad() +def sample_euler_ancestral( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + eta=1. +): + """ + Ancestral sampling with Euler method steps. + + 1. compute dx_{i}/dt at the current timestep + 2. get \sigma_{up} and \sigma_{down} from ancestral method + 3. compute x_{t-1} = x_{t} + dx_{t}/dt * \sigma_{down} + 4. Add additional noise after the update step x_{t-1} =x_{t-1} + z * \sigma_{up} + """ + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + for i in trange(len(sigmas) - 1, disable=disable): + # compute x_{t-1} + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + # get ancestral steps + sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) + if callback is not None: + callback({'x': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + # compute dx/dt + d = to_d(action, sigmas[i], denoised) + # compute dt based on sigma_down value + dt = sigma_down - sigmas[i] + # update current action + action = action + d * dt + if sigma_down > 0: + action = action + torch.randn_like(action) * sigma_up + if scaler is not None: + action = scaler.clip_output(action) + return action + + +@torch.no_grad() +def sample_heun( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + s_churn=0., + s_tmin=0., + s_tmax=float('inf'), + s_noise=1. +): + """ + Implements Algorithm 2 (Heun steps) from Karras et al. (2022). + For S_churn =0 this is an ODE solver otherwise SDE + Every update consists of these substeps: + 1. Addition of noise given the factor eps + 2. Solving the ODE dx/dt at timestep t using the score model + 3. Take Euler step from t -> t+1 to get x_{i+1} + 4. 2nd order correction step to get x_{i+1}^{(2)} + + In contrast to the Euler variant, this variant computes a 2nd order correction step. + """ + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + for i in trange(len(sigmas) - 1, disable=disable): + gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0. + eps = torch.randn_like(action) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + # if gamma > 0, use additional noise level for computation ODE-> SDE Solver + if gamma > 0: + action= action+ eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5 + denoised = model(state, action, goal, sigma_hat * s_in, **extra_args) + d = to_d(action, sigma_hat, denoised) + if callback is not None: + callback({'x': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised}) + dt = sigmas[i + 1] - sigma_hat + # if we only are at the last step we use an Euler step for our update otherwise the heun one + if sigmas[i + 1] == 0: + # Euler method + action= action+ d * dt + else: + # Heun's method + action_2 = action+ d * dt + denoised_2 = model(state, action_2, goal, sigmas[i + 1] * s_in,**extra_args) + d_2 = to_d( action_2, sigmas[i + 1], denoised_2) + d_prime = (d + d_2) / 2 + action= action+ d_prime * dt + # scale if wanted + if scaler is not None: + action = scaler.clip_output(action) + return action + + +@torch.no_grad() +def sample_dpm_2( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + s_churn=0., + s_tmin=0., + s_tmax=float('inf'), + s_noise=1. +): + """ + A sampler inspired by DPM-Solver-2 and Algorithm 2 from Karras et al. (2022). + SDE for S_churn!=0 and ODE otherwise + + 1. + + Last denoising step is an Euler step + """ + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + for i in trange(len(sigmas) - 1, disable=disable): + # compute stochastic gamma if s_churn > 0: + gamma = min(s_churn / (len(sigmas) - 1), 2 ** 0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0. + + eps = torch.randn_like(action) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + # add noise to our current action sample in SDE case + if gamma > 0: + action = action + eps * (sigma_hat ** 2 - sigmas[i] ** 2) ** 0.5 + # compute the derivative dx/dt at timestep t + denoised = model(state, action, goal, sigma_hat * s_in, **extra_args) + d = to_d(action, sigma_hat, denoised) + + if callback is not None: + callback({'action': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigma_hat, 'denoised': denoised}) + + # if we are at the last timestep: use Euler method + if sigmas[i + 1] == 0: + # Euler method + dt = sigmas[i + 1] - sigma_hat + action = action + d * dt + else: + # use Heun 2nd order update step + sigma_mid = sigma_hat.log().lerp(sigmas[i + 1].log(), 0.5).exp() + dt_1 = sigma_mid - sigma_hat + dt_2 = sigmas[i + 1] - sigma_hat + action_2 = action + d * dt_1 + denoised_2 = model(state, action_2, goal, sigma_mid * s_in, **extra_args) + d_2 = to_d( action_2, sigma_mid, denoised_2) + action = action + d_2 * dt_2 + if scaler is not None: + action = scaler.clip_output(action) + return action + + +@torch.no_grad() +def sample_dpm_2_ancestral(model, state, action, goal, sigmas, scaler=None, extra_args=None, callback=None, disable=None, eta=1.): + """ + Ancestral sampling with DPM-Solver inspired second-order steps. + + Ancestral sampling is based on the DDPM paper (https://arxiv.org/abs/2006.11239) generation process. + Song et al. (2021) show that ancestral sampling can be used to improve the performance of DDPM for its SDE formulation. + + 1. Compute dx_{i}/dt at the current timestep + + """ + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) + if callback is not None: + callback({'x': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + d = to_d(action, sigmas[i], denoised) + if sigma_down == 0: + # Euler method + dt = sigma_down - sigmas[i] + action= action+ d * dt + else: + # DPM-Solver-2 + sigma_mid = sigmas[i].log().lerp(sigma_down.log(), 0.5).exp() + dt_1 = sigma_mid - sigmas[i] + dt_2 = sigma_down - sigmas[i] + action_2 = action+ d * dt_1 + denoised_2 = model(state, action_2, goal, sigma_mid * s_in, **extra_args) + d_2 = to_d( action_2, sigma_mid, denoised_2) + action= action+ d_2 * dt_2 + action= action+ torch.randn_like(action) * sigma_up + if scaler is not None: + action = scaler.clip_output(action) + return action + + +def linear_multistep_coeff(order, t, i, j): + ''' + Returns the coefficient of the j-th derivative of the i-th step of a linear multistep method. + ''' + if order - 1 > i: + raise ValueError(f'Order {order} too high for step {i}') + def fn(tau): + prod = 1. + for k in range(order): + if j == k: + continue + prod *= (tau - t[i - k]) / (t[i - j] - t[i - k]) + return prod + return integrate.quad(fn, t[i], t[i + 1], epsrel=1e-4)[0] + + +@torch.no_grad() +def sample_lms( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + order=4 +): + ''' + A linear multistep sampler. + + 1. compute x_{t-1} using the current noise level + 2. compute dx/dt at x_{t-1} using the current noise level + ''' + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + sigmas_cpu = sigmas.detach().cpu().numpy() + ds = [] + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + d = to_d(action, sigmas[i], denoised) + ds.append(d) + if len(ds) > order: + ds.pop(0) + if callback is not None: + callback({'x': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + cur_order = min(i + 1, order) + coeffs = [linear_multistep_coeff(cur_order, sigmas_cpu, i, j) for j in range(cur_order)] + action = action + sum(coeff * d for coeff, d in zip(coeffs, reversed(ds))) + if scaler is not None: + action = scaler.clip_output(action) + return action + + +@torch.no_grad() +def log_likelihood(model, state, action, goal, sigma_min, sigma_max, extra_args=None, atol=1e-4, rtol=1e-4): + ''' + Computes the log-likelihood of actions + ''' + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + v = torch.randint_like(action, 2) * 2 - 1 + fevals = 0 + def ode_fn(sigma, action): + nonlocal fevals + with torch.enable_grad(): + action= action[0].detach().requires_grad_() + denoised = model(state, action, goal, sigma * s_in, **extra_args) + d = to_d(action, sigma, denoised) + fevals += 1 + grad = torch.autograd.grad((d * v).sum(), action)[0] + d_ll = (v * grad).flatten(1).sum(1) + return d.detach(), d_ll + action_min = action, action.new_zeros([action.shape[0]]) + t = action.new_tensor([sigma_min, sigma_max]) + sol = odeint(ode_fn, action_min, t, atol=atol, rtol=rtol, method='dopri5') + latent, delta_ll = sol[0][-1], sol[1][-1] + ll_prior = torch.distributions.Normal(0, sigma_max).log_prob(latent).flatten(1).sum(1) + return ll_prior + delta_ll, {'fevals': fevals} + + +class PIDStepSizeController: + """A PID controller for ODE adaptive step size control.""" + def __init__(self, h, pcoeff, icoeff, dcoeff, order=1, accept_safety=0.81, eps=1e-8): + self.h = h + self.b1 = (pcoeff + icoeff + dcoeff) / order + self.b2 = -(pcoeff + 2 * dcoeff) / order + self.b3 = dcoeff / order + self.accept_safety = accept_safety + self.eps = eps + self.errs = [] + + def limiter(self, action): + return 1 + math.atan(action- 1) + + def propose_step(self, error): + inv_error = 1 / (float(error) + self.eps) + if not self.errs: + self.errs = [inv_error, inv_error, inv_error] + self.errs[0] = inv_error + factor = self.errs[0] ** self.b1 * self.errs[1] ** self.b2 * self.errs[2] ** self.b3 + factor = self.limiter(factor) + accept = factor >= self.accept_safety + if accept: + self.errs[2] = self.errs[1] + self.errs[1] = self.errs[0] + self.h *= factor + return accept + + +class DPMSolver(nn.Module): + """DPM-Solver. See https://arxiv.org/abs/2206.00927.""" + + def __init__(self, model, extra_args=None, eps_callback=None, info_callback=None): + super().__init__() + self.model = model + self.extra_args = {} if extra_args is None else extra_args + self.eps_callback = eps_callback + self.info_callback = info_callback + + def t(self, sigma): + return -sigma.log() + + def sigma(self, t): + return t.neg().exp() + + def eps(self, eps_cache, key, state, action, goal, t, *args, **kwargs): + if key in eps_cache: + return eps_cache[key], eps_cache + sigma = self.sigma(t) * action.new_ones([action.shape[0]]) + eps = (action - self.model(state, action, goal, sigma, *args, **self.extra_args, **kwargs)) / self.sigma(t) + if self.eps_callback is not None: + self.eps_callback() + return eps, {key: eps, **eps_cache} + + def dpm_solver_1_step(self, state, action, goal, t, t_next, eps_cache=None): + eps_cache = {} if eps_cache is None else eps_cache + h = t_next - t + eps, eps_cache = self.eps(eps_cache, 'eps', state, action, goal, t) + action_1 = action- self.sigma(t_next) * h.expm1() * eps + return action_1, eps_cache + + def dpm_solver_2_step(self, state, action, goal, t, t_next, r1=1 / 2, eps_cache=None): + eps_cache = {} if eps_cache is None else eps_cache + h = t_next - t + eps, eps_cache = self.eps(eps_cache, 'eps', state, action, goal, t) + s1 = t + r1 * h + u1 = action - self.sigma(s1) * (r1 * h).expm1() * eps + eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', state, u1, goal, s1) + action_2 = action - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / (2 * r1) * h.expm1() * (eps_r1 - eps) + return action_2, eps_cache + + def dpm_solver_3_step(self, state, action, goal, t, t_next, r1=1 / 3, r2=2 / 3, eps_cache=None): + eps_cache = {} if eps_cache is None else eps_cache + h = t_next - t + eps, eps_cache = self.eps(eps_cache, 'eps', state, action, goal, t) + s1 = t + r1 * h + s2 = t + r2 * h + u1 = action - self.sigma(s1) * (r1 * h).expm1() * eps + eps_r1, eps_cache = self.eps(eps_cache, 'eps_r1', state, u1, goal, s1) + u2 = action - self.sigma(s2) * (r2 * h).expm1() * eps - self.sigma(s2) * (r2 / r1) * ((r2 * h).expm1() / (r2 * h) - 1) * (eps_r1 - eps) + eps_r2, eps_cache = self.eps(eps_cache, 'eps_r2', state, u2, goal, s2) + action_3 = action - self.sigma(t_next) * h.expm1() * eps - self.sigma(t_next) / r2 * (h.expm1() / h - 1) * (eps_r2 - eps) + return action_3, eps_cache + + def dpm_solver_fast(self, state, action, goal, t_start, t_end, nfe, eta=0., s_noise=1., noise_sampler=None): + noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler + if not t_end > t_start and eta: + raise ValueError('eta must be 0 for reverse sampling') + + m = math.floor(nfe / 3) + 1 + ts = torch.linspace(t_start, t_end, m + 1, device=action.device) + + if nfe % 3 == 0: + orders = [3] * (m - 2) + [2, 1] + else: + orders = [3] * (m - 1) + [nfe % 3] + + for i in range(len(orders)): + eps_cache = {} + t, t_next = ts[i], ts[i + 1] + if eta: + sd, su = get_ancestral_step(self.sigma(t), self.sigma(t_next), eta) + t_next_ = torch.minimum(t_end, self.t(sd)) + su = (self.sigma(t_next) ** 2 - self.sigma(t_next_) ** 2) ** 0.5 + else: + t_next_, su = t_next, 0. + + eps, eps_cache = self.eps(eps_cache, 'eps', state, action, goal, t) + denoised = action- self.sigma(t) * eps + if self.info_callback is not None: + self.info_callback({'x': action, 'i': i, 't': ts[i], 't_up': t, 'denoised': denoised}) + + if orders[i] == 1: + action, eps_cache = self.dpm_solver_1_step(state, action, goal, t, t_next_, eps_cache=eps_cache) + elif orders[i] == 2: + action, eps_cache = self.dpm_solver_2_step(state, action, goal, t, t_next_, eps_cache=eps_cache) + else: + action, eps_cache = self.dpm_solver_3_step(state, action, goal, t, t_next_, eps_cache=eps_cache) + + action= action+ su * s_noise * noise_sampler(self.sigma(t), self.sigma(t_next)) + + return action + + def dpm_solver_adaptive(self, state, action, goal, t_start, t_end, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1.): + noise_sampler = default_noise_sampler(action) if noise_sampler is None else noise_sampler + if order not in {2, 3}: + raise ValueError('order should be 2 or 3') + forward = t_end > t_start + if not forward and eta: + raise ValueError('eta must be 0 for reverse sampling') + h_init = abs(h_init) * (1 if forward else -1) + atol = torch.tensor(atol) + rtol = torch.tensor(rtol) + s = t_start + action_prev = action + accept = True + pid = PIDStepSizeController(h_init, pcoeff, icoeff, dcoeff, 1.5 if eta else order, accept_safety) + info = {'steps': 0, 'nfe': 0, 'n_accept': 0, 'n_reject': 0} + + while s < t_end - 1e-5 if forward else s > t_end + 1e-5: + eps_cache = {} + t = torch.minimum(t_end, s + pid.h) if forward else torch.maximum(t_end, s + pid.h) + if eta: + sd, su = get_ancestral_step(self.sigma(s), self.sigma(t), eta) + t_ = torch.minimum(t_end, self.t(sd)) + su = (self.sigma(t) ** 2 - self.sigma(t_) ** 2) ** 0.5 + else: + t_, su = t, 0. + + eps, eps_cache = self.eps(eps_cache, 'eps', state, action, goal, s) + denoised = action - self.sigma(s) * eps + + if order == 2: + action_low, eps_cache = self.dpm_solver_1_step(state, action, goal, s, t_, eps_cache=eps_cache) + action_high, eps_cache = self.dpm_solver_2_step(state, action, goal, s, t_, eps_cache=eps_cache) + else: + action_low, eps_cache = self.dpm_solver_2_step(state, action, goal, s, t_, r1=1 / 3, eps_cache=eps_cache) + action_high, eps_cache = self.dpm_solver_3_step(state, action, goal, s, t_, eps_cache=eps_cache) + delta = torch.maximum(atol, rtol * torch.maximum( action_low.abs(), action_prev.abs())) + error = torch.linalg.norm(( action_low - action_high) / delta) / action.numel() ** 0.5 + accept = pid.propose_step(error) + if accept: + action_prev = action_low + action = action_high + su * s_noise * noise_sampler(self.sigma(s), self.sigma(t)) + s = t + info['n_accept'] += 1 + else: + info['n_reject'] += 1 + info['nfe'] += order + info['steps'] += 1 + + if self.info_callback is not None: + self.info_callback({'x': action, 'i': info['steps'] - 1, 't': s, 't_up': s, 'denoised': denoised, 'error': error, 'h': pid.h, **info}) + + return action, info + + +@torch.no_grad() +def sample_dpm_fast( + model, + state, + action, + goal, + sigma_min, + sigma_max, + n, + scaler=None, + extra_args=None, + callback=None, + disable=None, + eta=0., + s_noise=1., + noise_sampler=None +): + """DPM-Solver-Fast (fixed step size). See https://arxiv.org/abs/2206.00927.""" + if sigma_min <= 0 or sigma_max <= 0: + raise ValueError('sigma_min and sigma_maactionmust not be 0') + with tqdm(total=n, disable=disable) as pbar: + dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update) + if callback is not None: + dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info}) + return dpm_solver.dpm_solver_fast(state, action, goal, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), n, eta, s_noise, noise_sampler) + + +@torch.no_grad() +def sample_dpmpp_2m( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None +): + """DPM-Solver++(2M).""" + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + sigma_fn = lambda t: t.neg().exp() + t_fn = lambda sigma: sigma.log().neg() + old_denoised = None + + for i in trange(len(sigmas) - 1, disable=disable): + # predict the next action + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + if callback is not None: + callback({'action': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1]) + h = t_next - t + if old_denoised is None or sigmas[i + 1] == 0: + action = (sigma_fn(t_next) / sigma_fn(t)) * action - (-h).expm1() * denoised + else: + h_last = t - t_fn(sigmas[i - 1]) + r = h_last / h + denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised + action = (sigma_fn(t_next) / sigma_fn(t)) * action - (-h).expm1() * denoised_d + old_denoised = denoised + return action + + +@torch.no_grad() +def sample_dpmpp_sde( + model, + state, + action, + goal, + sigmas, + extra_args=None, + callback=None, + disable=None, + eta=1., + s_noise=1., + scaler=None, + noise_sampler=None, + r=1 / 2 +): + """DPM-Solver++ (stochastic).""" + x = action + sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() + noise_sampler = BrownianTreeNoiseSampler(x, sigma_min, sigma_max) if noise_sampler is None else noise_sampler + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + sigma_fn = lambda t: t.neg().exp() + t_fn = lambda sigma: sigma.log().neg() + + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(state, x, goal, sigmas[i] * s_in, **extra_args) + if callback is not None: + callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + if sigmas[i + 1] == 0: + # Euler method + d = to_d(x, sigmas[i], denoised) + dt = sigmas[i + 1] - sigmas[i] + x = x + d * dt + else: + # DPM-Solver++ + t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1]) + h = t_next - t + s = t + h * r + fac = 1 / (2 * r) + + # Step 1 + sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(s), eta) + s_ = t_fn(sd) + x_2 = (sigma_fn(s_) / sigma_fn(t)) * x - (t - s_).expm1() * denoised + x_2 = x_2 + noise_sampler(sigma_fn(t), sigma_fn(s)) * s_noise * su + denoised_2 = model(state, x_2, goal, sigma_fn(s) * s_in, **extra_args) + + # Step 2 + sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(t_next), eta) + t_next_ = t_fn(sd) + denoised_d = (1 - fac) * denoised + fac * denoised_2 + x = (sigma_fn(t_next_) / sigma_fn(t)) * x - (t - t_next_).expm1() * denoised_d + x = x + noise_sampler(sigma_fn(t), sigma_fn(t_next)) * s_noise * su + if scaler is not None: + x = scaler.clip_output(x) + return x + + + +@torch.no_grad() +def sample_dpmpp_2_with_lms( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None +): + """DPM-Solver++(2M).""" + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + sigma_fn = lambda t: t.neg().exp() + t_fn = lambda sigma: sigma.log().neg() + old_denoised = None + + for i in trange(len(sigmas) - 1, disable=disable): + # predict the next action + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + if callback is not None: + callback({'action': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1]) + h = t_next - t + if old_denoised is None or sigmas[i + 1] == 0: + action = (sigma_fn(t_next) / sigma_fn(t)) * action - (-h).expm1() * denoised + else: + h_last = t - t_fn(sigmas[i - 1]) + r = h_last / h + denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised + action = (sigma_fn(t_next) / sigma_fn(t)) * action - (-h).expm1() * denoised_d + old_denoised = denoised + return action + + +@torch.no_grad() +def sample_dpm_adaptive( + model, + state, + action, + goal, + sigma_min, + sigma_max, + extra_args=None, + callback=None, + disable=None, + order=3, + rtol=0.05, + atol=0.0078, + h_init=0.05, + pcoeff=0., + icoeff=1., + dcoeff=0., + accept_safety=0.81, + eta=0., + s_noise=1., + return_info=False +): + """ + DPM-Solver-12 and 23 (adaptive step size). + + See https://arxiv.org/abs/2206.00927. + """ + if sigma_min <= 0 or sigma_max <= 0: + raise ValueError('sigma_min and sigma_max action nmust not be 0') + with tqdm(disable=disable) as pbar: + dpm_solver = DPMSolver(model, extra_args, eps_callback=pbar.update) + if callback is not None: + dpm_solver.info_callback = lambda info: callback({'sigma': dpm_solver.sigma(info['t']), 'sigma_hat': dpm_solver.sigma(info['t_up']), **info}) + action, info = dpm_solver.dpm_solver_adaptive(state, action, goal, dpm_solver.t(torch.tensor(sigma_max)), dpm_solver.t(torch.tensor(sigma_min)), order, rtol, atol, h_init, pcoeff, icoeff, dcoeff, accept_safety, eta, s_noise) + if return_info: + return action, info + return action + + +@torch.no_grad() +def sample_dpmpp_2s_ancestral( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + eta=1., + s_noise=1., + noise_sampler=None +): + """ + Ancestral sampling combined with DPM-Solver++(2S) second-order steps.""" + extra_args = {} if extra_args is None else extra_args + noise_sampler = default_noise_sampler(action) if noise_sampler is None else noise_sampler + s_in = action.new_ones([action.shape[0]]) + sigma_fn = lambda t: t.neg().exp() + t_fn = lambda sigma: sigma.log().neg() + + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) + if callback is not None: + callback({'action': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + if sigma_down == 0: + # Euler method + d = to_d(action, sigmas[i], denoised) + dt = sigma_down - sigmas[i] + action = action + d * dt + else: + # DPM-Solver-2++(2S) + t, t_next = t_fn(sigmas[i]), t_fn(sigma_down) + r = 1 / 2 + h = t_next - t + s = t + r * h + x_2 = (sigma_fn(s) / sigma_fn(t)) * action - (-h * r).expm1() * denoised + denoised_2 = model(state, x_2, goal, sigma_fn(s) * s_in, **extra_args) + action = (sigma_fn(t_next) / sigma_fn(t)) * action - (-h).expm1() * denoised_2 + # Noise addition + action = action + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up + if scaler is not None: + action = scaler.clip_output(action) + return action + + +@torch.no_grad() +def sample_ddim( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + eta=1., +): + """ + DPM-Solver 1( or DDIM sampler""" + extra_args = {} if extra_args is None else extra_args + s_in = action.new_ones([action.shape[0]]) + sigma_fn = lambda t: t.neg().exp() + t_fn = lambda sigma: sigma.log().neg() + old_denoised = None + + for i in trange(len(sigmas) - 1, disable=disable): + # predict the next action + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + if callback is not None: + callback({'action': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1]) + h = t_next - t + action = (sigma_fn(t_next) / sigma_fn(t)) * action - (-h).expm1() * denoised + return action + + + +@torch.no_grad() +def sample_dpmpp_2s( + model, + state, + action, + goal, + sigmas, + scaler=None, + extra_args=None, + callback=None, + disable=None, + eta=1., +): + """ + DPM-Solver++(2S) second-order steps.""" + extra_args = {} if extra_args is None else extra_args + sigma_fn = lambda t: t.neg().exp() + t_fn = lambda sigma: sigma.log().neg() + s_in = action.new_ones([action.shape[0]]) + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(state, action, goal, sigmas[i] * s_in, **extra_args) + if callback is not None: + callback({'action': action, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised}) + if sigmas[i + 1] == 0: + # Euler method + d = to_d(action, sigmas[i], denoised) + dt = sigmas[i + 1] - sigmas[i] + action = action + d * dt + else: + # DPM-Solver-2++(2S) + t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1]) + r = 1 / 2 + h = t_next - t + s = t + r * h + x_2 = (sigma_fn(s) / sigma_fn(t)) * action - (-h * r).expm1() * denoised + denoised_2 = model(state, x_2, goal, sigma_fn(s) * s_in, **extra_args) + action = (sigma_fn(t_next) / sigma_fn(t)) * action - (-h).expm1() * denoised_2 + if scaler is not None: + action = scaler.clip_output(action) + return action + + +def make_sample_contour_plot(actions, n_steps, file_store_path): + + store_path = os.path.join(file_store_path, 'action_visualization.png') + rows = n_steps % 2 + for idx, step in range(n_steps): + fig, axs = plt.subplots() + actions + store_path = os.path.join(file_store_path, f'action_visualization_step_{idx}.png') + + + \ No newline at end of file diff --git a/code/policy_models/edm_diffusion/score_wrappers.py b/code/policy_models/edm_diffusion/score_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..a34d1d55dfef2768cb0321c4df4a9b8c6494edda --- /dev/null +++ b/code/policy_models/edm_diffusion/score_wrappers.py @@ -0,0 +1,119 @@ +from torch import nn +from .utils import append_dims +from policy_models.module.diffusion_decoder import DiffusionTransformer + +''' +Wrappers for the score-based models based on Karras et al. 2022 +They are used to get improved scaling of different noise levels, which +improves training stability and model performance + +Code is adapted from: + +https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/layers.py +''' + + +class GCDenoiser(nn.Module): + """ + A Karras et al. preconditioner for denoising diffusion models. + + Args: + inner_model: The inner model used for denoising. + sigma_data: The data sigma for scalings (default: 1.0). + """ + def __init__(self, action_dim, obs_dim, goal_dim, num_tokens, goal_window_size, obs_seq_len, act_seq_len, device, sigma_data=1., proprio_dim=8): + super().__init__() + self.inner_model = DiffusionTransformer( + action_dim = action_dim, + obs_dim = obs_dim, + goal_dim = goal_dim, + proprio_dim= proprio_dim, + goal_conditioned = True, + embed_dim = 384, + n_dec_layers = 4, + n_enc_layers = 4, + n_obs_token = num_tokens, + goal_seq_len = goal_window_size, + obs_seq_len = obs_seq_len, + action_seq_len =act_seq_len, + embed_pdrob = 0, + goal_drop = 0, + attn_pdrop = 0.3, + resid_pdrop = 0.1, + mlp_pdrop = 0.05, + n_heads= 8, + device = device, + use_mlp_goal = True, + ) + self.sigma_data = sigma_data + + def get_scalings(self, sigma): + """ + Compute the scalings for the denoising process. + + Args: + sigma: The input sigma. + Returns: + The computed scalings for skip connections, output, and input. + """ + c_skip = self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2) + c_out = sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2) ** 0.5 + c_in = 1 / (sigma ** 2 + self.sigma_data ** 2) ** 0.5 + return c_skip, c_out, c_in + + def loss(self, state, action, goal, noise, sigma, **kwargs): + """ + Compute the loss for the denoising process. + + Args: + state: The input state. + action: The input action. + goal: The input goal. + noise: The input noise. + sigma: The input sigma. + **kwargs: Additional keyword arguments. + Returns: + The computed loss. + """ + c_skip, c_out, c_in = [append_dims(x, action.ndim) for x in self.get_scalings(sigma)] + noised_input = action + noise * append_dims(sigma, action.ndim) + model_output = self.inner_model(state, noised_input * c_in, goal, sigma, **kwargs) + target = (action - c_skip * noised_input) / c_out + return (model_output - target).pow(2).flatten(1).mean(), model_output + + def forward(self, state, action, goal, sigma, **kwargs): + """ + Perform the forward pass of the denoising process. + + Args: + state: The input state. + action: The input action. + goal: The input goal. + sigma: The input sigma. + **kwargs: Additional keyword arguments. + + Returns: + The output of the forward pass. + """ + c_skip, c_out, c_in = [append_dims(x, action.ndim) for x in self.get_scalings(sigma)] + return self.inner_model(state, action * c_in, goal, sigma, **kwargs) * c_out + action * c_skip + + def forward_context_only(self, state, action, goal, sigma, **kwargs): + """ + Perform the forward pass of the denoising process. + + Args: + state: The input state. + action: The input action. + goal: The input goal. + sigma: The input sigma. + **kwargs: Additional keyword arguments. + + Returns: + The output of the forward pass. + """ + c_skip, c_out, c_in = [append_dims(x, action.ndim) for x in self.get_scalings(sigma)] + return self.inner_model.forward_enc_only(state, action * c_in, goal, sigma, **kwargs) + + def get_params(self): + return self.inner_model.parameters() diff --git a/code/policy_models/edm_diffusion/utils.py b/code/policy_models/edm_diffusion/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..328eb1d2c8de3d3f344de983d5932328ecf52fa4 --- /dev/null +++ b/code/policy_models/edm_diffusion/utils.py @@ -0,0 +1,203 @@ +import torch +import math +import torch.nn as nn +import numpy as np +import einops + + +def return_time_sigma_embedding_model(embedding_type, time_embed_dim, device): + ''' + Method returns an embedding model given the chosen type + ''' + if embedding_type == 'GaussianFourier': + return GaussianFourierEmbedding(time_embed_dim, device) + elif embedding_type == 'Sinusoidal': + return SinusoidalPosEmbedding(time_embed_dim, device) + elif embedding_type == 'FourierFeatures': + return FourierFeatures(time_embed_dim, device) + else: + raise ValueError('Embedding not avaiable, please chose an existing one!') + + +class GaussianFourierProjection(nn.Module): + """Gaussian random features for encoding time steps.""" + def __init__(self, embed_dim, scale=30.): + super().__init__() + # Randomly sample weights during initialization. These weights are fixed + # during optimization and are not trainable. + self.W = nn.Parameter(torch.randn(embed_dim // 2) * scale, requires_grad=False) + + def forward(self, x): + x_proj = x[:, None] * self.W[None, :] * 2 * np.pi + return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1) + + +class FourierFeatures(nn.Module): + def __init__(self, time_embed_dim, device, in_features=1, std=1.): + super().__init__() + self.device = device + assert time_embed_dim % 2 == 0 + self.register_buffer('weight', torch.randn([time_embed_dim // 2, in_features]) * std + ) + + def forward(self, input): + if len(input.shape) == 1: + input = einops.rearrange(input, 'b -> b 1') + f = 2 * math.pi * input @ self.weight.T + return torch.cat([f.cos(), f.sin()], dim=-1).to(self.device) + + +class GaussianFourierEmbedding(nn.Module): + + def __init__(self, time_embed_dim, device): + super().__init__() + self.t_dim = time_embed_dim + self.embed = nn.Sequential( + GaussianFourierProjection(embed_dim=time_embed_dim), + nn.Linear(time_embed_dim, 2*time_embed_dim), + nn.Mish(), + nn.Linear(2*time_embed_dim, time_embed_dim) + ).to(device) + + def forward(self, t): + return self.embed(t) + + +class SinusoidalPosEmbedding(nn.Module): + + def __init__(self, time_embed_dim, device): + super().__init__() + self.device = device + self.embed = nn.Sequential( + SinusoidalPosEmb(time_embed_dim), + nn.Linear(time_embed_dim, time_embed_dim * 2), + nn.Mish(), + nn.Linear(time_embed_dim * 2, time_embed_dim), + ).to(self.device) + + def forward(self, t): + return self.embed(t) + + + +class PositionalEncoding(nn.Module): + def __init__(self, d_model, dropout=0.1, max_len=5000): + super(PositionalEncoding, self).__init__() + self.dropout = nn.Dropout(p=dropout) + + pe = torch.zeros(max_len, d_model) + position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) + div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-np.log(10000.0) / d_model)) + pe[:, 0::2] = torch.sin(position * div_term) + pe[:, 1::2] = torch.cos(position * div_term) + pe = pe.unsqueeze(0).transpose(0, 1) + + self.register_buffer('pe', pe) + + def forward(self, x): + # not used in the final model + x = x + self.pe[:x.shape[0], :] + return self.dropout(x) + + +class SinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + self.dim = dim + + def forward(self, x): + device = x.device + half_dim = self.dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, device=device) * -emb) + emb = x[:, None] * emb[None, :] + emb = torch.cat((emb.sin(), emb.cos()), dim=-1) + return emb + + +class InputEncoder(nn.Module): + + def __init__(self, input_dim, latent_dim): + super().__init__() + + self.input_dim = input_dim + self.latent_dim = latent_dim + + self.emb = nn.Linear(self.input_dim, self.latent_dim) + + def forward(self, x): + return self.emb(x) + + +class TEncoder(nn.Module): + + def __init__(self, input_dim, latent_dim): + super().__init__() + + self.input_dim = input_dim + self.latent_dim = latent_dim + + self.emb = nn.Linear(self.input_dim, self.latent_dim) + + def forward(self, x): + return self.emb(x) + + +def append_dims(x, target_dims): + """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" + dims_to_append = target_dims - x.ndim + if dims_to_append < 0: + raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less') + return x[(...,) + (None,) * dims_to_append] + + +def rand_log_normal(shape, loc=0., scale=1., device='cpu', dtype=torch.float32): + """Draws samples from a lognormal distribution.""" + return (torch.randn(shape, device=device, dtype=dtype) * scale + loc).exp() + + +def rand_log_logistic(shape, loc=0., scale=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32): + """Draws samples from an optionally truncated log-logistic distribution.""" + min_value = torch.as_tensor(min_value, device=device, dtype=torch.float64) + max_value = torch.as_tensor(max_value, device=device, dtype=torch.float64) + min_cdf = min_value.log().sub(loc).div(scale).sigmoid() + max_cdf = max_value.log().sub(loc).div(scale).sigmoid() + u = torch.rand(shape, device=device, dtype=torch.float64) * (max_cdf - min_cdf) + min_cdf + return u.logit().mul(scale).add(loc).exp().to(dtype) + + +def rand_log_uniform(shape, min_value, max_value, device='cpu', dtype=torch.float32): + """Draws samples from an log-uniform distribution.""" + min_value = math.log(min_value) + max_value = math.log(max_value) + return (torch.rand(shape, device=device, dtype=dtype) * (max_value - min_value) + min_value).exp() + + +def rand_v_diffusion(shape, sigma_data=1., min_value=0., max_value=float('inf'), device='cpu', dtype=torch.float32): + """Draws samples from a truncated v-diffusion training timestep distribution.""" + min_cdf = math.atan(min_value / sigma_data) * 2 / math.pi + max_cdf = math.atan(max_value / sigma_data) * 2 / math.pi + u = torch.rand(shape, device=device, dtype=dtype) * (max_cdf - min_cdf) + min_cdf + return torch.tan(u * math.pi / 2) * sigma_data + + +def rand_split_log_normal(shape, loc, scale_1, scale_2, device='cpu', dtype=torch.float32): + """Draws samples from a split lognormal distribution.""" + n = torch.randn(shape, device=device, dtype=dtype).abs() + u = torch.rand(shape, device=device, dtype=dtype) + n_left = n * -scale_1 + loc + n_right = n * scale_2 + loc + ratio = scale_1 / (scale_1 + scale_2) + return torch.where(u < ratio, n_left, n_right).exp() + +# Function to sample from discrete values +def rand_discrete(shape, values, device='cpu', dtype=torch.float32): + """Draws samples from the given discrete values.""" + indices = torch.randint(0, len(values), shape, device=device) + samples = torch.index_select(values, 0, indices).to(dtype) + return samples + + +def rand_uniform(shape, min_value, max_value, device='cpu', dtype=torch.float32): + """Draws samples from a uniform distribution.""" + return torch.rand(shape, device=device, dtype=dtype) * (max_value - min_value) + min_value diff --git a/code/policy_models/losses/__pycache__/step_unet_mse.cpython-310.pyc b/code/policy_models/losses/__pycache__/step_unet_mse.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfe35494f30bd389f98306845184191b5e3ee417 Binary files /dev/null and b/code/policy_models/losses/__pycache__/step_unet_mse.cpython-310.pyc differ diff --git a/code/policy_models/losses/__pycache__/step_unet_mse.cpython-39.pyc b/code/policy_models/losses/__pycache__/step_unet_mse.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2cc806d3346bbf21829bfe5b87dde36dfea03a2 Binary files /dev/null and b/code/policy_models/losses/__pycache__/step_unet_mse.cpython-39.pyc differ diff --git a/code/policy_models/losses/step_unet_mse.py b/code/policy_models/losses/step_unet_mse.py new file mode 100644 index 0000000000000000000000000000000000000000..27ee53fe2787c6b1d2664137aff520931825ed07 --- /dev/null +++ b/code/policy_models/losses/step_unet_mse.py @@ -0,0 +1,373 @@ +import torch +import torch.nn.functional as F +from einops import rearrange, repeat +import numpy as np +import random + +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=np.float64) + omega /= embed_dim / 2. + omega = 1. / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + +def encode_text(texts, tokenizer, text_encoder, img_cond=None, img_cond_mask=None, img_encoder=None, position_encode=True, use_clip=False, max_length=20): + """Encode text with optional image conditioning.""" + with torch.no_grad(): + if use_clip: + inputs = tokenizer(texts, padding='max_length', return_tensors="pt",truncation=True, max_length=max_length).to(text_encoder.device) + outputs = text_encoder(**inputs) + encoder_hidden_states = outputs.last_hidden_state # (batch, 30, 512) + if position_encode: + embed_dim, pos_num = encoder_hidden_states.shape[-1], encoder_hidden_states.shape[1] + pos = np.arange(pos_num,dtype=np.float64) + + position_encode = get_1d_sincos_pos_embed_from_grid(embed_dim, pos) + position_encode = torch.tensor(position_encode, device=encoder_hidden_states.device, dtype=encoder_hidden_states.dtype, requires_grad=False) + + encoder_hidden_states += position_encode + assert encoder_hidden_states.shape[-1] == 512 + + if img_encoder is not None: + assert img_cond is not None + assert img_cond_mask is not None + img_cond = img_cond.to(img_encoder.device) + if len(img_cond.shape) == 5: + img_cond = img_cond.squeeze(1) + + img_hidden_states = img_encoder(img_cond).image_embeds + img_hidden_states[img_cond_mask] = 0.0 + img_hidden_states = img_hidden_states.unsqueeze(1).expand(-1,encoder_hidden_states.shape[1],-1) + assert img_hidden_states.shape[-1] == 512 + encoder_hidden_states = torch.cat([encoder_hidden_states, img_hidden_states], dim=-1) + assert encoder_hidden_states.shape[-1] == 1024 + else: + encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states], dim=-1) + + else: + inputs = tokenizer(texts, padding='max_length', return_tensors="pt",truncation=True, max_length=32).to(text_encoder.device) + outputs = text_encoder(**inputs) + encoder_hidden_states = outputs.last_hidden_state # (batch, 30, 512) + assert encoder_hidden_states.shape[1:] == (32,1024) + + return encoder_hidden_states + + +def unwrap_unet(unet): + if hasattr(unet, "module"): + unet = unet.module + return unet + +def _step_unet(unet, sample, timestep, encoder_hidden_states, added_time_ids, use_layer_idx=5, all_layer=False, complete=False): + """Direct UNet forward pass with early stopping at specified layer.""" + unet = unwrap_unet(unet) + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + is_mps = sample.device.type == "mps" + if isinstance(timestep, float): + dtype = torch.float32 if is_mps else torch.float64 + else: + dtype = torch.int32 if is_mps else torch.int64 + timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) + elif len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + batch_size, num_frames = sample.shape[:2] + timesteps = timesteps.expand(batch_size) + + t_emb = unet.time_proj(timesteps) + t_emb = t_emb.to(dtype=sample.dtype) + emb = unet.time_embedding(t_emb) + + time_embeds = unet.add_time_proj(added_time_ids.flatten()) + time_embeds = time_embeds.reshape((batch_size, -1)) + time_embeds = time_embeds.to(emb.dtype) + aug_emb = unet.add_embedding(time_embeds) + emb = emb + aug_emb + + # Flatten the batch and frames dimensions + sample = sample.flatten(0, 1) + emb = emb.repeat_interleave(num_frames, dim=0) + encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0) + + # 2. pre-process + sample = unet.conv_in(sample) + + image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device) + + down_block_res_samples = (sample,) + for downsample_block in unet.down_blocks: + if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention: + sample, res_samples = downsample_block( + hidden_states=sample, + temb=emb, + encoder_hidden_states=encoder_hidden_states, + image_only_indicator=image_only_indicator, + ) + else: + sample, res_samples = downsample_block( + hidden_states=sample, + temb=emb, + image_only_indicator=image_only_indicator, + ) + + down_block_res_samples += res_samples + + # 4. mid + sample = unet.mid_block( + hidden_states=sample, + temb=emb, + encoder_hidden_states=encoder_hidden_states, + image_only_indicator=image_only_indicator, + ) + + feature_list = [] + + # 5. up + for i, upsample_block in enumerate(unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] + + if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention: + sample = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + encoder_hidden_states=encoder_hidden_states, + image_only_indicator=image_only_indicator, + ) + else: + sample = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + image_only_indicator=image_only_indicator, + ) + + if i < use_layer_idx: + factor = 2**(use_layer_idx - i) + feature_list.append(torch.nn.functional.interpolate(sample, scale_factor=factor)) + + if i == use_layer_idx and not complete: + feature_list.append(sample) + break + + if not complete: + if all_layer: + sample = torch.cat(feature_list, dim=1) + sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) + else: + sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) + return sample + else: + sample = unet.conv_norm_out(sample) + sample = unet.conv_act(sample) + sample = unet.conv_out(sample) + sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) + return sample + + +def _compute_step_unet_feature(videos, images, texts, unet, pipeline, tokenizer, text_encoder, image_encoder, args, timestep=20, extract_layer_idx=1, step_time=1, max_length=20, seed=None): + """Compute intermediate UNet feature with gradients enabled via direct UNet forward.""" + height = unet.module.config.sample_size * pipeline.vae_scale_factor // 3 + width = unet.module.config.sample_size * pipeline.vae_scale_factor // 3 + pipeline.vae.eval() + pipeline.image_encoder.eval() + device = images.device + dtype = pipeline.vae.dtype + #print('dtype:',dtype) + vae = pipeline.vae + + num_videos_per_prompt = 1 + + frames = rearrange(videos, 'b f c h w-> (b f) c h w').to(dtype) + with torch.no_grad(): + latents = vae.encode(frames).latent_dist.mode() * vae.config.scaling_factor + latents = rearrange(latents, '(b f) c h w-> b f c h w', b=images.shape[0]) + + + + + + pixel_values = images + batch_size = pixel_values.shape[0] + + pixel_values = rearrange(pixel_values, 'b f c h w-> (b f) c h w').to(dtype) + + with torch.no_grad(): + # texts, tokenizer, text_encoder, img_cond=None, img_cond_mask=None, img_encoder=None, position_encode=True, use_clip=False, max_length=20 + encoder_hidden_states = encode_text(texts, tokenizer, text_encoder, position_encode=args.position_encode, use_clip=True, max_length=max_length) + encoder_hidden_states = encoder_hidden_states.to(dtype) + image_embeddings = encoder_hidden_states + + needs_upcasting = pipeline.vae.dtype == torch.float16 and pipeline.vae.config.force_upcast + #if needs_upcasting: + # pipeline.vae.to(dtype=torch.float32) + # pixel_values.to(dtype=torch.float32) + if pixel_values.shape[-3] == 4: + image_latents = pixel_values/vae.config.scaling_factor + else: + image_latents = pipeline._encode_vae_image(pixel_values, device, num_videos_per_prompt, False) + image_latents = image_latents.to(image_embeddings.dtype) + + #print('dtype:', image_latents.dtype) + + #if needs_upcasting: + # pipeline.vae.to(dtype=torch.float16) + + #num_frames = unet.config.num_frames + num_frames = args.num_frames + image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1) + + + # num_channels_latents = unet.module.config.in_channels + + gen = None + if seed is not None: + gen = torch.Generator(device=device) + gen.manual_seed(int(seed)) + + # latents = pipeline.prepare_latents( + # batch_size * num_videos_per_prompt, + # num_frames, + # num_channels_latents, + # height, + # width, + # image_embeddings.dtype, + # device, + # gen, + # None, + # ) + rnd_normal = torch.randn([batch_size//2, 1, 1, 1, 1], device=device) + sigma = (rnd_normal * 1.6 + 0.7).exp() + c_in = 1 / (sigma**2 + 1) ** 0.5 + c_noise = (sigma.log() / 4).reshape([batch_size//2]) + loss_weight = (sigma ** 2 + 1) / sigma ** 2 + + # repreat items twice + sigma = torch.cat([sigma, sigma], dim=0) + c_noise = torch.cat([c_noise, c_noise], dim=0) + c_in = torch.cat([c_in, c_in], dim=0) + loss_weight = torch.cat([loss_weight, loss_weight], dim=0) + tmp_noise = torch.randn_like(latents.chunk(2, dim=0)[0]) + + latents = latents + torch.cat([tmp_noise, tmp_noise], dim=0) * sigma + + fps = 4 + motion_bucket_id = 127 + added_time_ids = pipeline._get_add_time_ids( + fps, + motion_bucket_id, + 0, + image_embeddings.dtype, + batch_size, + num_videos_per_prompt, + False, + ) + added_time_ids = added_time_ids.to(device) + + pipeline.scheduler.set_timesteps(timestep, device=device) + timesteps = pipeline.scheduler.timesteps + + + for i, t in enumerate(timesteps): + #print('step:',i) + if i == step_time - 1: + complete = False + else: + complete = True + # complete = True + #print('complete:',complete) + + latent_model_input = latents * c_in + # latent_model_input = pipeline.scheduler.scale_model_input(latent_model_input, t) + + # Concatenate image_latents over channels dimention + # latent_model_input = torch.cat([mask, latent_model_input, image_latents], dim=2) + latent_model_input = torch.cat([latent_model_input, image_latents], dim=2) + #print('latent_model_input_shape:',latent_model_input.shape) + #print('image_embeddings_shape:',image_embeddings.shape) + + # predict the noise residual + # print('extract_layer_idx:',extract_layer_idx) + # print('latent_model_input_shape:',latent_model_input.shape) + # print('encoder_hidden_states:',image_embeddings.shape) + feature_pred = _step_unet( + unet, + latent_model_input, + c_noise, + encoder_hidden_states=image_embeddings, + added_time_ids=added_time_ids, + use_layer_idx=extract_layer_idx, + all_layer=True, + complete=complete, + ) + # feature_pred = unet(latent_model_input,t,encoder_hidden_states=image_embeddings,added_time_ids=added_time_ids,return_dict=False,)[0] + + # print('feature_pred_shape:',feature_pred.shape) + + if not complete: + break + + latents = pipeline.scheduler.step(feature_pred, t, latents).prev_sample + + # latents = outputs.prev_sample + # pred_x0 = outputs.pred_original_sample + # frames = pipeline.decode_latents(pred_x0, num_frames) + # frames = pipeline.video_processor.postprocess_video(video=frames, output_type="np") + # import imageio + # breakpoint() + # imageio.mimsave("output.mp4", frames[0], fps=8) + return feature_pred + + +def step_unet_pairwise_mse_loss(batch, unet, pipeline, tokenizer, text_encoder, image_encoder, args, timestep=20, extract_layer_idx=1, step_time=1, max_length=20): + """ + Compute MSE between two step_unet feature passes derived from the same batch but with different noise seeds. + This keeps gradients w.r.t. UNet parameters. + """ + batchsize = batch['video'].shape[0] + # text = batch['text'][:batchsize//2] + # video = batch['video'][:batchsize//2] + text = batch['text'] + video = batch['video'] + # random select a batch of two numbers as index not the same + pairs = [random.sample(range(video.shape[1]), 2) for _ in range(video.shape[0])] + pairs = torch.tensor(pairs, device=video.device, dtype=torch.long) + + image1 = video[torch.arange(video.shape[0], device=video.device), pairs[:, 0]].unsqueeze(1) + image2 = video[torch.arange(video.shape[0], device=video.device), pairs[:, 1]].unsqueeze(1) + + # use the same seed for both images + # seed = torch.seed() + feats = _compute_step_unet_feature(torch.cat([video, video], dim=0), torch.cat([image1, image2], dim=0), text+text, unet, pipeline, tokenizer, text_encoder, image_encoder, args, timestep, extract_layer_idx, step_time, max_length) + # feat2 = _compute_step_unet_feature(image2, text, unet, pipeline, tokenizer, text_encoder, image_encoder, args, timestep, extract_layer_idx, step_time, max_length, seed=seed) + feat1, feat2 = feats.chunk(2, dim=0) + # use cosine similarity + # return F.mse_loss(feat1, feat2) + feat1 = feat1.permute(0,1,3,4,2) + feat1 = feat1.reshape(-1, feat1.shape[-1]) + feat2 = feat2.permute(0,1,3,4,2) + feat2 = feat2.reshape(-1, feat2.shape[-1]) + assert feat1.shape[-1] == 2560 + feat1 = F.normalize(feat1, dim=1) + feat2 = F.normalize(feat2, dim=1) + return 1 - (feat1 * feat2).sum(dim=1).mean() + + diff --git a/code/policy_models/module/Video_Former copy 2.py b/code/policy_models/module/Video_Former copy 2.py new file mode 100644 index 0000000000000000000000000000000000000000..f93bb52a9113dbdad8e4f0cf57af9302e4adbd96 --- /dev/null +++ b/code/policy_models/module/Video_Former copy 2.py @@ -0,0 +1,538 @@ +# This code is referenced from https://github.com/dhansmair/flamingo-mini + +import torch +from einops import rearrange, repeat +from einops_exts import rearrange_many +from torch import einsum, nn +import torch.nn.functional as F + +from policy_models.module.transformers.utils import feed_forward_layer + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + use_cross_attn=False, + y_dim=512, + qkv_bias: bool = False, + qk_norm: bool = False, + attn_drop: float = 0., + proj_drop: float = 0., + norm_layer: nn.Module = nn.LayerNorm, + attn_mask = None, + ) -> None: + super().__init__() + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.fused_attn = True + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.attn_mask = attn_mask + self.use_cross_attn=use_cross_attn + if self.use_cross_attn: + #print('use_cross_attn') + self.y_kv = nn.Linear(y_dim, dim * 2, bias=qkv_bias) + self.y_k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.gate = nn.Parameter(torch.zeros([self.num_heads])) + + def forward(self, x: torch.Tensor, y=None, attn_mask=None) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + + if self.fused_attn: + if self.attn_mask is not None: + self.attn_mask = self.attn_mask.to(x.device) + x = F.scaled_dot_product_attention( + q, k, v, + dropout_p=self.attn_drop.p if self.training else 0., + attn_mask=self.attn_mask + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + if self.use_cross_attn: + #print('y_shape:',y.shape) + N_y = y.shape[1] + y_kv = self.y_kv(y).reshape(B, N_y, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + y_k, y_v = y_kv.unbind(0) + y_k = self.y_k_norm(y_k) + y_out = F.scaled_dot_product_attention( + q, y_k, y_v, + dropout_p=self.attn_drop.p if self.training else 0., + ) + #print('y_out_shape:', y_out.shape) + y_out = y_out*self.gate.tanh().view(1, -1, 1, 1) + x = x + y_out + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + +class PerceiverAttentionLayer(nn.Module): + """Perceiver Attention Layer""" + + def __init__(self, dim: int, dim_head: int = 64, heads: int = 8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + self.dim_head = dim_head + inner_dim = dim_head * heads + + # trainable components of PerceiverAttentionLayer + self.norm_media = nn.LayerNorm(dim) + self.norm_latents = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_k = nn.Linear(dim, inner_dim, bias=False) + self.to_v = nn.Linear(dim, inner_dim, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, features, latents): + """Latent vectors are cross-attending to the visual features x + + Args: + features: Batch of visual features with shape (batch_size, n_features, dim) + latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim) + + Returns: + Attention score with shape (batch_size, n_latents, dim) + """ + assert features.ndim == 3 + assert latents.ndim == 3 + assert features.shape[0] == latents.shape[0] + assert features.shape[2] == latents.shape[2] + + n_heads = self.heads + n_batch, n_features, dim = features.shape + n_queries = latents.shape[1] + + # Layer normalization + x = self.norm_media(features) + latents = self.norm_latents(latents) + + # Compute the queries from the latents, for all attention heads simultaneously + q = self.to_q(latents) + q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads) + assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head]) + + # Keys and values for all attention heads + kv_input = torch.cat((x, latents), dim=-2) + n_features_latents = n_features + n_queries + k = self.to_k(kv_input) + v = self.to_v(kv_input) + + k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads) + assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head]) + + q = q * self.scale + + # Attention scores + sim = einsum('b h q d, b h f d -> b h q f', q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + alphas = sim.softmax(dim=-1) + + out = einsum('b h q f, b h f v -> b h q v', alphas, v) + out = rearrange(out, 'b h q v -> b q (h v)') + + return self.to_out(out) + +class TempAttentionLayer(nn.Module): + """Perceiver Attention Layer""" + + def __init__(self, dim: int, dim_head: int = 64, heads: int = 8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + self.dim_head = dim_head + inner_dim = dim_head * heads + + # trainable components of PerceiverAttentionLayer + self.norm_media = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_k = nn.Linear(dim, inner_dim, bias=False) + self.to_v = nn.Linear(dim, inner_dim, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, features): + """Latent vectors are cross-attending to the visual features x + + Args: + features: Batch of visual features with shape (batch_size, n_features, dim) + latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim) + + Returns: + Attention score with shape (batch_size, n_latents, dim) + """ + assert features.ndim == 3 + + n_heads = self.heads + n_batch, n_features, dim = features.shape + n_queries = features.shape[1] + + # Layer normalization + x = self.norm_media(features) + + # Compute the queries from the latents, for all attention heads simultaneously + q = self.to_q(x) + q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads) + assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head]) + + # Keys and values for all attention heads + n_features_latents = n_features + k = self.to_k(x) + v = self.to_v(x) + + k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads) + assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head]) + + q = q * self.scale + + # Attention scores + sim = einsum('b h q d, b h f d -> b h q f', q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + alphas = sim.softmax(dim=-1) + + out = einsum('b h q f, b h f v -> b h q v', alphas, v) + out = rearrange(out, 'b h q v -> b q (h v)') + + return self.to_out(out) + + +class Video_Former_3D(nn.Module): + """Perceiver Resampler with multi-head attention layer""" + + def __init__( + self, + dim: int, + depth: int, + condition_dim: int = 1280, + dim_head: int = 64, + heads: int = 8, + num_latents: int = 64, + num_frame: int = 14, + num_time_embeds: int = 4, + ff_mult: int = 4, + activation: str = 'gelu', + trainable: bool = True, + use_temporal: bool = False, + ): + super().__init__() + + self.dim = dim + self.num_queries = num_latents + self.num_frame = num_frame + self.condition_dim = condition_dim + self.use_temporal = use_temporal + self.input_mask_mode = 'zero' # 'none' | 'zero' | 'gaussian' | 'learnable' + + self.goal_emb = nn.Sequential( + nn.Linear(condition_dim, dim * 2), + nn.GELU(), + nn.Linear(dim * 2, dim) + ) + frame_seq_len = num_latents // num_frame + self.latents = nn.Parameter(torch.randn(self.num_frame, frame_seq_len, dim)) # type: ignore[reportPrivateUsage] + self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim)) # type: ignore[reportPrivateUsage] + attn_mask = torch.ones((num_frame, num_frame)) + #attn_mask = torch.tril(attn_mask).bool() + + self.layers = nn.ModuleList([]) + + if self.use_temporal: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + #TempAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False, + y_dim=512, attn_mask=attn_mask), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + else: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + + # Layer normalization takes as input the query vector length + self.norm = nn.LayerNorm(dim) + + self._update_trainable_state(trainable) + + # learnable frame token (used when input_mask_mode == 'learnable') + if self.input_mask_mode == 'learnable': + # shape: (1, 1, n_features, dim) after goal_emb + self.learnable_mask_token = nn.Parameter(torch.zeros(1, 1, 1, dim)) + + def _update_trainable_state(self, trainable: bool = True): + for param in self.parameters(): + param.requires_grad = trainable + + def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None, extra : torch.Tensor = None, frame_mask_prob: float = 0.0, language: torch.Tensor = None): + """Run perceiver resampler on the input visual embeddings + + Args: + x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual) + mask: Mask for the input visual embeddings of shape (batch_size, n_frames) + extra: Extra tensor for concatenation + frame_mask_prob: Probability of masking each frame during training (0.0 = no masking) + language: Language embeddings of shape (batch_size, 1, lang_dim) + + Returns: + Resampler features of shape (batch_size, num_queries, d_visual) + """ + assert x_f.ndim == 4 + + batch_size, max_length, _, dim = x_f.shape + + # Generate per-batch frame mask (True=keep, False=mask) with non-uniform probability centered at index 6 + frame_mask = None + if frame_mask_prob > 0.0 and self.training: + # per-frame mask probabilities p_i: highest at center_idx=6, decays with distance + center_idx = 6 if max_length > 6 else (max_length // 2) + frame_indices = torch.arange(max_length, device=x_f.device).float() + distances = (frame_indices - float(center_idx)).abs() + sigma = 2.0 + # Gaussian decay: p_i = frame_mask_prob * exp(-0.5 * (d/sigma)^2) + per_frame_p = frame_mask_prob * torch.exp(-0.5 * (distances / sigma) ** 2) + # broadcast to batch and sample Bernoulli per (b, t) + rand_vals = torch.rand(batch_size, max_length, device=x_f.device) + # True=keep, False=mask + frame_mask = rand_vals > per_frame_p.unsqueeze(0) + # ensure at least one frame kept per sample + needs_fix = frame_mask.sum(dim=1) == 0 + if needs_fix.any(): + idx = torch.nonzero(needs_fix, as_tuple=False).squeeze(-1) + rand_cols = torch.randint(0, max_length, (idx.numel(),), device=x_f.device) + frame_mask[idx, rand_cols] = True + + # Mask the position embeddings for the padded frames + time_pos_emb = ( + self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1) + ) # [batch_size, max_length, 1, dim] + if mask is not None: + time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1) + + # Apply the position embeddings + x_f = self.goal_emb(x_f) + # Frame-level input masking before adding positional encoding + if frame_mask is not None: + bsz = batch_size + T = max_length + n_features = x_f.shape[2] + d = x_f.shape[3] + mask_expand = frame_mask.unsqueeze(-1).unsqueeze(-1).expand(bsz, T, n_features, d) + if self.input_mask_mode == 'zero': + x_f = torch.where(mask_expand, x_f, torch.zeros_like(x_f)) + elif self.input_mask_mode == 'gaussian': + noise = torch.randn_like(x_f) + x_f = torch.where(mask_expand, x_f, noise) + elif self.input_mask_mode == 'learnable': + token = self.learnable_mask_token + token = token.expand(bsz, T, n_features, d) + x_f = torch.where(mask_expand, x_f, token) + # 'none' -> do nothing + # 融合语言:将 language (b,1,512) 投影到dim,并按帧复制后拼接为额外特征 + # if language is not None: + # lang = self.lang_emb(language.squeeze(1)) # (b, dim) + # lang = lang.unsqueeze(1) # (b,1,dim) + # lang = repeat(lang, 'b q d -> b T q d', T=max_length) # (b,T,1,dim) + # x_f = torch.cat([x_f, lang], dim=2) + if extra is not None: + extra = repeat(extra, 'b q d -> b T q d', T=max_length) + x_f = torch.cat([x_f, extra],dim = 2) + x_f = x_f + time_pos_emb + + # Select temporal keep mask for spatial attention only (do not change latent length) + keep_mask_time = None + if frame_mask_prob > 1.0 and self.training: + b, T, n, d = x_f.shape + # center-weighted dropping: closer to center has higher drop prob + center_idx = 6 if T > 6 else (T // 2) + frame_indices = torch.arange(T, device=x_f.device).float() + distances = (frame_indices - float(center_idx)).abs() + sigma = 2.0 + # unnormalized weights (max at center, decay with distance) + weights = torch.exp(-0.5 * (distances / sigma) ** 2) + weights = weights / (weights.sum() + 1e-8) + # sample p ~ Uniform(0, frame_mask_prob) then fixed count per batch + p = (torch.rand((), device=x_f.device) * frame_mask_prob).item() + num_to_remove = int(T * p) + if num_to_remove >= T: + num_to_remove = T - 1 + if num_to_remove > 0: + drop_idx = torch.multinomial(weights, num_samples=num_to_remove, replacement=False) + keep_mask_time = torch.ones(T, dtype=torch.bool, device=x_f.device) + keep_mask_time[drop_idx] = False + + # Copy the latents for every element in the batch (full timeline, no dropping) + x_full = repeat(self.latents, 'T q d -> b T q d', b=batch_size) # (b, T, q, d) + + # Apply attention and feed forward layer + if self.use_temporal: + for attn, Temp_attn, ffw in self.layers: + # spatial attention only on kept frames in b T q d layout + if keep_mask_time is not None: + # select kept time steps + x_kept = x_full[:, keep_mask_time, :, :] # (b, T_kept, q, d) + x_f_kept = x_f[:, keep_mask_time, :, :] # (b, T_kept, n, d) + # flatten kept slices for attention + x_kept_flat = rearrange(x_kept, 'b T q d -> (b T) q d') + x_f_kept_flat = rearrange(x_f_kept, 'b T n d -> (b T) n d') + # update kept positions + x_kept_flat = x_kept_flat + attn(x_f_kept_flat, x_kept_flat) + x_kept = rearrange(x_kept_flat, '(b T) q d -> b T q d', b=batch_size) + # create new tensor combining kept and unmasked parts + x_full_new = torch.zeros_like(x_full) + x_full_new[:, keep_mask_time, :, :] = x_kept + x_full_new[:, ~keep_mask_time, :, :] = x_full[:, ~keep_mask_time, :, :] + x_full = x_full_new + else: + # no dropping, full spatial attention + x_full_flat = rearrange(x_full, 'b T q d -> (b T) q d') + x_f_flat = rearrange(x_f, 'b T n d -> (b T) n d') + x_full_flat = x_full_flat + attn(x_f_flat, x_full_flat) + x_full = rearrange(x_full_flat, '(b T) q d -> b T q d', b=batch_size) + + # temporal attention on full timeline (no additional mask) + x_full_flat = rearrange(x_full, 'b T q d -> (b q) T d') + x_full_flat = x_full_flat + Temp_attn(x_full_flat, attn_mask=None) + x_full_flat = rearrange(x_full_flat, '(b q) T d -> (b T) q d', b=batch_size) + x_full_flat = x_full_flat + ffw(x_full_flat) + x_full = rearrange(x_full_flat, '(b T) q d -> b T q d', b=batch_size) + else: + for attn, ffw in self.layers: + x = x + attn(x_f, x) + x = x + ffw(x) + + #x = rearrange(x, 'l q d -> b T q d', b=batch_size) + x = rearrange(x_full, 'b T q d -> b (T q) d') + assert x.shape == torch.Size([batch_size, self.num_queries, self.dim]) + norm = self.norm(x) + + return norm + +class Video_Former_2D(nn.Module): + """Perceiver Resampler with multi-head attention layer""" + + def __init__( + self, + dim: int, + depth: int, + condition_dim: int = 1280, + dim_head: int = 64, + heads: int = 8, + num_latents: int = 64, + num_frame: int = 16, + num_time_embeds: int = 4, + ff_mult: int = 4, + activation: str = 'gelu', + trainable: bool = True, + ): + super().__init__() + + self.dim = dim + self.num_queries = num_latents + self.num_frame = num_frame + self.condition_dim = condition_dim + + self.goal_emb = nn.Sequential( + nn.Linear(condition_dim, dim * 2), + nn.GELU(), + nn.Linear(dim * 2, dim) + ) + seq_len = num_latents // num_frame + self.latents = nn.Parameter(torch.randn(num_frame, seq_len, dim)) # type: ignore[reportPrivateUsage] + self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim)) # type: ignore[reportPrivateUsage] + + self.layers = nn.ModuleList([]) + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + + # Layer normalization takes as input the query vector length + self.norm = nn.LayerNorm(dim) + + self._update_trainable_state(trainable) + + def _update_trainable_state(self, trainable: bool = True): + for param in self.parameters(): + param.requires_grad = trainable + + def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None): + """Run perceiver resampler on the input visual embeddings + + Args: + x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual) + mask: Mask for the input visual embeddings of shape (batch_size, n_frames) + + Returns: + Resampler features of shape (batch_size, num_queries, d_visual) + """ + assert x_f.ndim == 4 + + batch_size, max_length, _, dim = x_f.shape + + assert dim == self.condition_dim + + # Mask the position embeddings for the padded frames + time_pos_emb = ( + self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1) + ) # [batch_size, max_length, 1, dim] + if mask is not None: + time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1) + + # Apply the position embeddings + x_f = self.goal_emb(x_f) + x_f = x_f + time_pos_emb + + # Flatten the frames + x_f = rearrange(x_f, 'b T n d -> (b T) n d') + + # Copy the latents for every element in the batch + x = repeat(self.latents, 'T q d -> b T q d', b=batch_size) + x = rearrange(x, 'b T q d -> (b T) q d') + + # Apply attention and feed forward layer + for attn, ffw in self.layers: + x = x + attn(x_f, x) + x = x + ffw(x) + + #x = rearrange(x, 'l q d -> b T q d', b=batch_size) + x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2]) + x = rearrange(x, 'b T q d -> b (T q) d') + assert x.shape == torch.Size([batch_size, self.num_queries, self.dim]) + norm = self.norm(x) + + return norm diff --git a/code/policy_models/module/Video_Former copy.py b/code/policy_models/module/Video_Former copy.py new file mode 100644 index 0000000000000000000000000000000000000000..87aad207dd169f56d582201314a296c6630b0bad --- /dev/null +++ b/code/policy_models/module/Video_Former copy.py @@ -0,0 +1,554 @@ +# This code is referenced from https://github.com/dhansmair/flamingo-mini + +import torch +from einops import rearrange, repeat +from einops_exts import rearrange_many +from torch import einsum, nn +import torch.nn.functional as F + +from policy_models.module.transformers.utils import feed_forward_layer + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + use_cross_attn=False, + y_dim=512, + qkv_bias: bool = False, + qk_norm: bool = False, + attn_drop: float = 0., + proj_drop: float = 0., + norm_layer: nn.Module = nn.LayerNorm, + attn_mask = None, + ) -> None: + super().__init__() + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.fused_attn = True + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.attn_mask = attn_mask + self.use_cross_attn=use_cross_attn + if self.use_cross_attn: + #print('use_cross_attn') + self.y_kv = nn.Linear(y_dim, dim * 2, bias=qkv_bias) + self.y_k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.gate = nn.Parameter(torch.zeros([self.num_heads])) + + def forward(self, x: torch.Tensor, y=None, attn_mask=None) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + + if self.fused_attn: + runtime_mask = None + if attn_mask is not None: + runtime_mask = attn_mask.to(x.device) + elif self.attn_mask is not None: + runtime_mask = self.attn_mask.to(x.device)[:q.shape[2],:k.shape[2]] + x = F.scaled_dot_product_attention( + q, k, v, + dropout_p=self.attn_drop.p if self.training else 0., + attn_mask=runtime_mask + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + if self.use_cross_attn: + #print('y_shape:',y.shape) + N_y = y.shape[1] + y_kv = self.y_kv(y).reshape(B, N_y, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + y_k, y_v = y_kv.unbind(0) + y_k = self.y_k_norm(y_k) + y_out = F.scaled_dot_product_attention( + q, y_k, y_v, + dropout_p=self.attn_drop.p if self.training else 0., + ) + #print('y_out_shape:', y_out.shape) + y_out = y_out*self.gate.tanh().view(1, -1, 1, 1) + x = x + y_out + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + +class PerceiverAttentionLayer(nn.Module): + """Perceiver Attention Layer""" + + def __init__(self, dim: int, dim_head: int = 64, heads: int = 8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + self.dim_head = dim_head + inner_dim = dim_head * heads + + # trainable components of PerceiverAttentionLayer + self.norm_media = nn.LayerNorm(dim) + self.norm_latents = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_k = nn.Linear(dim, inner_dim, bias=False) + self.to_v = nn.Linear(dim, inner_dim, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, features, latents): + """Latent vectors are cross-attending to the visual features x + + Args: + features: Batch of visual features with shape (batch_size, n_features, dim) + latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim) + + Returns: + Attention score with shape (batch_size, n_latents, dim) + """ + assert features.ndim == 3 + assert latents.ndim == 3 + assert features.shape[0] == latents.shape[0] + assert features.shape[2] == latents.shape[2] + + n_heads = self.heads + n_batch, n_features, dim = features.shape + n_queries = latents.shape[1] + + # Layer normalization + x = self.norm_media(features) + latents = self.norm_latents(latents) + + # Compute the queries from the latents, for all attention heads simultaneously + q = self.to_q(latents) + q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads) + assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head]) + + # Keys and values for all attention heads + kv_input = torch.cat((x, latents), dim=-2) + n_features_latents = n_features + n_queries + k = self.to_k(kv_input) + v = self.to_v(kv_input) + + k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads) + assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head]) + + q = q * self.scale + + # Attention scores + sim = einsum('b h q d, b h f d -> b h q f', q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + alphas = sim.softmax(dim=-1) + + out = einsum('b h q f, b h f v -> b h q v', alphas, v) + out = rearrange(out, 'b h q v -> b q (h v)') + + return self.to_out(out) + +class TempAttentionLayer(nn.Module): + """Perceiver Attention Layer""" + + def __init__(self, dim: int, dim_head: int = 64, heads: int = 8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + self.dim_head = dim_head + inner_dim = dim_head * heads + + # trainable components of PerceiverAttentionLayer + self.norm_media = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_k = nn.Linear(dim, inner_dim, bias=False) + self.to_v = nn.Linear(dim, inner_dim, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, features): + """Latent vectors are cross-attending to the visual features x + + Args: + features: Batch of visual features with shape (batch_size, n_features, dim) + latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim) + + Returns: + Attention score with shape (batch_size, n_latents, dim) + """ + assert features.ndim == 3 + + n_heads = self.heads + n_batch, n_features, dim = features.shape + n_queries = features.shape[1] + + # Layer normalization + x = self.norm_media(features) + + # Compute the queries from the latents, for all attention heads simultaneously + q = self.to_q(x) + q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads) + assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head]) + + # Keys and values for all attention heads + n_features_latents = n_features + k = self.to_k(x) + v = self.to_v(x) + + k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads) + assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head]) + + q = q * self.scale + + # Attention scores + sim = einsum('b h q d, b h f d -> b h q f', q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + alphas = sim.softmax(dim=-1) + + out = einsum('b h q f, b h f v -> b h q v', alphas, v) + out = rearrange(out, 'b h q v -> b q (h v)') + + return self.to_out(out) + + +class Video_Former_3D(nn.Module): + """Perceiver Resampler with multi-head attention layer""" + + def __init__( + self, + dim: int, + depth: int, + condition_dim: int = 1280, + dim_head: int = 64, + heads: int = 8, + num_latents: int = 64, + num_frame: int = 14, + num_time_embeds: int = 4, + ff_mult: int = 4, + activation: str = 'gelu', + trainable: bool = True, + use_temporal: bool = False, + ): + super().__init__() + + self.dim = dim + self.num_queries = num_latents + self.num_frame = num_frame + self.condition_dim = condition_dim + self.use_temporal = use_temporal + self.input_mask_mode = 'zero' # 'none' | 'zero' | 'gaussian' | 'learnable' + + self.goal_emb = nn.Sequential( + nn.Linear(condition_dim, dim * 2), + nn.GELU(), + nn.Linear(dim * 2, dim) + ) + + # 语言嵌入层(将512维语言向量映射到与视觉相同的dim) + # self.lang_emb = nn.Linear(512, dim) + + frame_seq_len = num_latents // num_frame + self.latents = nn.Parameter(torch.randn(self.num_frame, frame_seq_len, dim)) # type: ignore[reportPrivateUsage] + self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim)) # type: ignore[reportPrivateUsage] + attn_mask = torch.ones((num_frame, num_frame)) + #attn_mask = torch.tril(attn_mask).bool() + + self.layers = nn.ModuleList([]) + + if self.use_temporal: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + #TempAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False, + y_dim=512, attn_mask=attn_mask), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + else: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + + # Layer normalization takes as input the query vector length + self.norm = nn.LayerNorm(dim) + + self._update_trainable_state(trainable) + + # learnable frame token (used when input_mask_mode == 'learnable') + if self.input_mask_mode == 'learnable': + # shape: (1, 1, n_features, dim) after goal_emb + self.learnable_mask_token = nn.Parameter(torch.zeros(1, 1, 1, dim)) + + def _update_trainable_state(self, trainable: bool = True): + for param in self.parameters(): + param.requires_grad = trainable + + def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None, extra : torch.Tensor = None, frame_mask_prob: float = 0.0, language: torch.Tensor = None): + """Run perceiver resampler on the input visual embeddings + + Args: + x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual) + mask: Mask for the input visual embeddings of shape (batch_size, n_frames) + extra: Extra tensor for concatenation + frame_mask_prob: Probability of masking each frame during training (0.0 = no masking) + language: Language embeddings of shape (batch_size, 1, lang_dim) + + Returns: + Resampler features of shape (batch_size, num_queries, d_visual) + """ + assert x_f.ndim == 4 + batch_size, max_length, _, dim = x_f.shape + + # Generate per-batch frame mask (True=keep, False=mask) with non-uniform probability centered at index 6 + frame_mask = None + if frame_mask_prob > 1.0 and self.training: + # per-frame mask probabilities p_i: highest at center_idx=6, decays with distance + center_idx = 6 if max_length > 6 else (max_length // 2) + frame_indices = torch.arange(max_length, device=x_f.device).float() + distances = (frame_indices - float(center_idx)).abs() + sigma = 2.0 + # Gaussian decay: p_i = frame_mask_prob * exp(-0.5 * (d/sigma)^2) + per_frame_p = frame_mask_prob * torch.exp(-0.5 * (distances / sigma) ** 2) + # broadcast to batch and sample Bernoulli per (b, t) + rand_vals = torch.rand(batch_size, max_length, device=x_f.device) + # True=keep, False=mask + frame_mask = rand_vals > per_frame_p.unsqueeze(0) + # ensure at least one frame kept per sample + needs_fix = frame_mask.sum(dim=1) == 0 + if needs_fix.any(): + idx = torch.nonzero(needs_fix, as_tuple=False).squeeze(-1) + rand_cols = torch.randint(0, max_length, (idx.numel(),), device=x_f.device) + frame_mask[idx, rand_cols] = True + + # Mask the position embeddings for the padded frames + time_pos_emb = ( + self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1) + ) # [batch_size, max_length, 1, dim] + if mask is not None: + time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1) + + # Apply the position embeddings + x_f = self.goal_emb(x_f) + # Frame-level input masking before adding positional encoding + if frame_mask is not None: + bsz = batch_size + T = max_length + n_features = x_f.shape[2] + d = x_f.shape[3] + mask_expand = frame_mask.unsqueeze(-1).unsqueeze(-1).expand(bsz, T, n_features, d) + if self.input_mask_mode == 'zero': + x_f = torch.where(mask_expand, x_f, torch.zeros_like(x_f)) + elif self.input_mask_mode == 'gaussian': + noise = torch.randn_like(x_f) + x_f = torch.where(mask_expand, x_f, noise) + elif self.input_mask_mode == 'learnable': + token = self.learnable_mask_token + token = token.expand(bsz, T, n_features, d) + x_f = torch.where(mask_expand, x_f, token) + # 'none' -> do nothing + # 融合语言:将 language (b,1,512) 投影到dim,并按帧复制后拼接为额外特征 + # if language is not None: + # lang = self.lang_emb(language.squeeze(1)) # (b, dim) + # lang = lang.unsqueeze(1) # (b,1,dim) + # lang = repeat(lang, 'b q d -> b T q d', T=max_length) # (b,T,1,dim) + # x_f = torch.cat([x_f, lang], dim=2) + if extra is not None: + extra = repeat(extra, 'b q d -> b T q d', T=max_length) + x_f = torch.cat([x_f, extra],dim = 2) + x_f = x_f + time_pos_emb + + # Apply Token Masking Augmentation (TMAug) - frame dropping on temporal dimension + dropped_indices = None + if frame_mask_prob > 0.0 and self.training: + b, T, n, d = x_f.shape + + # Randomly select frames to drop + num_to_remove = int(T * frame_mask_prob) + if num_to_remove > 0 and num_to_remove < T: + # Randomly select frame indices to remove + indices_to_remove = torch.randperm(T, device=x_f.device)[:num_to_remove] + keep_mask = torch.ones(T, dtype=torch.bool, device=x_f.device) + keep_mask[indices_to_remove] = False + dropped_indices = indices_to_remove + + # Apply frame dropping + x_f = x_f[:, keep_mask, :, :] # (b, T_new, n, d) + + + # Flatten the frames + x_f = rearrange(x_f, 'b T n d -> (b T) n d') + + # Get actual time dimension after dropping + actual_T = x_f.shape[0] // batch_size # (b*T_new) // b = T_new + + # Copy the latents for every element in the batch + # x = repeat(self.latents, 'T q d -> b T q d', b=batch_size) + # Copy the latents for every element in the batch, matching the actual time dimension + if dropped_indices is not None: + # Apply the same dropping to latents + latents_keep_mask = torch.ones(self.num_frame, dtype=torch.bool, device=x_f.device) + latents_keep_mask[dropped_indices] = False + latents_after_drop = self.latents[latents_keep_mask] # (T_new, q, d) + x = repeat(latents_after_drop, 'T q d -> b T q d', b=batch_size) + else: + # No dropping, use original latents + x = repeat(self.latents, 'T q d -> b T q d', b=batch_size) + + x = rearrange(x, 'b T q d -> (b T) q d') + + # Apply attention and feed forward layer + if self.use_temporal: + for attn, Temp_attn, ffw in self.layers: + x = x + attn(x_f, x) + x = rearrange(x, '(b T) q d -> (b q) T d', b = batch_size) + # build per-batch temporal attention mask if frame_mask is provided + runtime_temporal_mask = None + if frame_mask is not None: + # frame_mask: (b, T) True=keep, False=mask + keep = frame_mask # (b, T) + # expand along batch for each latent query: current batch for attention is (b * q) + q_per_frame = x.shape[0] // batch_size + # construct (b, 1, 1, T) -> (b*q, 1, 1, T) + mask_bt = keep.unsqueeze(1).unsqueeze(2) # (b,1,1,T) + runtime_temporal_mask = mask_bt.repeat_interleave(q_per_frame, dim=0) # (b*q,1,1,T) + # convert to additive mask with 0 for keep and -inf for masked + runtime_temporal_mask = runtime_temporal_mask.to(x.dtype) + runtime_temporal_mask = torch.where( + runtime_temporal_mask > 0, + torch.zeros_like(runtime_temporal_mask), + torch.full_like(runtime_temporal_mask, -1e9) + ) + x = x + Temp_attn(x, attn_mask=runtime_temporal_mask) + x = rearrange(x, '(b q) T d -> (b T) q d', b = batch_size) + x = x + ffw(x) + else: + for attn, ffw in self.layers: + x = x + attn(x_f, x) + x = x + ffw(x) + + #x = rearrange(x, 'l q d -> b T q d', b=batch_size) + x = x.reshape(batch_size, actual_T, x.shape[1],x.shape[2]) + x = rearrange(x, 'b T q d -> b (T q) d') + # assert x.shape == torch.Size([batch_size, self.num_queries, self.dim]) + expected_queries = actual_T * (self.num_queries // self.num_frame) + assert x.shape == torch.Size([batch_size, expected_queries, self.dim]) + norm = self.norm(x) + + return norm + +class Video_Former_2D(nn.Module): + """Perceiver Resampler with multi-head attention layer""" + + def __init__( + self, + dim: int, + depth: int, + condition_dim: int = 1280, + dim_head: int = 64, + heads: int = 8, + num_latents: int = 64, + num_frame: int = 16, + num_time_embeds: int = 4, + ff_mult: int = 4, + activation: str = 'gelu', + trainable: bool = True, + ): + super().__init__() + + self.dim = dim + self.num_queries = num_latents + self.num_frame = num_frame + self.condition_dim = condition_dim + + self.goal_emb = nn.Sequential( + nn.Linear(condition_dim, dim * 2), + nn.GELU(), + nn.Linear(dim * 2, dim) + ) + seq_len = num_latents // num_frame + self.latents = nn.Parameter(torch.randn(num_frame, seq_len, dim)) # type: ignore[reportPrivateUsage] + self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim)) # type: ignore[reportPrivateUsage] + + self.layers = nn.ModuleList([]) + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + + # Layer normalization takes as input the query vector length + self.norm = nn.LayerNorm(dim) + + self._update_trainable_state(trainable) + + def _update_trainable_state(self, trainable: bool = True): + for param in self.parameters(): + param.requires_grad = trainable + + def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None): + """Run perceiver resampler on the input visual embeddings + + Args: + x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual) + mask: Mask for the input visual embeddings of shape (batch_size, n_frames) + + Returns: + Resampler features of shape (batch_size, num_queries, d_visual) + """ + assert x_f.ndim == 4 + + batch_size, max_length, _, dim = x_f.shape + + assert dim == self.condition_dim + + # Mask the position embeddings for the padded frames + time_pos_emb = ( + self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1) + ) # [batch_size, max_length, 1, dim] + if mask is not None: + time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1) + + # Apply the position embeddings + x_f = self.goal_emb(x_f) + x_f = x_f + time_pos_emb + + # Flatten the frames + x_f = rearrange(x_f, 'b T n d -> (b T) n d') + + # Copy the latents for every element in the batch + x = repeat(self.latents, 'T q d -> b T q d', b=batch_size) + x = rearrange(x, 'b T q d -> (b T) q d') + + # Apply attention and feed forward layer + for attn, ffw in self.layers: + x = x + attn(x_f, x) + x = x + ffw(x) + + #x = rearrange(x, 'l q d -> b T q d', b=batch_size) + x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2]) + x = rearrange(x, 'b T q d -> b (T q) d') + assert x.shape == torch.Size([batch_size, self.num_queries, self.dim]) + norm = self.norm(x) + + return norm diff --git a/code/policy_models/module/Video_Former.py b/code/policy_models/module/Video_Former.py new file mode 100644 index 0000000000000000000000000000000000000000..c9db1a1d840003558bf577423a791170df460db6 --- /dev/null +++ b/code/policy_models/module/Video_Former.py @@ -0,0 +1,670 @@ +# This code is referenced from https://github.com/dhansmair/flamingo-mini + +import torch +from einops import rearrange, repeat +from einops_exts import rearrange_many +from torch import einsum, nn +import torch.nn.functional as F + +from policy_models.module.transformers.utils import feed_forward_layer + +class Attention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + use_cross_attn=False, + y_dim=512, + qkv_bias: bool = False, + qk_norm: bool = False, + attn_drop: float = 0., + proj_drop: float = 0., + norm_layer: nn.Module = nn.LayerNorm, + attn_mask = None, + ) -> None: + super().__init__() + assert dim % num_heads == 0, 'dim should be divisible by num_heads' + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.fused_attn = True + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.attn_mask = attn_mask + self.use_cross_attn=use_cross_attn + if self.use_cross_attn: + #print('use_cross_attn') + self.y_kv = nn.Linear(y_dim, dim * 2, bias=qkv_bias) + self.y_k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.gate = nn.Parameter(torch.zeros([self.num_heads])) + + def forward(self, x: torch.Tensor, y=None, attn_mask=None) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + # TODO: whether to use attn_mask + if self.fused_attn: + runtime_mask = None + if attn_mask is not None: + runtime_mask = attn_mask.to(x.device) + elif self.attn_mask is not None: + runtime_mask = self.attn_mask.to(x.device)[:q.shape[2],:k.shape[2]] + x = F.scaled_dot_product_attention( + q, k, v, + dropout_p=self.attn_drop.p if self.training else 0., + attn_mask=runtime_mask + ) + else: + q = q * self.scale + attn = q @ k.transpose(-2, -1) + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + + if self.use_cross_attn: + #print('y_shape:',y.shape) + N_y = y.shape[1] + y_kv = self.y_kv(y).reshape(B, N_y, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + y_k, y_v = y_kv.unbind(0) + y_k = self.y_k_norm(y_k) + y_out = F.scaled_dot_product_attention( + q, y_k, y_v, + dropout_p=self.attn_drop.p if self.training else 0., + ) + #print('y_out_shape:', y_out.shape) + y_out = y_out*self.gate.tanh().view(1, -1, 1, 1) + x = x + y_out + + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + +class PerceiverAttentionLayer(nn.Module): + """Perceiver Attention Layer""" + + def __init__(self, dim: int, dim_head: int = 64, heads: int = 8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + self.dim_head = dim_head + inner_dim = dim_head * heads + + # trainable components of PerceiverAttentionLayer + self.norm_media = nn.LayerNorm(dim) + self.norm_latents = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_k = nn.Linear(dim, inner_dim, bias=False) + self.to_v = nn.Linear(dim, inner_dim, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, features, latents): + """Latent vectors are cross-attending to the visual features x + + Args: + features: Batch of visual features with shape (batch_size, n_features, dim) + latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim) + + Returns: + Attention score with shape (batch_size, n_latents, dim) + """ + assert features.ndim == 3 + assert latents.ndim == 3 + assert features.shape[0] == latents.shape[0] + assert features.shape[2] == latents.shape[2] + + n_heads = self.heads + n_batch, n_features, dim = features.shape + n_queries = latents.shape[1] + + # Layer normalization + x = self.norm_media(features) + latents = self.norm_latents(latents) + + # Compute the queries from the latents, for all attention heads simultaneously + q = self.to_q(latents) + q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads) + assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head]) + + # Keys and values for all attention heads + kv_input = torch.cat((x, latents), dim=-2) + n_features_latents = n_features + n_queries + k = self.to_k(kv_input) + v = self.to_v(kv_input) + + k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads) + assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head]) + + q = q * self.scale + + # Attention scores + sim = einsum('b h q d, b h f d -> b h q f', q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + alphas = sim.softmax(dim=-1) + + out = einsum('b h q f, b h f v -> b h q v', alphas, v) + out = rearrange(out, 'b h q v -> b q (h v)') + + return self.to_out(out) + +class TempAttentionLayer(nn.Module): + """Perceiver Attention Layer""" + + def __init__(self, dim: int, dim_head: int = 64, heads: int = 8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + self.dim_head = dim_head + inner_dim = dim_head * heads + + # trainable components of PerceiverAttentionLayer + self.norm_media = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_k = nn.Linear(dim, inner_dim, bias=False) + self.to_v = nn.Linear(dim, inner_dim, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, features): + """Latent vectors are cross-attending to the visual features x + + Args: + features: Batch of visual features with shape (batch_size, n_features, dim) + latents: Latent learnt vectors which are used to compute queries with shape (batch_size, n_latents, dim) + + Returns: + Attention score with shape (batch_size, n_latents, dim) + """ + assert features.ndim == 3 + + n_heads = self.heads + n_batch, n_features, dim = features.shape + n_queries = features.shape[1] + + # Layer normalization + x = self.norm_media(features) + + # Compute the queries from the latents, for all attention heads simultaneously + q = self.to_q(x) + q = rearrange(q, 'b q (h d) -> b h q d', h=n_heads) + assert q.shape == torch.Size([n_batch, n_heads, n_queries, self.dim_head]) + + # Keys and values for all attention heads + n_features_latents = n_features + k = self.to_k(x) + v = self.to_v(x) + + k, v = rearrange_many((k, v), 'b f (h d) -> b h f d', h=n_heads) + assert v.shape == torch.Size([n_batch, n_heads, n_features_latents, self.dim_head]) + + q = q * self.scale + + # Attention scores + sim = einsum('b h q d, b h f d -> b h q f', q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + alphas = sim.softmax(dim=-1) + + out = einsum('b h q f, b h f v -> b h q v', alphas, v) + out = rearrange(out, 'b h q v -> b q (h v)') + + return self.to_out(out) + + +class Video_Former_3D(nn.Module): + """Perceiver Resampler with multi-head attention layer""" + + def __init__( + self, + dim: int, + depth: int, + condition_dim: int = 1280, + dim_head: int = 64, + heads: int = 8, + num_latents: int = 64, + num_frame: int = 14, + num_time_embeds: int = 4, + ff_mult: int = 4, + activation: str = 'gelu', + trainable: bool = True, + use_temporal: bool = False, + ): + super().__init__() + + self.dim = dim + self.num_queries = num_latents + self.num_frame = num_frame + self.condition_dim = condition_dim + self.use_temporal = use_temporal + self.input_mask_mode = 'zero' # 'none' | 'zero' | 'gaussian' | 'learnable' + + self.goal_emb = nn.Sequential( + nn.Linear(condition_dim, dim * 2), + nn.GELU(), + nn.Linear(dim * 2, dim) + ) + # self.goal_emb = nn.Sequential( + # nn.Linear(condition_dim, dim), + # nn.LayerNorm(dim), + # ) + frame_seq_len = num_latents // num_frame + self.latents = nn.Parameter(torch.randn(self.num_frame, frame_seq_len, dim)) # type: ignore[reportPrivateUsage] + self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim)) # type: ignore[reportPrivateUsage] + attn_mask = torch.ones((num_frame, num_frame)) + #attn_mask = torch.tril(attn_mask).bool() + + self.layers = nn.ModuleList([]) + + if self.use_temporal: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + #TempAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False, + y_dim=512, attn_mask=attn_mask), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + else: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + + # Layer normalization takes as input the query vector length + self.norm = nn.LayerNorm(dim) + + self._update_trainable_state(trainable) + + # learnable frame token (used when input_mask_mode == 'learnable') + if self.input_mask_mode == 'learnable': + # shape: (1, 1, n_features, dim) after goal_emb + self.learnable_mask_token = nn.Parameter(torch.zeros(1, 1, 1, dim)) + + def _update_trainable_state(self, trainable: bool = True): + for param in self.parameters(): + param.requires_grad = trainable + + def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None, extra : torch.Tensor = None, frame_mask_prob: float = 0.0, language: torch.Tensor = None): + """Run perceiver resampler on the input visual embeddings + + Args: + x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual) + mask: Mask for the input visual embeddings of shape (batch_size, n_frames) + extra: Extra tensor for concatenation + frame_mask_prob: Probability of masking each frame during training (0.0 = no masking) + language: Language embeddings of shape (batch_size, 1, lang_dim) + + Returns: + Resampler features of shape (batch_size, num_queries, d_visual) + """ + assert x_f.ndim == 4 + + batch_size, max_length, _, dim = x_f.shape + + # Generate per-batch frame mask (True=keep, False=mask) with non-uniform probability centered at index 6 + frame_mask = None + if frame_mask_prob > 0.0 and self.training: + # per-frame mask probabilities p_i: highest at center_idx=6, decays with distance + center_idx = 6 if max_length == 14 else (max_length // 2) + frame_indices = torch.arange(max_length, device=x_f.device).float() + distances = (frame_indices - float(center_idx)).abs() + sigma = 2.0 + # Gaussian decay: p_i = frame_mask_prob * exp(-0.5 * (d/sigma)^2) + per_frame_p = frame_mask_prob * torch.exp(-0.5 * (distances / sigma) ** 2) + # broadcast to batch and sample Bernoulli per (b, t) + rand_vals = torch.rand(batch_size, max_length, device=x_f.device) + # True=keep, False=mask + frame_mask = rand_vals > per_frame_p.unsqueeze(0) + # ensure at least one frame kept per sample + needs_fix = frame_mask.sum(dim=1) == 0 + if needs_fix.any(): + idx = torch.nonzero(needs_fix, as_tuple=False).squeeze(-1) + rand_cols = torch.randint(0, max_length, (idx.numel(),), device=x_f.device) + frame_mask[idx, rand_cols] = True + + # Mask the position embeddings for the padded frames + time_pos_emb = ( + self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1) + ) # [batch_size, max_length, 1, dim] + if mask is not None: + time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1) + + # Apply the position embeddings + x_f = self.goal_emb(x_f) + # Frame-level input masking before adding positional encoding + if frame_mask is not None: + bsz = batch_size + T = max_length + n_features = x_f.shape[2] + d = x_f.shape[3] + mask_expand = frame_mask.unsqueeze(-1).unsqueeze(-1).expand(bsz, T, n_features, d) + if self.input_mask_mode == 'zero': + x_f = torch.where(mask_expand, x_f, torch.zeros_like(x_f)) + elif self.input_mask_mode == 'gaussian': + noise = torch.randn_like(x_f) + x_f = torch.where(mask_expand, x_f, noise) + elif self.input_mask_mode == 'learnable': + token = self.learnable_mask_token + token = token.expand(bsz, T, n_features, d) + x_f = torch.where(mask_expand, x_f, token) + # 'none' -> do nothing + if extra is not None: + extra = repeat(extra, 'b q d -> b T q d', T=max_length) + x_f = torch.cat([x_f, extra],dim = 2) + x_f = x_f + time_pos_emb + + # Flatten the frames + x_f = rearrange(x_f, 'b T n d -> (b T) n d') + + # Copy the latents for every element in the batch + x = repeat(self.latents, 'T q d -> b T q d', b=batch_size) + x = rearrange(x, 'b T q d -> (b T) q d') + + # Apply attention and feed forward layer + if self.use_temporal: + for attn, Temp_attn, ffw in self.layers: + x = x + attn(x_f, x) + x = rearrange(x, '(b T) q d -> (b q) T d', b = batch_size) + # build per-batch temporal attention mask if frame_mask is provided + runtime_temporal_mask = None + if frame_mask is not None: + # frame_mask: (b, T) True=keep, False=mask + keep = frame_mask # (b, T) + # expand along batch for each latent query: current batch for attention is (b * q) + q_per_frame = x.shape[0] // batch_size + # construct (b, 1, 1, T) -> (b*q, 1, 1, T) + mask_bt = keep.unsqueeze(1).unsqueeze(2) # (b,1,1,T) + runtime_temporal_mask = mask_bt.repeat_interleave(q_per_frame, dim=0) # (b*q,1,1,T) + # convert to additive mask with 0 for keep and -inf for masked + runtime_temporal_mask = runtime_temporal_mask.to(x.dtype) + runtime_temporal_mask = torch.where( + runtime_temporal_mask > 0, + torch.zeros_like(runtime_temporal_mask), + torch.full_like(runtime_temporal_mask, -1e9) + ) + x = x + Temp_attn(x, attn_mask=runtime_temporal_mask) + x = rearrange(x, '(b q) T d -> (b T) q d', b = batch_size) + x = x + ffw(x) + else: + for attn, ffw in self.layers: + x = x + attn(x_f, x) + x = x + ffw(x) + + #x = rearrange(x, 'l q d -> b T q d', b=batch_size) + x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2]) + x = rearrange(x, 'b T q d -> b (T q) d') + assert x.shape == torch.Size([batch_size, self.num_queries, self.dim]) + norm = self.norm(x) + + return norm + +class Video_Former_2D(nn.Module): + """Perceiver Resampler with multi-head attention layer""" + + def __init__( + self, + dim: int, + depth: int, + condition_dim: int = 1280, + dim_head: int = 64, + heads: int = 8, + num_latents: int = 64, + num_frame: int = 16, + num_time_embeds: int = 4, + ff_mult: int = 4, + activation: str = 'gelu', + trainable: bool = True, + ): + super().__init__() + + self.dim = dim + self.num_queries = num_latents + self.num_frame = num_frame + self.condition_dim = condition_dim + + self.goal_emb = nn.Sequential( + nn.Linear(condition_dim, dim * 2), + nn.GELU(), + nn.Linear(dim * 2, dim) + ) + seq_len = num_latents // num_frame + self.latents = nn.Parameter(torch.randn(num_frame, seq_len, dim)) # type: ignore[reportPrivateUsage] + self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim)) # type: ignore[reportPrivateUsage] + + self.layers = nn.ModuleList([]) + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + + # Layer normalization takes as input the query vector length + self.norm = nn.LayerNorm(dim) + + self._update_trainable_state(trainable) + + def _update_trainable_state(self, trainable: bool = True): + for param in self.parameters(): + param.requires_grad = trainable + + def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None): + """Run perceiver resampler on the input visual embeddings + + Args: + x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual) + mask: Mask for the input visual embeddings of shape (batch_size, n_frames) + + Returns: + Resampler features of shape (batch_size, num_queries, d_visual) + """ + assert x_f.ndim == 4 + + batch_size, max_length, _, dim = x_f.shape + + assert dim == self.condition_dim + + # Mask the position embeddings for the padded frames + time_pos_emb = ( + self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1) + ) # [batch_size, max_length, 1, dim] + if mask is not None: + time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1) + + # Apply the position embeddings + x_f = self.goal_emb(x_f) + x_f = x_f + time_pos_emb + + # Flatten the frames + x_f = rearrange(x_f, 'b T n d -> (b T) n d') + + # Copy the latents for every element in the batch + x = repeat(self.latents, 'T q d -> b T q d', b=batch_size) + x = rearrange(x, 'b T q d -> (b T) q d') + + # Apply attention and feed forward layer + for attn, ffw in self.layers: + x = x + attn(x_f, x) + x = x + ffw(x) + + #x = rearrange(x, 'l q d -> b T q d', b=batch_size) + x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2]) + x = rearrange(x, 'b T q d -> b (T q) d') + assert x.shape == torch.Size([batch_size, self.num_queries, self.dim]) + norm = self.norm(x) + + return norm + + + +class Video_Former_3D_vggt(nn.Module): + """Perceiver Resampler with multi-head attention layer""" + + def __init__( + self, + dim: int, + depth: int, + condition_dim: int = 1280, + dim_head: int = 64, + heads: int = 8, + num_latents: int = 64, + num_frame: int = 14, + num_time_embeds: int = 4, + ff_mult: int = 4, + activation: str = 'gelu', + trainable: bool = True, + use_temporal: bool = False, + ): + super().__init__() + + self.dim = dim + self.num_queries = num_latents + self.num_frame = num_frame + self.condition_dim = condition_dim + self.use_temporal = use_temporal + self.input_mask_mode = 'zero' # 'none' | 'zero' | 'gaussian' | 'learnable' + + self.goal_emb = nn.Sequential( + nn.Linear(condition_dim, dim * 2), + nn.GELU(), + nn.Linear(dim * 2, dim) + ) + frame_seq_len = num_latents // num_frame + self.latents = nn.Parameter(torch.randn(self.num_frame, frame_seq_len, dim)) # type: ignore[reportPrivateUsage] + self.time_pos_emb = nn.Parameter(torch.randn(num_time_embeds, 1, dim)) # type: ignore[reportPrivateUsage] + attn_mask = torch.ones((num_frame, num_frame)) + attn_mask2 = torch.ones((256, 256)) + #attn_mask = torch.tril(attn_mask).bool() + + self.layers = nn.ModuleList([]) + + self.vggt_emb = nn.Sequential( + nn.Linear(dim, 2048), + nn.GELU(), + nn.Linear(2048, 2048) + ) + + + self.spatial_attn = Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False, + y_dim=512, attn_mask=attn_mask2) + self.temporal_attn = Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False, + y_dim=512, attn_mask=attn_mask) + self.feature_ffw = feed_forward_layer(dim=dim, mult=ff_mult, activation=activation) + + if self.use_temporal: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + Attention(dim, num_heads=heads, qkv_bias=True, use_cross_attn=False, + y_dim=512, attn_mask=attn_mask), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + else: + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttentionLayer(dim=dim, dim_head=dim_head, heads=heads), + feed_forward_layer(dim=dim, mult=ff_mult, activation=activation), + ] + ) + ) + + # Layer normalization takes as input the query vector length + self.norm = nn.LayerNorm(dim) + self.norm_g = nn.LayerNorm(dim) + + self._update_trainable_state(trainable) + + # learnable frame token (used when input_mask_mode == 'learnable') + if self.input_mask_mode == 'learnable': + # shape: (1, 1, n_features, dim) after goal_emb + self.learnable_mask_token = nn.Parameter(torch.zeros(1, 1, 1, dim)) + + def _update_trainable_state(self, trainable: bool = True): + for param in self.parameters(): + param.requires_grad = trainable + + def forward(self, x_f: torch.Tensor, mask: torch.BoolTensor = None, extra : torch.Tensor = None, frame_mask_prob: float = 0.0, language: torch.Tensor = None): + """Run perceiver resampler on the input visual embeddings + Args: + x_f: Input visual embeddings of shape (batch_size, n_frames, n_features, d_visual) + mask: Mask for the input visual embeddings of shape (batch_size, n_frames) + extra: Extra tensor for concatenation + Returns: + Resampler features of shape (batch_size, num_queries, d_visual) + """ + assert x_f.ndim == 4 + + batch_size, max_length, _, dim = x_f.shape + + # Mask the position embeddings for the padded frames + time_pos_emb = ( + self.time_pos_emb[:max_length].unsqueeze(0).expand(batch_size, -1, -1, -1) + ) # [batch_size, max_length, 1, dim] + if mask is not None: + time_pos_emb = time_pos_emb * mask.unsqueeze(-1).unsqueeze(-1) + + # Apply the position embeddings + x_f = self.goal_emb(x_f) + + if extra is not None: + extra = repeat(extra, 'b q d -> b T q d', T=max_length) + x_f = torch.cat([x_f, extra],dim = 2) + x_f = x_f + time_pos_emb + + # Flatten the frames + x_f = rearrange(x_f, 'b T n d -> (b T) n d') + + # Copy the latents for every element in the batch + x = repeat(self.latents, 'T q d -> b T q d', b=batch_size) + x = rearrange(x, 'b T q d -> (b T) q d') + + x_g = x_f + self.spatial_attn(x_f) + x_g = rearrange(x_g, '(b T) q d -> (b q) T d', b = batch_size) + x_g = x_g + self.temporal_attn(x_g) + x_g = rearrange(x_g, '(b q) T d -> (b T) q d', b = batch_size) + x_g = x_g + self.feature_ffw(x_g) + + # x_f = torch.cat([x_f, x_g], dim = 1) + x_f = x_g + + # Apply attention and feed forward layer + for attn, Temp_attn, ffw in self.layers: + x = x + attn(x_f, x) + x = rearrange(x, '(b T) q d -> (b q) T d', b = batch_size) + x = x + Temp_attn(x) + x = rearrange(x, '(b q) T d -> (b T) q d', b = batch_size) + x = x + ffw(x) + + #x = rearrange(x, 'l q d -> b T q d', b=batch_size) + x = x.reshape(batch_size, -1 ,x.shape[1],x.shape[2]) + x = rearrange(x, 'b T q d -> b (T q) d') + assert x.shape == torch.Size([batch_size, self.num_queries, self.dim]) + norm = self.norm(x) + x_g = rearrange(x_g, '(b T) q d -> b T q d', b = batch_size) + + return norm, self.vggt_emb(self.norm_g(x_g)) \ No newline at end of file diff --git a/code/policy_models/module/__init__.py b/code/policy_models/module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/module/__pycache__/Video_Former.cpython-310.pyc b/code/policy_models/module/__pycache__/Video_Former.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7665e8d94dfc7df5239fb964250f3212af134c0f Binary files /dev/null and b/code/policy_models/module/__pycache__/Video_Former.cpython-310.pyc differ diff --git a/code/policy_models/module/__pycache__/Video_Former.cpython-39.pyc b/code/policy_models/module/__pycache__/Video_Former.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90ee02a216b99f57bdefa0b040d45a67b6898b23 Binary files /dev/null and b/code/policy_models/module/__pycache__/Video_Former.cpython-39.pyc differ diff --git a/code/policy_models/module/__pycache__/__init__.cpython-310.pyc b/code/policy_models/module/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88c6be7f9c78918cbc5d0a31d3b324bda63bac92 Binary files /dev/null and b/code/policy_models/module/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/module/__pycache__/__init__.cpython-39.pyc b/code/policy_models/module/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7898bea8cd251c50971978b0f3968e8f9ea0ade8 Binary files /dev/null and b/code/policy_models/module/__pycache__/__init__.cpython-39.pyc differ diff --git a/code/policy_models/module/__pycache__/clip.cpython-310.pyc b/code/policy_models/module/__pycache__/clip.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fea0e8baed4ecc3b4b03ab0f73718a32714b801 Binary files /dev/null and b/code/policy_models/module/__pycache__/clip.cpython-310.pyc differ diff --git a/code/policy_models/module/__pycache__/clip.cpython-39.pyc b/code/policy_models/module/__pycache__/clip.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f72b7ec433e29ab9bb2a59dd7b7abe9f5f8e55dd Binary files /dev/null and b/code/policy_models/module/__pycache__/clip.cpython-39.pyc differ diff --git a/code/policy_models/module/__pycache__/clip_lang_encoder.cpython-310.pyc b/code/policy_models/module/__pycache__/clip_lang_encoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..225dfa887c092847a803ba89dfac11ae3ad75b6e Binary files /dev/null and b/code/policy_models/module/__pycache__/clip_lang_encoder.cpython-310.pyc differ diff --git a/code/policy_models/module/__pycache__/clip_lang_encoder.cpython-39.pyc b/code/policy_models/module/__pycache__/clip_lang_encoder.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b84e104b1c6636d927ff6751afe442598bacea0 Binary files /dev/null and b/code/policy_models/module/__pycache__/clip_lang_encoder.cpython-39.pyc differ diff --git a/code/policy_models/module/__pycache__/diffusion_decoder.cpython-310.pyc b/code/policy_models/module/__pycache__/diffusion_decoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ddd4ccbeb6f3d02b23543f152374ab53a038cc9 Binary files /dev/null and b/code/policy_models/module/__pycache__/diffusion_decoder.cpython-310.pyc differ diff --git a/code/policy_models/module/__pycache__/diffusion_decoder.cpython-39.pyc b/code/policy_models/module/__pycache__/diffusion_decoder.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65bdb952bc644ff5f8bfee9be78154a0fca9159b Binary files /dev/null and b/code/policy_models/module/__pycache__/diffusion_decoder.cpython-39.pyc differ diff --git a/code/policy_models/module/__pycache__/diffusion_extract.cpython-310.pyc b/code/policy_models/module/__pycache__/diffusion_extract.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7c890f2baf8b0a708a91dc092f8401554dd8ccd Binary files /dev/null and b/code/policy_models/module/__pycache__/diffusion_extract.cpython-310.pyc differ diff --git a/code/policy_models/module/__pycache__/diffusion_extract.cpython-39.pyc b/code/policy_models/module/__pycache__/diffusion_extract.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab0a45bce747a34b9c2de3018835c09d03f4eb2a Binary files /dev/null and b/code/policy_models/module/__pycache__/diffusion_extract.cpython-39.pyc differ diff --git a/code/policy_models/module/clip.py b/code/policy_models/module/clip.py new file mode 100644 index 0000000000000000000000000000000000000000..8a39f040152a9c5728bd834c0eff6d04822a434e --- /dev/null +++ b/code/policy_models/module/clip.py @@ -0,0 +1,718 @@ +########################################### +# Authors: OpenAI +# Credit: https://github.com/openai/CLIP +# MIT License. + +from collections import OrderedDict +import hashlib +import os +from typing import Any, Callable, List, Tuple, Union +import urllib +import warnings + +import numpy as np +from PIL import Image +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor +from tqdm import tqdm + +from policy_models.utils.clip_tokenizer import SimpleTokenizer as _Tokenizer + +try: + from torchvision.transforms import InterpolationMode + + BICUBIC = InterpolationMode.BICUBIC +except ImportError: + BICUBIC = Image.BICUBIC + +__all__ = ["available_models", "load_clip", "tokenize"] +_tokenizer = _Tokenizer() + +_MODELS = { + "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt", + "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt", + "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt", + "RN50x16": "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt", + "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt", + "ViT-B/16": "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt", +} + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + + self.relu = nn.ReLU(inplace=True) + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential( + OrderedDict( + [ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)), + ] + ) + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + identity = x + + out = self.relu(self.bn1(self.conv1(x))) + out = self.relu(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + + def forward(self, x): + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x, + key=x, + value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0, + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False, + ) + + return x[0] + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, input_resolution=224, width=64): + super().__init__() + self.output_dim = output_dim + self.input_resolution = input_resolution + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.avgpool = nn.AvgPool2d(2) + self.relu = nn.ReLU(inplace=True) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim) + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def forward(self, x): + def stem(x): + for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]: + x = self.relu(bn(conv(x))) + x = self.avgpool(x) + return x + + x = x.type(self.conv1.weight.dtype) + x = stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x + + def prepool_im(self, x): + """Run until prepool and save intermediate features""" + im = [] + + def stem(x): + for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]: + x = self.relu(bn(conv(x))) + im.append(x) + x = self.avgpool(x) + im.append(x) + return x + + x = x.type(self.conv1.weight.dtype) + x = stem(x) + + for layer in [self.layer1, self.layer2, self.layer3, self.layer4]: + x = layer(x) + im.append(x) + + return x, im + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" + + def forward(self, x: torch.Tensor) -> torch.Tensor: + orig_type = x.dtype + ret = super().forward(x.type(torch.float32)) + return ret.type(orig_type) + + +class QuickGELU(nn.Module): + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x * torch.sigmoid(1.702 * x) + + +class ResidualAttentionBlock(nn.Module): + def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): + super().__init__() + + self.attn = nn.MultiheadAttention(d_model, n_head) + self.ln_1 = LayerNorm(d_model) + self.mlp = nn.Sequential( + OrderedDict( + [ + ("c_fc", nn.Linear(d_model, d_model * 4)), + ("gelu", QuickGELU()), + ("c_proj", nn.Linear(d_model * 4, d_model)), + ] + ) + ) + self.ln_2 = LayerNorm(d_model) + self.attn_mask = attn_mask + + def attention(self, x: torch.Tensor) -> torch.Tensor: + self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None + return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x + self.attention(self.ln_1(x)) + x = x + self.mlp(self.ln_2(x)) + return x + + +class Transformer(nn.Module): + def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): + super().__init__() + self.width = width + self.layers = layers + self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.resblocks(x) + + +class VisionTransformer(nn.Module): + def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): + super().__init__() + self.input_resolution = input_resolution + self.output_dim = output_dim + self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) + + scale = width ** -0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) + self.ln_pre = LayerNorm(width) + + self.transformer = Transformer(width, layers, heads) + + self.ln_post = LayerNorm(width) + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.conv1(x) # shape = [*, width, grid, grid] + x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + x = torch.cat( + [ + self.class_embedding.to(x.dtype) + + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), + x, + ], + dim=1, + ) # shape = [*, grid ** 2 + 1, width] + x = x + self.positional_embedding.to(x.dtype) + x = self.ln_pre(x) + + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + + x = self.ln_post(x[:, 0, :]) + + if self.proj is not None: + x = x @ self.proj + + return x + + +class CLIP(nn.Module): + def __init__( + self, + embed_dim: int, + # vision + image_resolution: int, + vision_layers: Union[Tuple[int, int, int, int], int], + vision_width: int, + vision_patch_size: int, + # text + context_length: int, + vocab_size: int, + transformer_width: int, + transformer_heads: int, + transformer_layers: int, + ): + super().__init__() + + self.context_length = context_length + + if isinstance(vision_layers, (tuple, list)): + vision_heads = vision_width * 32 // 64 + self.visual = ModifiedResNet( + layers=vision_layers, + output_dim=embed_dim, + heads=vision_heads, + input_resolution=image_resolution, + width=vision_width, + ) + else: + vision_heads = vision_width // 64 + self.visual = VisionTransformer( # type: ignore + input_resolution=image_resolution, + patch_size=vision_patch_size, + width=vision_width, + layers=vision_layers, + heads=vision_heads, + output_dim=embed_dim, + ) + + self.transformer = Transformer( + width=transformer_width, + layers=transformer_layers, + heads=transformer_heads, + attn_mask=self.build_attention_mask(), + ) + + self.vocab_size = vocab_size + self.token_embedding = nn.Embedding(vocab_size, transformer_width) + self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) + self.ln_final = LayerNorm(transformer_width) + + self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + self.initialize_parameters() + + def initialize_parameters(self): + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + + if isinstance(self.visual, ModifiedResNet): + if self.visual.attnpool is not None: + std = self.visual.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) + attn_std = self.transformer.width ** -0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + @property + def dtype(self): + return self.visual.conv1.weight.dtype + + def encode_image(self, image): + return self.visual(image.type(self.dtype)) + + def encode_text(self, text): + x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding.type(self.dtype) + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer(x) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x).type(self.dtype) + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection + + return x + + def forward(self, image, text): + image_features = self.encode_image(image) + text_features = self.encode_text(text) + + # normalized features + image_features = image_features / image_features.norm(dim=-1, keepdim=True) + text_features = text_features / text_features.norm(dim=-1, keepdim=True) + + # cosine similarity as logits + logit_scale = self.logit_scale.exp() + logits_per_image = logit_scale * image_features @ text_features.t() + logits_per_text = logits_per_image.t() + + # shape = [global_batch_size, global_batch_size] + return logits_per_image, logits_per_text + + +def convert_weights(model: nn.Module) -> None: + """Convert applicable model parameters to fp16""" + + def _convert_weights_to_fp16(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.half() + if l.bias is not None: + l.bias.data = l.bias.data.half() + + if isinstance(l, nn.MultiheadAttention): + for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.half() + + for name in ["text_projection", "proj"]: + if hasattr(l, name): + attr = getattr(l, name) + if attr is not None: + attr.data = attr.data.half() + + model.apply(_convert_weights_to_fp16) + + +def build_model(state_dict: dict) -> Any: + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len( + [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")] + ) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) + image_resolution = vision_patch_size * grid_size + else: + counts: list = [ + len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4] + ] + vision_layers = tuple(counts) # type: ignore + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) + vision_patch_size = None + assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] + image_resolution = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith("transformer.resblocks"))) + + model = CLIP( + embed_dim, + image_resolution, + vision_layers, + vision_width, + vision_patch_size, + context_length, + vocab_size, + transformer_width, + transformer_heads, + transformer_layers, + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + if key in state_dict: + del state_dict[key] + + convert_weights(model) + model.load_state_dict(state_dict) # type:ignore + return model.eval() + + +def _download(url: str, root: str) -> str: + os.makedirs(root, exist_ok=True) + filename = os.path.basename(url) + + expected_sha256 = url.split("/")[-2] + download_target = os.path.join(root, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError(f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: + return download_target + else: + warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + + with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: + with tqdm( + total=int(source.info().get("Content-Length")), ncols=80, unit="iB", unit_scale=True, unit_divisor=1024 + ) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: + raise RuntimeError("Model has been downloaded but the SHA256 checksum does not not match") + + return download_target + + +def available_models() -> List[str]: + """Returns the names of available CLIP models""" + return list(_MODELS.keys()) + + +def _convert_image_to_rgb(image): + return image.convert("RGB") + + +def _transform(n_px): + return Compose( + [ + Resize(n_px, interpolation=BICUBIC), + CenterCrop(n_px), + _convert_image_to_rgb, + ToTensor(), + Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), + ] + ) + + +def load_clip( + name: str, + device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", + jit: bool = False, + download_root: str = None, +) -> Tuple[torch.nn.Module, Callable]: + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + + device : Union[str, torch.device] + The device to put the loaded model + + jit : bool + Whether to load the optimized JIT model or more hackable non-JIT model (default). + + download_root: str + path to download the model files; by default, it uses "~/.cache/clip" + + Returns + ------- + model : torch.nn.Module + The CLIP model + + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if name in _MODELS: + model_path = _download(_MODELS[name], download_root or os.path.expanduser("~/.cache/clip")) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError(f"Model {name} not found; available models = {available_models()}") + + try: + # loading JIT archive + model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval() + # model = torch.jit.load(model_path).eval() + state_dict = None + except RuntimeError: + # loading saved state dict + if jit: + warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") + jit = False + state_dict = torch.load(model_path, map_location="cpu") + + if not jit: + model = build_model(state_dict or model.state_dict()).to(device) + # model = build_model(state_dict or model.state_dict()) + if str(device) == "cpu": + model.float() + return model, _transform(model.visual.input_resolution) + + # patch the device names + device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) + device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1] + + def patch_device(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("prim::Constant"): + if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): + node.copyAttributes(device_node) + + model.apply(patch_device) + patch_device(model.encode_image) + patch_device(model.encode_text) + + # patch dtype to float32 on CPU + if str(device) == "cpu": + float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) + float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] + float_node = float_input.node() + + def patch_float(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("aten::to"): + inputs = list(node.inputs()) + for i in [1, 2]: # dtype can be the second or third argument to aten::to() + if inputs[i].node()["value"] == 5: + inputs[i].node().copyAttributes(float_node) + + model.apply(patch_float) + patch_float(model.encode_image) + patch_float(model.encode_text) + + model.float() + + return model, _transform(model.input_resolution.item()) + + +def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.LongTensor: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + + context_length : int + The context length to use; all CLIP models use 77 as the context length + + truncate: bool + Whether to truncate the text in case its encoding is longer than the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder["<|startoftext|>"] + eot_token = _tokenizer.encoder["<|endoftext|>"] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + if truncate: + tokens = tokens[:context_length] + tokens[-1] = eot_token + else: + raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") + result[i, : len(tokens)] = torch.tensor(tokens) + + return result # type:ignore diff --git a/code/policy_models/module/clip_lang_encoder.py b/code/policy_models/module/clip_lang_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..63e1bf0a875c3088a2c443265b80065b375fa531 --- /dev/null +++ b/code/policy_models/module/clip_lang_encoder.py @@ -0,0 +1,28 @@ +from typing import List + +import torch +import torch.nn as nn + +from policy_models.module.clip import build_model, load_clip, tokenize + + +class LangClip(nn.Module): + def __init__(self, freeze_backbone: bool = True, model_name: str = "RN50"): + super(LangClip, self).__init__() + self.device = "cuda" if torch.cuda.is_available() else "cpu" + # Load CLIP model + print(f"loading language CLIP model with backbone: {model_name}") + self._load_clip(model_name) + if freeze_backbone: + for param in self.clip_rn50.parameters(): + param.requires_grad = False + + def _load_clip(self, model_name: str) -> None: + model, _ = load_clip(model_name, device=self.device) + self.clip_rn50 = build_model(model.state_dict()).to(self.device) + + def forward(self, x: List) -> torch.Tensor: + with torch.no_grad(): + tokens = tokenize(x).to(self.device) + emb = self.clip_rn50.encode_text(tokens) + return torch.unsqueeze(emb, 1) diff --git a/code/policy_models/module/diffusion_decoder.py b/code/policy_models/module/diffusion_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..720386be255b6fde754d5f08998209b25e59a32d --- /dev/null +++ b/code/policy_models/module/diffusion_decoder.py @@ -0,0 +1,286 @@ +import einops + +from policy_models.module.transformers.transformer_blocks import * + +class SinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + self.dim = dim + + def forward(self, x): + device = x.device + half_dim = self.dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, device=device) * -emb) + emb = x[:, None] * emb[None, :] + emb = torch.cat((emb.sin(), emb.cos()), dim=-1) + return emb + +logger = logging.getLogger(__name__) + +def return_model_parameters_in_millions(model): + num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + num_params_in_millions = round(num_params / 1_000_000, 2) + return num_params_in_millions + + +class DiffusionTransformer(nn.Module): + """the full GPT score model, with a context size of block_size""" + + def __init__( + self, + obs_dim: int, + goal_dim: int, + device: str, + n_obs_token: int, + goal_conditioned: bool, + action_dim: int, + proprio_dim: int, + embed_dim: int, + embed_pdrob: float, + attn_pdrop: float, + resid_pdrop: float, + mlp_pdrop: float, + n_dec_layers: int, + n_enc_layers: int, + n_heads: int, + goal_seq_len: int, + obs_seq_len: int, + action_seq_len: int, + goal_drop: float = 0.1, + bias=False, + use_mlp_goal: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + linear_output: bool = True, + use_noise_encoder: bool = False, + use_ada_conditioning: bool = True, + ): + super().__init__() + self.device = device + self.goal_conditioned = goal_conditioned + self.obs_dim = obs_dim + self.embed_dim = embed_dim + self.n_obs_token = n_obs_token + self.use_ada_conditioning = use_ada_conditioning + + if self.goal_conditioned: + block_size = goal_seq_len + action_seq_len + obs_seq_len * self.n_obs_token + 2 + else: + block_size = action_seq_len + obs_seq_len * self.n_obs_token + 2 + self.action_seq_len = action_seq_len + if self.goal_conditioned: + seq_size = goal_seq_len + obs_seq_len * self.n_obs_token + action_seq_len + else: + seq_size = obs_seq_len * self.n_obs_token + action_seq_len + print(f"obs dim: {obs_dim}, goal_dim: {goal_dim}, action_dim: {action_dim}, proprio_dim: {proprio_dim}") + self.tok_emb = nn.Linear(obs_dim, embed_dim) + if use_mlp_goal: + self.goal_emb = nn.Sequential( + nn.Linear(goal_dim, embed_dim * 2), + nn.GELU(), + nn.Linear(embed_dim * 2, embed_dim) + ) + else: + self.goal_emb = nn.Linear(goal_dim, embed_dim) + + if use_mlp_goal: + self.lang_emb = nn.Sequential( + nn.Linear(goal_dim, embed_dim * 2), + nn.GELU(), + nn.Linear(embed_dim * 2, embed_dim) + ) + else: + self.lang_emb = nn.Linear(goal_dim, embed_dim) + + if not self.goal_conditioned: + for param in self.lang_emb.parameters(): + param.requires_grad = False + for param in self.goal_emb.parameters(): + param.requires_grad = False + + self.pos_emb = nn.Parameter(torch.zeros(1, seq_size, embed_dim)) + print('seq_size:',seq_size) + self.drop = nn.Dropout(embed_pdrob) + self.proprio_drop = nn.Dropout(0.5) + self.cond_mask_prob = goal_drop + self.use_rot_embed = use_rot_embed + self.action_dim = action_dim + self.obs_dim = obs_dim + self.embed_dim = embed_dim + self.latent_encoder_emb = None + + self.encoder = TransformerEncoder( + embed_dim=embed_dim, + n_heads=n_heads, + attn_pdrop=attn_pdrop, + resid_pdrop=resid_pdrop, + n_layers=n_enc_layers, + block_size=block_size, + bias=bias, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + mlp_pdrop=mlp_pdrop, + ) + + self.decoder = TransformerFiLMDecoder( + embed_dim=embed_dim, + n_heads=n_heads, + attn_pdrop=attn_pdrop, + resid_pdrop=resid_pdrop, + n_layers=n_dec_layers, + film_cond_dim=embed_dim, + block_size=block_size, + bias=bias, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + mlp_pdrop=mlp_pdrop, + use_cross_attention=True, + use_noise_encoder=use_noise_encoder, + ) + + self.latent_encoder_emb = None + self.proprio_emb = nn.Sequential( + nn.Linear(proprio_dim, embed_dim * 2), + nn.Mish(), + nn.Linear(embed_dim * 2, embed_dim), + ).to(self.device) + + self.block_size = block_size + self.goal_seq_len = goal_seq_len + self.obs_seq_len = obs_seq_len + + self.sigma_emb = nn.Sequential( + SinusoidalPosEmb(embed_dim), + nn.Linear(embed_dim, embed_dim * 2), + nn.Mish(), + nn.Linear(embed_dim * 2, embed_dim), + ).to(self.device) + + self.action_emb = nn.Linear(action_dim, embed_dim) + + if linear_output: + self.action_pred = nn.Linear(embed_dim, self.action_dim) + else: + self.action_pred = nn.Sequential( + nn.Linear(embed_dim, 100), + nn.GELU(), + nn.Linear(100, self.action_dim) + ) + + self.apply(self._init_weights) + logger.info(f'Number of encoder parameters: {return_model_parameters_in_millions(self.encoder)}') + logger.info(f'Number of decoder parameters: {return_model_parameters_in_millions(self.decoder)}') + logger.info( + "number of parameters: %e", sum(p.numel() for p in self.parameters()) + ) + + def get_block_size(self): + return self.block_size + + def _init_weights(self, module): + if isinstance(module, (nn.Linear, nn.Embedding)): + torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) + if isinstance(module, nn.Linear) and module.bias is not None: + torch.nn.init.zeros_(module.bias) + elif isinstance(module, nn.LayerNorm): + torch.nn.init.zeros_(module.bias) + torch.nn.init.ones_(module.weight) + elif isinstance(module, DiffusionTransformer): + torch.nn.init.normal_(module.pos_emb, mean=0.0, std=0.02) + + def forward(self, states, actions, goals, sigma, uncond: Optional[bool] = False): + context = self.forward_enc_only(states, actions, goals, sigma, uncond) + pred_actions = self.forward_dec_only(context, actions, sigma) + return pred_actions + + def forward_enc_only(self, states, actions=None, goals=None, sigma=None, uncond: Optional[bool] = False): + emb_t = self.process_sigma_embeddings(sigma) if not self.use_ada_conditioning else None + goals = self.preprocess_goals(goals, states['state_images'].size(1), uncond) + state_embed, proprio_embed = self.process_state_embeddings(states) + goal_embed = self.process_goal_embeddings(goals) + + input_seq = self.concatenate_inputs(emb_t, goal_embed, state_embed, proprio_embed, uncond) + context = self.encoder(input_seq) + self.latent_encoder_emb = context + return context + + def forward_dec_only(self, context, actions, sigma): + emb_t = self.process_sigma_embeddings(sigma) + action_embed = self.action_emb(actions) + action_x = self.drop(action_embed) + + x = self.decoder(action_x, emb_t, context) + pred_actions = self.action_pred(x) + return pred_actions + + def process_sigma_embeddings(self, sigma): + sigmas = sigma.log() / 4 + sigmas = einops.rearrange(sigmas, 'b -> b 1') + emb_t = self.sigma_emb(sigmas) + if len(emb_t.shape) == 2: + emb_t = einops.rearrange(emb_t, 'b d -> b 1 d') + return emb_t + + def preprocess_goals(self, goals, states_length, uncond=False): + if len(goals.shape) == 2: + goals = einops.rearrange(goals, 'b d -> b 1 d') + if goals.shape[1] == states_length and self.goal_seq_len == 1: + goals = goals[:, 0, :] + goals = einops.rearrange(goals, 'b d -> b 1 d') + if goals.shape[-1] == 2 * self.obs_dim: + goals = goals[:, :, :self.obs_dim] + if self.training: + goals = self.mask_cond(goals) + if uncond: + goals = torch.zeros_like(goals).to(self.device) + return goals + + def process_state_embeddings(self, states): + states_global = self.tok_emb(states['state_images']) + if 'state_obs' in states: + proprio_embed = self.proprio_emb(states['state_obs']) + else: + proprio_embed = None + return states_global, proprio_embed + + def process_goal_embeddings(self, goals): + goal_embed = self.lang_emb(goals) + return goal_embed + + def apply_position_embeddings(self, goal_embed, state_embed, action_embed, proprio_embed, t): + pos_len = t + self.goal_seq_len + self.action_seq_len - 1 + position_embeddings = self.pos_emb[:, :pos_len, :] + goal_x = self.drop(goal_embed + position_embeddings[:, :self.goal_seq_len, :]) + state_x = self.drop(state_embed + position_embeddings[:, self.goal_seq_len:(self.goal_seq_len + t), :]) + action_x = self.drop(action_embed + position_embeddings[:, (self.goal_seq_len + t - 1):, :]) + proprio_x = self.drop(proprio_embed + position_embeddings[:, self.goal_seq_len:(self.goal_seq_len + t), :]) if proprio_embed is not None else None + return goal_x, state_x, action_x, proprio_x + + def concatenate_inputs(self, emb_t, goal_x, state_x, proprio_x, uncond=False): + input_seq_components = [state_x] + + if self.goal_conditioned: + input_seq_components.insert(0, goal_x) + + if proprio_x is not None: + input_seq_components.append(proprio_x) + #else: + # if not self.goal_conditioned: + # input_seq_components.append(self.drop(goal_x)) + + input_seq = torch.cat(input_seq_components, dim=1) + return input_seq + + def mask_cond(self, cond, force_mask=False): + bs, t, d = cond.shape + if force_mask: + return torch.zeros_like(cond) + elif self.training and self.cond_mask_prob > 0.: + mask = torch.bernoulli(torch.ones((bs, t, d), device=cond.device) * self.cond_mask_prob) + return cond * (1. - mask) + else: + return cond + + def get_params(self): + return self.parameters() \ No newline at end of file diff --git a/code/policy_models/module/diffusion_extract.py b/code/policy_models/module/diffusion_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..91f7a0e1216b7247b32a5280e42534428d4d2b8c --- /dev/null +++ b/code/policy_models/module/diffusion_extract.py @@ -0,0 +1,556 @@ +from typing import Dict, Optional, Tuple, Union +from diffusers.models import UNetSpatioTemporalConditionModel +from diffusers import TextToVideoSDPipeline, StableVideoDiffusionPipeline +import torch +import torch.nn as nn +from einops import rearrange, repeat +import math +import random +from transformers import AutoTokenizer, CLIPTextModelWithProjection +import numpy as np +import os +from video_models.pipeline import MaskStableVideoDiffusionPipeline,TextStableVideoDiffusionPipeline + +class Diffusion_feature_extractor(nn.Module): + def __init__( + self, + pipeline=None, + tokenizer=None, + text_encoder=None, + position_encoding=True, + ): + super().__init__() + self.pipeline = pipeline if pipeline is not None else StableVideoDiffusionPipeline() + self.tokenizer = tokenizer if tokenizer is not None else AutoTokenizer.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32",use_fast=False) + self.text_encoder = text_encoder if text_encoder is not None else CLIPTextModelWithProjection.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32") + self.num_frames = int(os.environ.get("GLOBAL_FRAME_NUM")) + self.position_encoding = position_encoding + + @torch.no_grad() + def forward( + self, + pixel_values: torch.Tensor, + texts, + timestep: Union[torch.Tensor, float, int], + extract_layer_idx: Union[torch.Tensor, float, int], + use_latent = False, + all_layer = False, + step_time = 1, + max_length = 20, + ): + with torch.no_grad(): + # texts, tokenizer, text_encoder, img_cond=None, img_cond_mask=None, img_encoder=None, position_encode=True, use_clip=False, max_length=20 + encoder_hidden_states = self.encode_text(texts, self.tokenizer, self.text_encoder, position_encode=self.position_encoding, use_clip=True, max_length=max_length) + encoder_hidden_states = encoder_hidden_states.to(self.pipeline.vae.dtype) + + # frames = MaskStableVideoDiffusionPipeline.__call__(self.pipeline,image=pixel_values.squeeze(1), text=encoder_hidden_states, width=pixel_values.shape[-1], height=pixel_values.shape[-2], num_frames=self.num_frames, num_inference_steps=20, max_guidance_scale=7.5, fps=7, motion_bucket_id=127, decode_chunk_size=7, mask=None).frames + # tmpframes = [] + # for ii in range(len(frames)): + # tmpframe = frames[ii][3] + # tmpframe = torch.tensor(np.array(tmpframe),device=self.pipeline.unet.device).permute(2,0,1)[None] + # tmpframes.append(tmpframe/255.*2.-1) + # pixel_values = torch.cat(tmpframes,dim=0).unsqueeze(1) + + # # tmpimgs = torch.tensor(np.array(frames[10][2]),device=self.pipeline.unet.device).permute(2,0,1)[None] + # # image = image/255.*2.-1 + # # res = MaskStableVideoDiffusionPipeline.__call__(self.pipeline,image=image, text=encoder_hidden_states[0].unsqueeze(0), width=256, height=256, num_frames=self.num_frames, num_inference_steps=20, max_guidance_scale=2.5, fps=7, motion_bucket_id=127, decode_chunk_size=7, mask=None).frames + + + + + + height = self.pipeline.unet.config.sample_size * self.pipeline.vae_scale_factor //3 + width = self.pipeline.unet.config.sample_size * self.pipeline.vae_scale_factor //3 + self.pipeline.vae.eval() + self.pipeline.image_encoder.eval() + device = self.pipeline.unet.device + dtype = self.pipeline.vae.dtype + #print('dtype:',dtype) + vae = self.pipeline.vae + + num_videos_per_prompt=1 + + batch_size = pixel_values.shape[0] + + pixel_values = rearrange(pixel_values, 'b f c h w-> (b f) c h w').to(dtype) + + image_embeddings = encoder_hidden_states + + needs_upcasting = self.pipeline.vae.dtype == torch.float16 and self.pipeline.vae.config.force_upcast + #if needs_upcasting: + # self.pipeline.vae.to(dtype=torch.float32) + # pixel_values.to(dtype=torch.float32) + if pixel_values.shape[-3] == 4: + image_latents = pixel_values/vae.config.scaling_factor + else: + image_latents = self.pipeline._encode_vae_image(pixel_values, device, num_videos_per_prompt, False) + image_latents = image_latents.to(image_embeddings.dtype) + + #print('dtype:', image_latents.dtype) + + #if needs_upcasting: + # self.pipeline.vae.to(dtype=torch.float16) + + #num_frames = self.pipeline.unet.config.num_frames + num_frames = self.num_frames + image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1) + + fps=4 + motion_bucket_id=127 + added_time_ids = self.pipeline._get_add_time_ids( + fps, + motion_bucket_id, + 0, + image_embeddings.dtype, + batch_size, + num_videos_per_prompt, + False, + ) + added_time_ids = added_time_ids.to(device) + + self.pipeline.scheduler.set_timesteps(timestep, device=device) + timesteps = self.pipeline.scheduler.timesteps + + num_channels_latents = self.pipeline.unet.config.in_channels + latents = self.pipeline.prepare_latents( + batch_size * num_videos_per_prompt, + num_frames, + num_channels_latents, + height, + width, + image_embeddings.dtype, + device, + None, + None, + ) + + for i, t in enumerate(timesteps): + #print('step:',i) + if i == step_time - 1: + complete = False + else: + complete = True + # complete = True + #print('complete:',complete) + + latent_model_input = latents + latent_model_input = self.pipeline.scheduler.scale_model_input(latent_model_input, t) + + # Concatenate image_latents over channels dimention + # latent_model_input = torch.cat([mask, latent_model_input, image_latents], dim=2) + latent_model_input = torch.cat([latent_model_input, image_latents], dim=2) + #print('latent_model_input_shape:',latent_model_input.shape) + #print('image_embeddings_shape:',image_embeddings.shape) + + # predict the noise residual + # print('extract_layer_idx:',extract_layer_idx) + # print('latent_model_input_shape:',latent_model_input.shape) + # print('encoder_hidden_states:',image_embeddings.shape) + feature_pred = self.step_unet( + latent_model_input, + t, + encoder_hidden_states=image_embeddings, + added_time_ids=added_time_ids, + use_layer_idx=extract_layer_idx, + all_layer = all_layer, + complete = complete, + )[0] + # feature_pred = self.pipeline.unet(latent_model_input,t,encoder_hidden_states=image_embeddings,added_time_ids=added_time_ids,return_dict=False,)[0] + + # print('feature_pred_shape:',feature_pred.shape) + + if not complete: + break + + latents = self.pipeline.scheduler.step(feature_pred, t, latents).prev_sample + + + # res = self.pipeline.scheduler.step(feature_pred, t, latents) + # pred_x0 = res.pred_original_sample + # latents = res.prev_sample + # frames = self.pipeline.decode_latents(pred_x0, num_frames) + # frames = self.pipeline.video_processor.postprocess_video(video=frames, output_type="np") + # import imageio + # breakpoint() + # imageio.mimsave("output.mp4", frames[3], fps=8) + # imageio.mimsave("image.mp4", pixel_values[3].cpu().permute(1,2,0)[None], fps=8) + + return feature_pred + + # def step_unet( + # self, + # sample: torch.Tensor, + # timestep: Union[torch.Tensor, float, int], + # encoder_hidden_states: torch.Tensor, + # added_time_ids: torch.Tensor, + # use_layer_idx: int = 1, + # ): + # r""" + # The [`UNetSpatioTemporalConditionModel`] forward method. + + # Args: + # sample (`torch.Tensor`): + # The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`. + # timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input. + # encoder_hidden_states (`torch.Tensor`): + # The encoder hidden states with shape `(batch, sequence_length, cross_attention_dim)`. + # added_time_ids: (`torch.Tensor`): + # The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal + # embeddings and added to the time embeddings. + # return_dict (`bool`, *optional*, defaults to `True`): + # Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead + # of a plain tuple. + # Returns: + # [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`: + # If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is + # returned, otherwise a `tuple` is returned where the first element is the sample tensor. + # """ + # # By default samples have to be AT least a multiple of the overall upsampling factor. + # # The overall upsampling factor is equal to 2 ** (# num of upsampling layears). + # # However, the upsampling interpolation output size can be forced to fit any upsampling size + # # on the fly if necessary. + # # default_overall_up_factor = 2**self.num_upsamplers + + # # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor` + # forward_upsample_size = False + # upsample_size = None + + # # if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]): + # # logger.info("Forward upsample size to force interpolation output size.") + # # forward_upsample_size = True + + # # 1. time + # timesteps = timestep + # if not torch.is_tensor(timesteps): + # # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can + # # This would be a good case for the `match` statement (Python 3.10+) + # is_mps = sample.device.type == "mps" + # if isinstance(timestep, float): + # dtype = sample.dtype if is_mps else torch.float64 + # else: + # dtype = torch.int32 if is_mps else torch.int64 + # # print('timestep:',timestep) + # timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) + # elif len(timesteps.shape) == 0: + # timesteps = timesteps[None].to(sample.device) + + # # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + # batch_size, num_frames = sample.shape[:2] + # timesteps = timesteps.expand(batch_size) + + # t_emb = self.pipeline.unet.time_proj(timesteps) + + # # `Timesteps` does not contain any weights and will always return f32 tensors + # # but time_embedding might actually be running in fp16. so we need to cast here. + # # there might be better ways to encapsulate this. + # t_emb = t_emb.to(dtype=sample.dtype) + + # emb = self.pipeline.unet.time_embedding(t_emb) + + # time_embeds = self.pipeline.unet.add_time_proj(added_time_ids.flatten()) + # time_embeds = time_embeds.reshape((batch_size, -1)) + # time_embeds = time_embeds.to(emb.dtype) + # aug_emb = self.pipeline.unet.add_embedding(time_embeds) + # emb = emb + aug_emb + + # # Flatten the batch and frames dimensions + # # sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width] + # sample = sample.flatten(0, 1) + # # Repeat the embeddings num_video_frames times + # # emb: [batch, channels] -> [batch * frames, channels] + # emb = emb.repeat_interleave(num_frames, dim=0) + # # encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels] + # encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0) + + # # 2. pre-process + # sample = self.pipeline.unet.conv_in(sample) + + # image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device) + + # down_block_res_samples = (sample,) + # for downsample_block in self.pipeline.unet.down_blocks: + # if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention: + # sample, res_samples = downsample_block( + # hidden_states=sample, + # temb=emb, + # encoder_hidden_states=encoder_hidden_states, + # image_only_indicator=image_only_indicator, + # ) + # else: + # sample, res_samples = downsample_block( + # hidden_states=sample, + # temb=emb, + # image_only_indicator=image_only_indicator, + # ) + + # down_block_res_samples += res_samples + + # # 4. mid + # sample = self.pipeline.unet.mid_block( + # hidden_states=sample, + # temb=emb, + # encoder_hidden_states=encoder_hidden_states, + # image_only_indicator=image_only_indicator, + # ) + + # # 5. up + # for i, upsample_block in enumerate(self.pipeline.unet.up_blocks): + # is_final_block = i == len(self.pipeline.unet.up_blocks) - 1 + + # res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + # down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] + + # # if we have not reached the final block and need to forward the + # # upsample size, we do it here + # if not is_final_block and forward_upsample_size: + # upsample_size = down_block_res_samples[-1].shape[2:] + + # if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention: + # sample = upsample_block( + # hidden_states=sample, + # temb=emb, + # res_hidden_states_tuple=res_samples, + # encoder_hidden_states=encoder_hidden_states, + # upsample_size=upsample_size, + # image_only_indicator=image_only_indicator, + # ) + # else: + # sample = upsample_block( + # hidden_states=sample, + # temb=emb, + # res_hidden_states_tuple=res_samples, + # upsample_size=upsample_size, + # image_only_indicator=image_only_indicator, + # ) + # if i == use_layer_idx: + # break + # sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) + + # return (sample,) + + + # old one + def step_unet( + self, + sample: torch.Tensor, + timestep: Union[torch.Tensor, float, int], + encoder_hidden_states: torch.Tensor, + added_time_ids: torch.Tensor, + use_layer_idx: int = 5, + all_layer: bool = False, + complete: bool = False, + ) : + r""" + The [`UNetSpatioTemporalConditionModel`] forward method. + + Args: + sample (`torch.Tensor`): + The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`. + timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input. + encoder_hidden_states (`torch.Tensor`): + The encoder hidden states with shape `(batch, sequence_length, cross_attention_dim)`. + added_time_ids: (`torch.Tensor`): + The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal + embeddings and added to the time embeddings. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead + of a plain tuple. + Returns: + [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`: + If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is + returned, otherwise a `tuple` is returned where the first element is the sample tensor. + """ + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can + # This would be a good case for the `match` statement (Python 3.10+) + is_mps = sample.device.type == "mps" + if isinstance(timestep, float): + dtype = torch.float32 if is_mps else torch.float64 + else: + dtype = torch.int32 if is_mps else torch.int64 + timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device) + elif len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + batch_size, num_frames = sample.shape[:2] + timesteps = timesteps.expand(batch_size) + + t_emb = self.pipeline.unet.time_proj(timesteps) + + # `Timesteps` does not contain any weights and will always return f32 tensors + # but time_embedding might actually be running in fp16. so we need to cast here. + # there might be better ways to encapsulate this. + t_emb = t_emb.to(dtype=sample.dtype) + + emb = self.pipeline.unet.time_embedding(t_emb) + + time_embeds = self.pipeline.unet.add_time_proj(added_time_ids.flatten()) + time_embeds = time_embeds.reshape((batch_size, -1)) + time_embeds = time_embeds.to(emb.dtype) + aug_emb = self.pipeline.unet.add_embedding(time_embeds) + emb = emb + aug_emb + + # Flatten the batch and frames dimensions + # sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width] + sample = sample.flatten(0, 1) + # Repeat the embeddings num_video_frames times + # emb: [batch, channels] -> [batch * frames, channels] + emb = emb.repeat_interleave(num_frames, dim=0) + # encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels] + encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0) + + # 2. pre-process + sample = self.pipeline.unet.conv_in(sample) + + image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device) + + down_block_res_samples = (sample,) + for downsample_block in self.pipeline.unet.down_blocks: + #print('sample_shape:',sample.shape) + #print('emb_shape:', emb.shape) + #print('encoder_hidden_states_shape:', encoder_hidden_states.shape) + if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention: + sample, res_samples = downsample_block( + hidden_states=sample, + temb=emb, + encoder_hidden_states=encoder_hidden_states, + image_only_indicator=image_only_indicator, + ) + else: + sample, res_samples = downsample_block( + hidden_states=sample, + temb=emb, + image_only_indicator=image_only_indicator, + ) + + down_block_res_samples += res_samples + + # 4. mid + sample = self.pipeline.unet.mid_block( + hidden_states=sample, + temb=emb, + encoder_hidden_states=encoder_hidden_states, + image_only_indicator=image_only_indicator, + ) + + feature_list = [] + + # 5. up + for i, upsample_block in enumerate(self.pipeline.unet.up_blocks): + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] + down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] + + if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention: + sample = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + encoder_hidden_states=encoder_hidden_states, + image_only_indicator=image_only_indicator, + ) + else: + sample = upsample_block( + hidden_states=sample, + temb=emb, + res_hidden_states_tuple=res_samples, + image_only_indicator=image_only_indicator, + ) + if i < use_layer_idx: + factor = 2**(use_layer_idx - i) + feature_list.append(torch.nn.functional.interpolate(sample,scale_factor=factor)) + #print('up_sample_idx:',i) + if i == use_layer_idx and not complete: + feature_list.append(sample) + break + + if not complete: + if all_layer: + sample = torch.cat(feature_list, dim=1) + sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) + else: + sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) + # 6. post-process + return (sample,) + + else: + sample = self.pipeline.unet.conv_norm_out(sample) + sample = self.pipeline.unet.conv_act(sample) + sample = self.pipeline.unet.conv_out(sample) + + # 7. Reshape back to original shape + sample = sample.reshape(batch_size, num_frames, *sample.shape[1:]) + + return (sample,) + + @torch.no_grad() + def encode_text(self, texts, tokenizer, text_encoder, img_cond=None, img_cond_mask=None, img_encoder=None, position_encode=True, use_clip=False, max_length=20): + def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): + """ + embed_dim: output dimension for each position + pos: a list of positions to be encoded: size (M,) + out: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=np.float64) + omega /= embed_dim / 2. + omega = 1. / 10000**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product + + emb_sin = np.sin(out) # (M, D/2) + emb_cos = np.cos(out) # (M, D/2) + + emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) + return emb + + # max_length = args.clip_token_length + with torch.no_grad(): + if use_clip: + inputs = tokenizer(texts, padding='max_length', return_tensors="pt",truncation=True, max_length=max_length).to(text_encoder.device) + outputs = text_encoder(**inputs) + encoder_hidden_states = outputs.last_hidden_state # (batch, 30, 512) + ###### will be used in the dp ########## + # self.text_embeds = outputs.text_embeds + ###################################### + if position_encode: + embed_dim, pos_num = encoder_hidden_states.shape[-1], encoder_hidden_states.shape[1] + pos = np.arange(pos_num,dtype=np.float64) + + position_encode = get_1d_sincos_pos_embed_from_grid(embed_dim, pos) + position_encode = torch.tensor(position_encode, device=encoder_hidden_states.device, dtype=encoder_hidden_states.dtype, requires_grad=False) + + # print("position_encode",position_encode.shape) + # print("encoder_hidden_states",encoder_hidden_states.shape) + + encoder_hidden_states += position_encode + assert encoder_hidden_states.shape[-1] == 512 + + if img_encoder is not None: + assert img_cond is not None + assert img_cond_mask is not None + # print("img_encoder",img_encoder.shape) + img_cond = img_cond.to(img_encoder.device) + if len(img_cond.shape) == 5: + img_cond = img_cond.squeeze(1) + + img_hidden_states = img_encoder(img_cond).image_embeds + img_hidden_states[img_cond_mask] = 0.0 + img_hidden_states = img_hidden_states.unsqueeze(1).expand(-1,encoder_hidden_states.shape[1],-1) + assert img_hidden_states.shape[-1] == 512 + encoder_hidden_states = torch.cat([encoder_hidden_states, img_hidden_states], dim=-1) + assert encoder_hidden_states.shape[-1] == 1024 + else: + encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states], dim=-1) + + else: + inputs = tokenizer(texts, padding='max_length', return_tensors="pt",truncation=True, max_length=32).to(text_encoder.device) + outputs = text_encoder(**inputs) + encoder_hidden_states = outputs.last_hidden_state # (batch, 30, 512) + assert encoder_hidden_states.shape[1:] == (32,1024) + + return encoder_hidden_states + diff --git a/code/policy_models/module/transformers/__init__.py b/code/policy_models/module/transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/module/transformers/__pycache__/__init__.cpython-310.pyc b/code/policy_models/module/transformers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44717e1f1908ad8fcae8a59c0999c0c3c3826eca Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/module/transformers/__pycache__/__init__.cpython-39.pyc b/code/policy_models/module/transformers/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4cb5e1ec8ce3662869315d7e5341df8657eff6a Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/__init__.cpython-39.pyc differ diff --git a/code/policy_models/module/transformers/__pycache__/position_embeddings.cpython-310.pyc b/code/policy_models/module/transformers/__pycache__/position_embeddings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c57a8e64dfba0b54298ed5f2ac1d2024de8d53d2 Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/position_embeddings.cpython-310.pyc differ diff --git a/code/policy_models/module/transformers/__pycache__/position_embeddings.cpython-39.pyc b/code/policy_models/module/transformers/__pycache__/position_embeddings.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d20ce9dc26d1e0e1d168d0a9d2f654c34a243ada Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/position_embeddings.cpython-39.pyc differ diff --git a/code/policy_models/module/transformers/__pycache__/transformer_blocks.cpython-310.pyc b/code/policy_models/module/transformers/__pycache__/transformer_blocks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a568a2d87e661af155e3fb088cc126a4fe0f2291 Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/transformer_blocks.cpython-310.pyc differ diff --git a/code/policy_models/module/transformers/__pycache__/transformer_blocks.cpython-39.pyc b/code/policy_models/module/transformers/__pycache__/transformer_blocks.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a280f0ca2529386801ed5c9345f4628c79ef1a3b Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/transformer_blocks.cpython-39.pyc differ diff --git a/code/policy_models/module/transformers/__pycache__/utils.cpython-310.pyc b/code/policy_models/module/transformers/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b13829c9c7498a534e01b338f5f36a261690b248 Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/utils.cpython-310.pyc differ diff --git a/code/policy_models/module/transformers/__pycache__/utils.cpython-39.pyc b/code/policy_models/module/transformers/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..608a326e53668146cfa352b5f1e7869009c680f5 Binary files /dev/null and b/code/policy_models/module/transformers/__pycache__/utils.cpython-39.pyc differ diff --git a/code/policy_models/module/transformers/position_embeddings.py b/code/policy_models/module/transformers/position_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..31f6ace5c70e032ddae2d7ff6fe0c62938eda950 --- /dev/null +++ b/code/policy_models/module/transformers/position_embeddings.py @@ -0,0 +1,260 @@ +from matplotlib.pyplot import cla +import torch +import torch.nn as nn +import torch.nn.functional as F +import einops + +from math import pi, log + +import torch +from torch import nn, einsum + +from einops import rearrange, repeat + + +from torch.distributions import Categorical + +from typing import Optional, Tuple + +import logging +import math +from typing import Optional + +import torch +import torch.nn as nn +from torch.nn import functional as F +from omegaconf import DictConfig +import einops + +# code imported from https://github.com/lucidrains/x-transformers +# Rot Embedding copied from https://github.com/lucidrains/rotary-embedding-torch/tree/main +# helper functions + +def exists(val): + return val is not None + +def broadcat(tensors, dim = -1): + num_tensors = len(tensors) + shape_lens = set(list(map(lambda t: len(t.shape), tensors))) + assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions' + shape_len = list(shape_lens)[0] + + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation' + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim = dim) + +# rotary embedding helper functions + +def rotate_half(x): + x = rearrange(x, '... (d r) -> ... d r', r = 2) + x1, x2 = x.unbind(dim = -1) + x = torch.stack((-x2, x1), dim = -1) + return rearrange(x, '... d r -> ... (d r)') + +def apply_rotary_emb(freqs, t, start_index = 0, scale = 1.): + freqs = freqs.to(t) + rot_dim = freqs.shape[-1] + end_index = start_index + rot_dim + assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}' + t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:] + t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale) + return torch.cat((t_left, t, t_right), dim = -1) + +# learned rotation helpers + +def apply_learned_rotations(rotations, t, start_index = 0, freq_ranges = None): + if exists(freq_ranges): + rotations = einsum('..., f -> ... f', rotations, freq_ranges) + rotations = rearrange(rotations, '... r f -> ... (r f)') + + rotations = repeat(rotations, '... n -> ... (n r)', r = 2) + return apply_rotary_emb(rotations, t, start_index = start_index) + +# classes + +class RotaryEmbedding(nn.Module): + def __init__( + self, + dim, + custom_freqs = None, + freqs_for = 'lang', + theta = 10000, + max_freq = 10, + num_freqs = 1, + learned_freq = False, + use_xpos = False, + xpos_scale_base = 512, + interpolate_factor = 1., + theta_rescale_factor = 1. + ): + super().__init__() + # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning + # has some connection to NTK literature + # https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/ + theta *= theta_rescale_factor ** (dim / (dim - 2)) + + if exists(custom_freqs): + freqs = custom_freqs + elif freqs_for == 'lang': + freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)) + elif freqs_for == 'pixel': + freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi + elif freqs_for == 'constant': + freqs = torch.ones(num_freqs).float() + else: + raise ValueError(f'unknown modality {freqs_for}') + + self.cache = dict() + self.cache_scale = dict() + self.freqs = nn.Parameter(freqs, requires_grad = learned_freq) + + # interpolation factors + + assert interpolate_factor >= 1. + self.interpolate_factor = interpolate_factor + + # xpos + + self.use_xpos = use_xpos + if not use_xpos: + self.register_buffer('scale', None) + return + + scale = (torch.arange(0, dim, 2) + 0.4 * dim) / (1.4 * dim) + self.scale_base = xpos_scale_base + self.register_buffer('scale', scale) + + def get_seq_pos(self, seq_len, device, dtype, offset = 0): + return (torch.arange(seq_len, device = device, dtype = dtype) + offset) / self.interpolate_factor + + def rotate_queries_or_keys(self, t, seq_dim = -2, offset = 0): + assert not self.use_xpos, 'you must use `.rotate_queries_and_keys` method instead and pass in both queries and keys, for length extrapolatable rotary embeddings' + device, dtype, seq_len = t.device, t.dtype, t.shape[seq_dim] + freqs = self.forward(lambda: self.get_seq_pos(seq_len, device = device, dtype = dtype, offset = offset), cache_key = f'freqs:{seq_len}|offset:{offset}') + return apply_rotary_emb(freqs, t) + + def rotate_queries_and_keys(self, q, k, seq_dim = -2): + assert self.use_xpos + device, dtype, seq_len = q.device, q.dtype, q.shape[seq_dim] + seq = self.get_seq_pos(seq_len, dtype = dtype, device = device) + freqs = self.forward(lambda: seq, cache_key = f'freqs:{seq_len}') + scale = self.get_scale(lambda: seq, cache_key = f'scale:{seq_len}').to(dtype) + rotated_q = apply_rotary_emb(freqs, q, scale = scale) + rotated_k = apply_rotary_emb(freqs, k, scale = scale ** -1) + return rotated_q, rotated_k + + def get_scale(self, t, cache_key = None): + assert self.use_xpos + + if exists(cache_key) and cache_key in self.cache: + return self.cache[cache_key] + + if callable(t): + t = t() + + scale = 1. + if self.use_xpos: + power = (t - len(t) // 2) / self.scale_base + scale = self.scale ** rearrange(power, 'n -> n 1') + scale = torch.cat((scale, scale), dim = -1) + + if exists(cache_key): + self.cache[cache_key] = scale + + return scale + + def forward(self, t, cache_key = None): + if exists(cache_key) and cache_key in self.cache: + return self.cache[cache_key] + + if callable(t): + t = t() + + freqs = self.freqs + + freqs = torch.einsum('..., f -> ... f', t.type(freqs.dtype), freqs) + freqs = repeat(freqs, '... n -> ... (n r)', r = 2) + + if exists(cache_key): + self.cache[cache_key] = freqs + + return freqs +# norms + +class RelativePositionBias(nn.Module): + def __init__(self, scale, causal = False, num_buckets = 32, max_distance = 128, heads = 8): + super().__init__() + self.scale = scale + self.causal = causal + self.num_buckets = num_buckets + self.max_distance = max_distance + self.relative_attention_bias = nn.Embedding(num_buckets, heads) + + @staticmethod + def _relative_position_bucket(relative_position, causal = True, num_buckets = 32, max_distance = 128): + ret = 0 + n = -relative_position + if not causal: + num_buckets //= 2 + ret += (n < 0).long() * num_buckets + n = torch.abs(n) + else: + n = torch.max(n, torch.zeros_like(n)) + + max_exact = num_buckets // 2 + is_small = n < max_exact + + val_if_large = max_exact + ( + torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact) + ).long() + val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1)) + + ret += torch.where(is_small, n, val_if_large) + return ret + + @property + def device(self): + return next(self.parameters()).device + + def forward(self, i, j): + device = self.device + q_pos = torch.arange(j - i, j, dtype = torch.long, device = device) + k_pos = torch.arange(j, dtype = torch.long, device = device) + rel_pos = k_pos[None, :] - q_pos[:, None] + rp_bucket = self._relative_position_bucket(rel_pos, causal = self.causal, num_buckets = self.num_buckets, max_distance = self.max_distance) + values = self.relative_attention_bias(rp_bucket) + bias = einops.rearrange(values, 'i j h -> h i j') + return bias * self.scale + + +class DynamicPositionBias(nn.Module): + def __init__(self, dim, *, heads, depth, log_distance = False, norm = False): + super().__init__() + assert depth >= 1, 'depth for dynamic position bias MLP must be greater or equal to 1' + self.log_distance = log_distance + + self.mlp = nn.ModuleList([]) + + self.mlp.append(nn.Sequential( + nn.Linear(1, dim), + nn.LayerNorm(dim) if norm else None, + nn.SiLU() + )) + + for _ in range(depth - 1): + self.mlp.append(nn.Sequential( + nn.Linear(dim, dim), + nn.LayerNorm(dim) if norm else None, + nn.SiLU() + )) + + self.mlp.append(nn.Linear(dim, heads)) + diff --git a/code/policy_models/module/transformers/transformer_blocks.py b/code/policy_models/module/transformers/transformer_blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..dd218f6b24cf31d1e16671c5aaaf51140b5bc387 --- /dev/null +++ b/code/policy_models/module/transformers/transformer_blocks.py @@ -0,0 +1,1232 @@ +from matplotlib.pyplot import cla +import torch +import torch.nn as nn +import torch.nn.functional as F +import einops +from inspect import isfunction + +from typing import Optional, Tuple + +import logging +import math +from typing import Optional + +import torch +import torch.nn as nn +from torch.nn import functional as F +from omegaconf import DictConfig +import einops +import matplotlib.pyplot as plt +import os +import numpy as np + +from .position_embeddings import * + + +# 类级别的计数器,用于为每个Attention实例分配唯一ID +_attention_instance_counter = 0 +# 全局字典,用于存储各层cross-attention的累计数据 +_cross_attn_accumulated_data = {} # {batch_idx: {layer_id: accumulated_data}} + +# 可视化模式:'average'(平均)或 'separate'(分别显示) +# 可通过环境变量 CROSS_ATTN_VIS_MODE 设置,默认为 'average' +def _get_cross_attn_vis_mode(): + mode = os.environ.get('CROSS_ATTN_VIS_MODE', 'average').lower() + if mode not in ['average', 'separate']: + mode = 'average' + return mode + + +def default(val, d): + if exists(val): + return val + return d() if isfunction(d) else d + + +class LayerNorm(nn.Module): + """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """ + + def __init__(self, ndim, bias): + super().__init__() + self.weight = nn.Parameter(torch.ones(ndim)) + self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None + + def forward(self, input): + return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5) + + + +# RMSNorm -- Better, simpler alternative to LayerNorm +class RMSNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-8) -> None: + super().__init__() + self.scale, self.eps = dim**-0.5, eps + self.g = nn.Parameter(torch.ones(dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + norm = torch.norm(x, dim=-1, keepdim=True) * self.scale + return x / norm.clamp(min=self.eps) * self.g + + +# SwishGLU -- A Gated Linear Unit (GLU) with the Swish activation; always better than GELU MLP! +class SwishGLU(nn.Module): + def __init__(self, in_dim: int, out_dim: int) -> None: + super().__init__() + self.act, self.project = nn.SiLU(), nn.Linear(in_dim, 2 * out_dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + projected, gate = self.project(x).tensor_split(2, dim=-1) + return projected * self.act(gate) + + + +class Attention(nn.Module): + + def __init__( + self, + n_embd: int, + n_head: int, + attn_pdrop: float, + resid_pdrop: float, + block_size: int, + causal: bool = False, + bias=False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + rotary_emb_dim = None, + rotary_xpos_scale_base = 512, + rotary_interpolation_factor = 1., + ): + super().__init__() + assert n_embd % n_head == 0 + # key, query, value projections for all heads, but in a batch + self.key = nn.Linear(n_embd, n_embd) + self.query = nn.Linear(n_embd, n_embd) + self.value = nn.Linear(n_embd, n_embd) + # output projection + self.c_proj = nn.Linear(n_embd, n_embd, bias=bias) + # regularization + self.attn_dropout = nn.Dropout(attn_pdrop) + self.resid_dropout = nn.Dropout(resid_pdrop) + self.n_head = n_head + self.n_embd = n_embd + self.causal = causal + # flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0 + self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') + if not self.flash: + print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0") + # causal mask to ensure that attention is only applied to the left in the input sequence + self.register_buffer("bias", torch.tril(torch.ones(block_size, block_size)) + .view(1, 1, block_size, block_size)) + self.use_rot_embed = use_rot_embed + if self.use_rot_embed: + # Update (12/2022): Rotary embedding has since been hugely successful, widely adopted in many large language models, including the largest in the world, PaLM. + # However, it has been uncovered in the ALiBi paper that rotary embeddings cannot length extrapolate well. + # This was recently addressed in a Microsoft research paper. + # They propose a way to unobtrusively add the same decay as in ALiBi, and found that this resolves the extrapolation problem. + # You can use it in this repository by setting `rotary_xpos = True`. Like ALiBi, it would enforce the attention to be local. You can set the receptive field with `rotary_xpos_scale_base` value, which defaults to `512` + rotary_emb_dim = max(default(rotary_emb_dim, self.n_head // 2), 32) + self.rotary_pos_emb = RotaryEmbedding( + rotary_emb_dim, + use_xpos = rotary_xpos, + xpos_scale_base = rotary_xpos_scale_base, + interpolate_factor = rotary_interpolation_factor, + ) + + + # 为每个Attention实例分配唯一ID + global _attention_instance_counter + self._instance_id = _attention_instance_counter + _attention_instance_counter += 1 + + # 用于保存可视化计数 + self._vis_counter = 0 + + def _visualize_attention(self, att: torch.Tensor, is_cross_attention: bool = False): + """ + 可视化attention权重(softmax后的) + att: (B, nh, T_q, T_k) attention权重矩阵 + is_cross_attention: 是否为cross-attention + """ + B = att.shape[0] # batch size + + # 如果是cross-attention,累计数据 + if is_cross_attention: + global _cross_attn_accumulated_data + + # 创建输出目录 + vis_dir = "attention_vis" + os.makedirs(vis_dir, exist_ok=True) + + # 循环处理batch内所有样本 + for b_idx in range(B): + # 平均所有头,得到该batch样本的attention权重 + att_vis = att[b_idx].mean(dim=0).detach().cpu().numpy() # (T_q, T_k) + + # 压缩query维度:对T_q维度求平均,得到每个key位置的总体attention + att_vis_1d = att_vis.mean(axis=0) # (T_k,) - 每个key位置受到的平均attention + + # 忽略idx=0,处理剩下的160个位置(idx 1-160) + # 每32个位置累计起来 + chunk_size = 32 + # 跳过idx=0,从idx=1开始处理 + att_vis_filtered = att_vis_1d[1:161] # 取idx 1-160,共160个位置 + + n_chunks = len(att_vis_filtered) // chunk_size # 160 / 32 = 5个chunks + att_vis_accumulated = [] + x_labels = [] + + for i in range(n_chunks): + start_idx_in_filtered = i * chunk_size # 在filtered数组中的索引 + end_idx_in_filtered = (i + 1) * chunk_size + # 实际的idx是从1开始的,所以需要+1 + actual_start_idx = start_idx_in_filtered + 1 + actual_end_idx = end_idx_in_filtered # end_idx_in_filtered=32对应实际idx=32 + chunk_sum = att_vis_filtered[start_idx_in_filtered:end_idx_in_filtered].sum() + att_vis_accumulated.append(chunk_sum) + x_labels.append(f'{actual_start_idx}-{actual_end_idx}') + + # 处理剩余的位置(如果有,但160个位置应该正好是5组,不应该有剩余) + if len(att_vis_filtered) % chunk_size != 0: + start_idx_in_filtered = n_chunks * chunk_size + actual_start_idx = start_idx_in_filtered + 1 + chunk_sum = att_vis_filtered[start_idx_in_filtered:].sum() + att_vis_accumulated.append(chunk_sum) + x_labels.append(f'{actual_start_idx}-{len(att_vis_1d)-1}') + + att_vis_accumulated = np.array(att_vis_accumulated) + + # 存储到全局字典中(确保b_idx存在) + if b_idx not in _cross_attn_accumulated_data: + _cross_attn_accumulated_data[b_idx] = {} + _cross_attn_accumulated_data[b_idx][self._instance_id] = { + 'data': att_vis_accumulated, + 'x_labels': x_labels, + 'step': self._vis_counter, + 'full_map': att_vis + } + + # 检查当前batch是否已经收集了4层cross-attention数据 + if b_idx in _cross_attn_accumulated_data and len(_cross_attn_accumulated_data[b_idx]) >= 4: + # 保存数据到txt文件 + self._save_accumulated_cross_attn_to_txt(b_idx) + # 保存最后一层的热力图 + self._save_last_layer_heatmap(b_idx) + # 可视化(如果需要) + self._plot_accumulated_cross_attn(b_idx) + + self._vis_counter += 1 + else: + # 非cross-attention的情况,保持原有逻辑(如果需要的话) + pass + + def _save_accumulated_cross_attn_to_txt(self, b_idx): + """保存所有层cross-attention的累计结果到txt文件""" + global _cross_attn_accumulated_data + + if b_idx not in _cross_attn_accumulated_data: + return + + layer_data = _cross_attn_accumulated_data[b_idx] + + # 确保有4层数据 + if len(layer_data) < 4: + return + + vis_dir = "attention_vis" + os.makedirs(vis_dir, exist_ok=True) + + # 获取x_labels(应该所有层都一样) + x_labels = None + for layer_id in sorted(layer_data.keys()): + if x_labels is None: + x_labels = layer_data[layer_id]['x_labels'] + break + + sorted_layer_ids = sorted(layer_data.keys())[:4] + step = layer_data[sorted_layer_ids[0]]['step'] + + # 收集所有层的数据(separate模式) + all_data = {} + for layer_id in sorted_layer_ids: + all_data[layer_id] = layer_data[layer_id]['data'] + + # 计算平均数据(从separate数据计算) + all_data_array = np.stack([all_data[layer_id] for layer_id in sorted_layer_ids], axis=0) # (4, n_chunks) + averaged_data = all_data_array.mean(axis=0) # (n_chunks,) + + # 保存到txt文件 + filename = os.path.join(vis_dir, f'attn_accumulated_step{step:04d}_batch{b_idx}.txt') + with open(filename, 'w') as f: + f.write(f"Cross-Attention Accumulated Data - Batch {b_idx}, Step {step}\n") + f.write("=" * 60 + "\n\n") + + # 写入x_labels(位置范围) + f.write("Key Position Ranges (每32个累计):\n") + f.write(", ".join(x_labels) + "\n\n") + + # 写入每层的数据(separate模式) + f.write("Separate Mode - Each Layer Data:\n") + f.write("-" * 60 + "\n") + for layer_id in sorted_layer_ids: + data = all_data[layer_id] + f.write(f"Layer {layer_id}:\n") + f.write(", ".join([f"{val:.6f}" for val in data]) + "\n") + f.write(f" Sum: {data.sum():.6f}, Mean: {data.mean():.6f}, Max: {data.max():.6f}, Min: {data.min():.6f}\n\n") + + # 写入平均数据(从separate计算得出) + f.write("Average Mode - Average of 4 Layers (calculated from separate data):\n") + f.write("-" * 60 + "\n") + f.write(", ".join([f"{val:.6f}" for val in averaged_data]) + "\n") + f.write(f" Sum: {averaged_data.sum():.6f}, Mean: {averaged_data.mean():.6f}, Max: {averaged_data.max():.6f}, Min: {averaged_data.min():.6f}\n") + + print(f"Cross-Attention数据已保存到txt: {filename} (Batch {b_idx})") + print(f" 包含4层separate数据和average数据(从separate计算得出)") + + def _save_last_layer_heatmap(self, b_idx): + """仅保存最后一层cross-attention的热力图(不压缩action维度,但key维度按32分组)""" + global _cross_attn_accumulated_data + + if b_idx not in _cross_attn_accumulated_data: + return + + layer_data = _cross_attn_accumulated_data[b_idx] + + if len(layer_data) < 4: + return + + # 取layer_id最大的那一层,视作最后一层 + last_layer_id = max(layer_data.keys()) + if 'full_map' not in layer_data[last_layer_id]: + return + + heatmap = layer_data[last_layer_id]['full_map'] # (T_q, T_k) + step = layer_data[last_layer_id]['step'] + + # 对key维度进行压缩:忽略idx=0,每32个位置分组 + chunk_size = 32 + T_q, T_k = heatmap.shape + + # 跳过idx=0,从idx=1开始处理,最多取到160(即索引1-160,共160个位置) + # 如果T_k小于161,则取到T_k-1 + end_idx_filtered = min(161, T_k) + heatmap_filtered = heatmap[:, 1:end_idx_filtered] # (T_q, min(160, T_k-1)) + + # 将key位置压缩成组(每32个一组) + n_chunks = heatmap_filtered.shape[1] // chunk_size + heatmap_compressed = [] + # 固定横坐标标签为 "-40 -20 0 20 40" + fixed_x_labels = ['-40', '-20', '0', '20', '40'] + + for i in range(n_chunks): + start_idx = i * chunk_size + end_idx = (i + 1) * chunk_size + # 对每个query位置,将该组的32个key位置的attention求和 + chunk_sum = heatmap_filtered[:, start_idx:end_idx].sum(axis=1, keepdims=True) # (T_q, 1) + heatmap_compressed.append(chunk_sum) + + # 处理剩余的位置(如果有) + if heatmap_filtered.shape[1] % chunk_size != 0: + start_idx = n_chunks * chunk_size + chunk_sum = heatmap_filtered[:, start_idx:].sum(axis=1, keepdims=True) + heatmap_compressed.append(chunk_sum) + + # 使用固定的横坐标标签 + x_labels = fixed_x_labels[:len(heatmap_compressed)] + + # 拼接成压缩后的热力图 (T_q, n_groups) + if len(heatmap_compressed) > 0: + heatmap_compressed = np.concatenate(heatmap_compressed, axis=1) # (T_q, n_groups) + else: + # 如果没有数据,创建一个空的热力图 + heatmap_compressed = np.zeros((T_q, 1)) + + vis_dir = "attention_vis" + os.makedirs(vis_dir, exist_ok=True) + + # 设置字体为 Times New Roman + plt.rcParams['font.family'] = 'Times New Roman' + + plt.figure(figsize=(10, 8)) + plt.imshow(heatmap_compressed, cmap='viridis', aspect='auto') + cbar = plt.colorbar(label='Attention Weight') + cbar.set_label('Attention Weight', fontsize=24, fontfamily='Times New Roman') + cbar.ax.tick_params(labelsize=20) + # 设置 colorbar 刻度字体 + for label in cbar.ax.get_yticklabels(): + label.set_fontfamily('Times New Roman') + # plt.title(f'Last Layer Cross-Attention Heatmap (Layer {last_layer_id})\nBatch {b_idx}, Step {step}', fontsize=13) + plt.xlabel('View angle', fontsize=24, fontfamily='Times New Roman') + plt.ylabel('Action', fontsize=24, fontfamily='Times New Roman') + plt.xticks(range(len(x_labels)), x_labels, rotation=0, ha='center', fontsize=20) + plt.yticks(fontsize=20) + # 设置刻度标签字体 + for label in plt.gca().get_xticklabels(): + label.set_fontfamily('Times New Roman') + for label in plt.gca().get_yticklabels(): + label.set_fontfamily('Times New Roman') + plt.tight_layout() + + filename = os.path.join(vis_dir, f'attn_heatmap_last_layer_step{step:04d}_batch{b_idx}.png') + plt.savefig(filename, dpi=150, bbox_inches='tight') + plt.close() + + print(f"最后一层Cross-Attention热力图已保存: {filename} (Batch {b_idx}, Layer {last_layer_id}, Shape: {heatmap_compressed.shape})") + + def _plot_accumulated_cross_attn(self, b_idx): + """绘制所有层cross-attention的累计结果""" + global _cross_attn_accumulated_data + + if b_idx not in _cross_attn_accumulated_data: + return + + layer_data = _cross_attn_accumulated_data[b_idx] + + # 确保有4层数据 + if len(layer_data) < 4: + return + + vis_mode = _get_cross_attn_vis_mode() + vis_dir = "attention_vis" + + # 设置字体为 Times New Roman + plt.rcParams['font.family'] = 'Times New Roman' + + # 创建图表 + plt.figure(figsize=(12, 6)) + + # 获取x_labels(应该所有层都一样) + x_labels = None + for layer_id in sorted(layer_data.keys()): + if x_labels is None: + x_labels = layer_data[layer_id]['x_labels'] + break + + sorted_layer_ids = sorted(layer_data.keys())[:4] + + if vis_mode == 'average': + # 平均模式:将四层数据求平均后绘制一条曲线 + all_data = [] + for layer_id in sorted_layer_ids: + data = layer_data[layer_id]['data'] + all_data.append(data) + + # 将四层数据堆叠后求平均 + all_data_array = np.stack(all_data, axis=0) # (4, n_chunks) + averaged_data = all_data_array.mean(axis=0) # (n_chunks,) + + # 绘制平均后的曲线 + step = layer_data[sorted_layer_ids[0]]['step'] + plt.plot(range(len(averaged_data)), averaged_data, linewidth=2, marker='o', markersize=4, + color='steelblue', alpha=0.8, label='Average (4 Layers)') + + plt.title(f'Average Cross-Attention (All 4 Layers) - Batch {b_idx}', fontsize=18, fontfamily='Times New Roman') + else: + # 分别显示模式:绘制四条曲线 + colors = ['steelblue', 'coral', 'mediumseagreen', 'mediumpurple'] # 4种颜色对应4层 + for i, layer_id in enumerate(sorted_layer_ids): + data = layer_data[layer_id]['data'] + step = layer_data[layer_id]['step'] + color = colors[i % len(colors)] + plt.plot(range(len(data)), data, linewidth=2, marker='o', markersize=4, + color=color, alpha=0.8, label=f'Layer {layer_id}') + + plt.title(f'Accumulated Cross-Attention (All Layers) - Batch {b_idx}', fontsize=18, fontfamily='Times New Roman') + legend = plt.legend(loc='best', fontsize=16) + for text in legend.get_texts(): + text.set_fontfamily('Times New Roman') + + plt.xlabel('Key Position (每32个累计)', fontsize=18, fontfamily='Times New Roman') + plt.ylabel('Cumulative Attention Weight', fontsize=18, fontfamily='Times New Roman') + plt.xticks(range(len(x_labels)), x_labels, rotation=45, ha='right', fontsize=16) + plt.yticks(fontsize=16) + # 设置刻度标签字体 + for label in plt.gca().get_xticklabels(): + label.set_fontfamily('Times New Roman') + for label in plt.gca().get_yticklabels(): + label.set_fontfamily('Times New Roman') + plt.ylim(0.15, 0.25) # 统一纵坐标单位,范围0.15-0.25 + plt.grid(alpha=0.3, linestyle='--') + plt.tight_layout() + + # 保存累计可视化图像 + step = layer_data[sorted_layer_ids[0]]['step'] + filename = os.path.join(vis_dir, f'attn_vis_accumulated_step{step:04d}_batch{b_idx}.png') + plt.savefig(filename, dpi=150, bbox_inches='tight') + plt.close() + + print(f"累计Cross-Attention可视化已保存: {filename} (Batch {b_idx}, Mode: {vis_mode})") + + # 清理该batch的数据 + del _cross_attn_accumulated_data[b_idx] + + def forward(self, x, context=None, custom_attn_mask=None): + B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd) + + # calculate query, key, values for all heads in batch and move head forward to be the batch dim + # if the context is not None we do cross-attention othberwise self=attention + # cross attention computes the query from x and the keys and values are from the context + if context is not None: + k = self.key(context).view(B, -1, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) + q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) + v = self.value(context).view(B, -1, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) + else: + k = self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) + q = self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) + v = self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) + + # apply rotary stuff here if needed: + if self.use_rot_embed: + q = self.rotary_pos_emb.rotate_queries_or_keys(q) + k = self.rotary_pos_emb.rotate_queries_or_keys(k) + + # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T) + if self.flash: + # efficient attention using Flash Attention CUDA kernels + y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=custom_attn_mask, dropout_p=self.attn_dropout.p if self.training else 0, is_causal=self.causal) + # if context is not None: + # # 为了可视化,手动计算attention权重(softmax后的) + # att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) + # if custom_attn_mask is not None: + # att = att.masked_fill(custom_attn_mask == 0, float('-inf')) + # att = F.softmax(att, dim=-1) # softmax后的attention权重 + # # 可视化attention(softmax后) + # self._visualize_attention(att, context is not None) + else: + # manual implementation of attention + att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) + if self.causal: + if custom_attn_mask is not None: + att = att.masked_fill(custom_attn_mask == 0, float('-inf')) + else: + att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf')) + att = F.softmax(att, dim=-1) + att = self.attn_dropout(att) + y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs) + y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side + + # output projection + y = self.resid_dropout(self.c_proj(y)) + return y + + +class MLP(nn.Module): + + def __init__( + self, + n_embd: int, + bias: bool, + dropout: float = 0 + ): + super().__init__() + self.c_fc = nn.Linear(n_embd, 4 * n_embd, bias=bias) + self.gelu = nn.GELU() + self.c_proj = nn.Linear(4 * n_embd, n_embd, bias=bias) + self.dropout = nn.Dropout(dropout) + + def forward(self, x): + x = self.c_fc(x) + x = self.gelu(x) + x = self.c_proj(x) + x = self.dropout(x) + return x + + +class Block(nn.Module): + + def __init__( + self, + n_embd: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + mlp_pdrop: float, + block_size: int, + causal: bool, + use_cross_attention: bool = False, + use_rot_embed: bool=False, + rotary_xpos: bool = False, + bias: bool = False, # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster + ): + super().__init__() + self.ln_1 = LayerNorm(n_embd, bias=bias) + self.attn = Attention(n_embd, n_heads, attn_pdrop, resid_pdrop, block_size, causal, bias, use_rot_embed, rotary_xpos) + self.use_cross_attention = use_cross_attention + if self.use_cross_attention: + self.cross_att = Attention(n_embd, n_heads, attn_pdrop, resid_pdrop, block_size, causal, bias, use_rot_embed, rotary_xpos) + self.ln3 = nn.LayerNorm(n_embd) + self.ln_2 = LayerNorm(n_embd, bias=bias) + self.mlp = MLP(n_embd, bias, mlp_pdrop) + + def forward(self, x, context=None, custom_attn_mask=None): + x = x + self.attn(self.ln_1(x), custom_attn_mask=custom_attn_mask) + if self.use_cross_attention and context is not None: + x = x + self.cross_att(self.ln3(x), context, custom_attn_mask=custom_attn_mask) + x = x + self.mlp(self.ln_2(x)) + return x + + + +class CrossAttentionOnlyBlock(nn.Module): + + def __init__( + self, + n_embd: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + mlp_pdrop: float, + block_size: int, + causal: bool, + use_rot_embed: bool=False, + rotary_xpos: bool = False, + bias: bool = False, # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster + ): + super().__init__() + self.ln_1 = LayerNorm(n_embd, bias=bias) + self.cross_att = Attention(n_embd, n_heads, attn_pdrop, resid_pdrop, block_size, causal, bias, use_rot_embed, rotary_xpos) + self.ln_2 = LayerNorm(n_embd, bias=bias) + self.mlp = MLP(n_embd, bias, mlp_pdrop) + + def forward(self, x, context=None, custom_attn_mask=None): + x = x + self.cross_att(self.ln_1(x), context, custom_attn_mask=custom_attn_mask) + x = x + self.mlp(self.ln_2(x)) + return x + + +class AdaLNZero(nn.Module): + """ + AdaLN-Zero modulation for conditioning. + """ + def __init__(self, hidden_size): + super().__init__() + self.modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(hidden_size, 6 * hidden_size, bias=True) + ) + # Initialize weights and biases to zero + # nn.init.zeros_(self.modulation[1].weight) + # nn.init.zeros_(self.modulation[1].bias) + + def forward(self, c): + return self.modulation(c).chunk(6, dim=-1) + +def modulate(x, shift, scale): + return shift + (x * (scale)) + + +class ConditionedBlock(Block): + """ + Block with AdaLN-Zero conditioning. + """ + def __init__( + self, + n_embd, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal, + film_cond_dim, + use_cross_attention=False, + use_rot_embed=False, + rotary_xpos=False, + bias=False # and any other arguments from the Block class + ): + super().__init__(n_embd, n_heads, attn_pdrop, resid_pdrop, mlp_pdrop, block_size, causal, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias) + self.adaLN_zero = AdaLNZero(film_cond_dim) + + def forward(self, x, c, context=None, custom_attn_mask=None): + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_zero(c) + + # Attention with modulation + x_attn = self.ln_1(x) + x_attn = modulate(x_attn, shift_msa, scale_msa) + x = x + gate_msa * self.attn(x_attn, custom_attn_mask=custom_attn_mask) + + # Cross attention if used + if self.use_cross_attention and context is not None: + x = x + self.cross_att(self.ln3(x), context, custom_attn_mask=custom_attn_mask) + + # MLP with modulation + x_mlp = self.ln_2(x) + x_mlp = modulate(x_mlp, shift_mlp, scale_mlp) + x = x + gate_mlp * self.mlp(x_mlp) + + return x + +class NoiseBlock(Block): + """ + Block with AdaLN-Zero conditioning. + """ + def __init__( + self, + n_embd, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal, + use_cross_attention=False, + use_rot_embed=False, + rotary_xpos=False, + bias=False # and any other arguments from the Block class + ): + super().__init__(n_embd, n_heads, attn_pdrop, resid_pdrop, mlp_pdrop, block_size, causal, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias) + + def forward(self, x, c, context=None, custom_attn_mask=None): + + x = x + self.attn(self.ln_1(x) + c, custom_attn_mask=custom_attn_mask) + if self.use_cross_attention and context is not None: + x = x + self.cross_att(self.ln3(x) + c, context, custom_attn_mask=custom_attn_mask) + x = x + self.mlp(self.ln_2(x)) + return x + + +class TransformerEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + ): + super().__init__() + self.blocks = nn.Sequential( + *[Block( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=False, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, custom_attn_mask=None): + for layer in self.blocks: + x = layer(x, custom_attn_mask=custom_attn_mask) + x = self.ln(x) + return x + + +class TransformerEncoderInterleaved(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + ): + super().__init__() + self.blocks = nn.Sequential( + *[Block( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=False, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x): + outputs = [] + for layer in self.blocks: + x = layer(x) + outputs.append(x) + x = self.ln(x) + outputs.pop(-1) + outputs.append(x) + return outputs + + +class TransformerFiLMEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + film_cond_dim: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + ): + super().__init__() + self.blocks = nn.Sequential( + *[ConditionedBlock( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=False, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias, + film_cond_dim=film_cond_dim + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, c): + for layer in self.blocks: + x = layer(x, c) + x = self.ln(x) + return x + + +class TransformerDecoder(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + use_cross_attention: bool = True, + ): + super().__init__() + self.blocks = nn.Sequential( + *[Block( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=True, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, cond=None, custom_attn_mask=None): + for layer in self.blocks: + x = layer(x, cond, custom_attn_mask=custom_attn_mask) + x = self.ln(x) + return x + + + +class TransformerFiLMDecoder(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + film_cond_dim: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + use_cross_attention: bool = True, + use_noise_encoder: bool = False, + kwargs: Optional[DictConfig] = None, + ): + super().__init__() + if use_noise_encoder: + self.blocks = nn.Sequential( + *[NoiseBlock( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=True, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias, + ) + for _ in range(n_layers)] + ) + else: + self.blocks = nn.Sequential( + *[ConditionedBlock( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=True, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias, + film_cond_dim=film_cond_dim, + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, c, cond=None, custom_attn_mask=None): + for layer in self.blocks: + x = layer(x, c, cond, custom_attn_mask=custom_attn_mask) + x = self.ln(x) + return x + + +class TransformerFiLMDecoderInterleaved(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + film_cond_dim: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + use_cross_attention: bool = True, + use_noise_encoder: bool = False, + kwargs: Optional[DictConfig] = None, + ): + super().__init__() + if use_noise_encoder: + self.blocks = nn.Sequential( + *[NoiseBlock( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=True, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias, + ) + for _ in range(n_layers)] + ) + else: + self.blocks = nn.Sequential( + *[ConditionedBlock( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=True, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias, + film_cond_dim=film_cond_dim, + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, c, cond=None, custom_attn_mask=None): + for idx, layer in enumerate(self.blocks): + cond_tokens =cond[idx] + x = layer(x, c, cond_tokens, custom_attn_mask=custom_attn_mask) + x = self.ln(x) + return x + + +class TransformerCrossAttentionEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + use_cross_attention: bool = True, + ): + super().__init__() + self.blocks = nn.Sequential( + *[Block( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=False, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, cond=None, custom_attn_mask=None): + for layer in self.blocks: + x = layer(x, cond, custom_attn_mask=custom_attn_mask) + x = self.ln(x) + return x + + +class TransformerCrossAttentionOnlyEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + use_cross_attention: bool = True, + ): + super().__init__() + self.blocks = nn.Sequential( + *[CrossAttentionOnlyBlock( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=False, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, cond=None, custom_attn_mask=None): + for layer in self.blocks: + x = layer(x, cond, custom_attn_mask=custom_attn_mask) + x = self.ln(x) + return x + +# As defined in Set Transformers () -- basically the above, additionally taking in +# a set of $k$ learned "seed vectors" that are used to "pool" information. +class MAPAttention(nn.Module): + def __init__(self, embed_dim: int, n_heads: int) -> None: + """Multi-Input Multi-Headed Attention Operation""" + super().__init__() + assert embed_dim % n_heads == 0, "`embed_dim` must be divisible by `n_heads`!" + self.n_heads, self.scale = n_heads, (embed_dim // n_heads) ** -0.5 + + # Projections (no bias) --> separate for Q (seed vector), and KV ("pool" inputs) + self.q, self.kv = nn.Linear(embed_dim, embed_dim, bias=False), nn.Linear(embed_dim, 2 * embed_dim, bias=False) + self.proj = nn.Linear(embed_dim, embed_dim) + + def forward(self, seed: torch.Tensor, x: torch.Tensor) -> torch.Tensor: + (B_s, K, C_s), (B_x, N, C_x) = seed.shape, x.shape + assert C_s == C_x, "Seed vectors and pool inputs must have the same embedding dimensionality!" + + # Project Seed Vectors to `queries` + q = self.q(seed).reshape(B_s, K, self.n_heads, C_s // self.n_heads).permute(0, 2, 1, 3) + kv = self.kv(x).reshape(B_x, N, 2, self.n_heads, C_x // self.n_heads).permute(2, 0, 3, 1, 4) + k, v = kv.unbind(0) + + # Attention --> compute weighted sum over values! + scores = q @ (k.transpose(-2, -1) * self.scale) + attn = scores.softmax(dim=-1) + vals = (attn @ v).transpose(1, 2).reshape(B_s, K, C_s) + + # Project back to `embed_dim` + return self.proj(vals) + + +class MAPBlock(nn.Module): + def __init__( + self, + n_latents: int, + embed_dim: int, + n_heads: int, + output_dim: None, + mlp_ratio: float = 4.0, + do_rms_norm: bool = True, + do_swish_glu: bool = True, + ) -> None: + """Multiheaded Attention Pooling Block -- note that for MAP, we adopt earlier post-norm conventions.""" + super().__init__() + self.n_latents, self.embed_dim, self.n_heads = n_latents, embed_dim, 2 * n_heads + + self.embed_dim = output_dim + # Projection Operator + self.projection = nn.Linear(embed_dim, self.embed_dim) + + # Initialize Latents + self.latents = nn.Parameter(torch.zeros(self.n_latents, self.embed_dim)) + nn.init.normal_(self.latents, std=0.02) + + # Custom MAP Attention (seed, encoder outputs) -> seed + self.attn_norm = RMSNorm(self.embed_dim) if do_rms_norm else nn.LayerNorm(self.embed_dim, eps=1e-6) + self.attn = MAPAttention(self.embed_dim, n_heads=self.n_heads) + if output_dim is None: + output_dim = self.embed_dim + # Position-wise Feed-Forward Components + self.mlp_norm = RMSNorm(self.embed_dim) if do_rms_norm else nn.LayerNorm(self.embed_dim, eps=1e-6) + self.mlp = nn.Sequential( + # Handle SwishGLU vs. GELU MLP... + ( + SwishGLU(self.embed_dim, int(mlp_ratio * self.embed_dim)) + if do_swish_glu + else nn.Sequential(nn.Linear(self.embed_dim, int(mlp_ratio * self.embed_dim)), nn.GELU()) + ), + nn.Linear(int(mlp_ratio * self.embed_dim), self.embed_dim), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + latents = repeat(self.latents, "n_latents d -> bsz n_latents d", bsz=x.shape[0]) + latents = self.attn_norm(latents + self.attn(latents, self.projection(x))) + latents = self.mlp_norm(latents + self.mlp(latents)) + return latents.squeeze(dim=1) + + +class SiamneseDecoder(nn.Module): + def __init__( + self, + embed_dim: int, + n_heads: int, + attn_pdrop: float, + resid_pdrop: float, + n_layers: int, + block_size: int, + bias: bool = False, + use_rot_embed: bool = False, + rotary_xpos: bool = False, + mlp_pdrop: float = 0, + use_cross_attention: bool = True, + ): + super().__init__() + self.blocks = nn.Sequential( + *[Block( + embed_dim, + n_heads, + attn_pdrop, + resid_pdrop, + mlp_pdrop, + block_size, + causal=False, + use_cross_attention=use_cross_attention, + use_rot_embed=use_rot_embed, + rotary_xpos=rotary_xpos, + bias=bias + ) + for _ in range(n_layers)] + ) + self.ln = LayerNorm(embed_dim, bias) + + def forward(self, x, cond=None, custom_attn_mask=None): + for layer in self.blocks: + x = layer(x, cond, custom_attn_mask=custom_attn_mask) + x = self.ln(x) + return x + + +class ClipStyleProjection(nn.Module): + + def __init__(self, clip_style, token_dim=384, clip_token_index=0, num_token=4): + super(ClipStyleProjection, self).__init__() + self.clip_style = clip_style + self.clip_token_index = clip_token_index + if clip_style == 'map' or clip_style == 'map_state_only': + self.latent_proj = MAPBlock(1, token_dim, 8, output_dim=token_dim) + elif clip_style == 'mean_pooling' or clip_style == 'mean_pool_state_only': + self.latent_proj = MeanPooling(token_dim) + elif clip_style == 'mlp': + self.latent_proj = nn.Sequential( + nn.Linear(num_token * token_dim, token_dim), + nn.LayerNorm(token_dim), + nn.Tanh() + ) + elif clip_style == 'single_token': + self.latent_proj = nn.Identity() + elif clip_style == 'multihead': + self.latent_proj = nn.Identity() # No projection needed + else: + raise ValueError("Invalid clip_style. Expected 'map', 'mean_pooling', or 'single_token' or 'multihead'.") + # print(self.clip_style) + + def forward(self, x): + # print('clip style is ' + self.clip_style) + # print(f'x shape {x.shape}') + if self.clip_style == 'single_token': + x = x[:, self.clip_token_index, :] + elif self.clip_style == 'map_state_only' or self.clip_style == 'mean_pool_state_only': + x = x[:, 1:] + elif self.clip_style == 'mlp': + # print('reshaping before clip') + x = einops.rearrange(x, 'b t d -> b (t d)') + # print(x.shape) + return self.latent_proj(x) + + +class MeanPooling(nn.Module): + def __init__(self, token_dim): + super(MeanPooling, self).__init__() + self.token_dim = token_dim + + def forward(self, x): + return x.mean(dim=1).view(-1, self.token_dim) + diff --git a/code/policy_models/module/transformers/utils.py b/code/policy_models/module/transformers/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6009f4715b48bc81be586c21f96146b8967da8cb --- /dev/null +++ b/code/policy_models/module/transformers/utils.py @@ -0,0 +1,50 @@ +import torch +from torch import nn + + +class SquaredReLU(nn.Module): + """Squared ReLU activation function""" + + def __init__(self): + super().__init__() + + def forward(self, x): + return torch.pow(torch.relu(x), 2) + + +def feed_forward_layer(dim: int, mult: int = 4, activation: str = 'gelu'): + """Feed forward layer with given activation function""" + + activations = dict(gelu=nn.GELU, sqrelu=SquaredReLU, relu=nn.ReLU) + assert activation in activations, f'activation can only be one of {activations.keys()}' + + inner_dim = int(dim * mult) + return nn.Sequential( + nn.LayerNorm(dim), + nn.Linear(dim, inner_dim, bias=False), + activations[activation](), + nn.Linear(inner_dim, dim, bias=False), + ) + +# RMSNorm -- Better, simpler alternative to LayerNorm +class RMSNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-8) -> None: + super().__init__() + self.scale, self.eps = dim**-0.5, eps + self.g = nn.Parameter(torch.ones(dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + norm = torch.norm(x, dim=-1, keepdim=True) * self.scale + return x / norm.clamp(min=self.eps) * self.g + + +# SwishGLU -- A Gated Linear Unit (GLU) with the Swish activation; always better than GELU MLP! +class SwishGLU(nn.Module): + def __init__(self, in_dim: int, out_dim: int) -> None: + super().__init__() + self.act, self.project = nn.SiLU(), nn.Linear(in_dim, 2 * out_dim) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + projected, gate = self.project(x).tensor_split(2, dim=-1) + return projected * self.act(gate) + diff --git a/code/policy_models/rollout/__init__.py b/code/policy_models/rollout/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/rollout/__pycache__/__init__.cpython-310.pyc b/code/policy_models/rollout/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c156223118dbbeaed9eaa7ceb094b3f86f68fa3 Binary files /dev/null and b/code/policy_models/rollout/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/rollout/__pycache__/rollout_video.cpython-310.pyc b/code/policy_models/rollout/__pycache__/rollout_video.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f645c74c11e24f19c09e0e882462cb12da3e4af3 Binary files /dev/null and b/code/policy_models/rollout/__pycache__/rollout_video.cpython-310.pyc differ diff --git a/code/policy_models/rollout/rollout.py b/code/policy_models/rollout/rollout.py new file mode 100644 index 0000000000000000000000000000000000000000..5b6e5a318237fad7c6a07fc6519bc29c5ec85e66 --- /dev/null +++ b/code/policy_models/rollout/rollout.py @@ -0,0 +1,427 @@ +from collections import defaultdict +from functools import partial, reduce +import logging +from operator import add +from typing import Any, Dict, List, Tuple + +import hydra +import numpy as np +from pytorch_lightning import Callback, LightningModule, Trainer +import torch +import torch.distributed as dist + +from policy_models.datasets.base_dataset import get_validation_window_size +from policy_models.rollout.rollout_video import RolloutVideo +from policy_models.utils.utils import get_portion_of_batch_ids + +log_print = logging.getLogger(__name__) + + +def log_rank_0(*args, **kwargs): + # when using ddp, only log with rank 0 process + if dist.is_available() and dist.is_initialized() and dist.get_rank() != 0: + return + log_print.info(*args, **kwargs) + + +def select_first(all_task_ids, num, *args, **kwargs): + """ + Select the first num indices + """ + return all_task_ids[:num] + + +def select_balanced(all_task_ids, num, *args, **kwargs): + """ + Select the indices equally balanced validation + """ + split_ids = np.array_split(sorted(all_task_ids), num)[: len(all_task_ids)] + return [ids[0] for ids in split_ids] + + +def select_longest(all_task_ids, num, min_window_size, max_window_size): + """ + Select the indices with the longest sequence window + """ + sorted_ids = sorted( + all_task_ids, + key=partial(get_validation_window_size, min_window_size=min_window_size, max_window_size=max_window_size), + reverse=True, + ) + return sorted_ids[:num] + + +def get_video_tag(task, mod): + return f"_{mod}/{list(task)[0]}" + + +class Rollout(Callback): + """ + A class for performing rollouts during validation step. + """ + + def __init__( + self, + env_cfg, + skip_epochs, + rollout_freq, + video, + num_rollouts_per_task, + check_percentage_of_batch, + replan_freq, + ep_len, + tasks, + empty_cache, + log_video_to_file, + save_dir, + start_robot_neutral, + add_goal_thumbnail, + min_window_size, + max_window_size, + lang_folder, + id_selection_strategy="select_first", + ): + self.env = None # type: Any + self.env_cfg = env_cfg + self.tasks = hydra.utils.instantiate(tasks) + self.skip_epochs = skip_epochs + self.rollout_freq = rollout_freq + self.video = video + self.num_rollouts_per_task = num_rollouts_per_task + self.check_percentage_of_batch = check_percentage_of_batch + self.replan_freq = replan_freq + self.ep_len = ep_len + self.empty_cache = empty_cache + self.log_video_to_file = log_video_to_file + self.save_dir = save_dir + self.task_to_id_dict = None # type: Any + self.id_to_task_dict = None # type: Any + self.full_task_to_id_dict = None # type: Any + self.groundtruth_task_counter = None # type: Any + self.rollout_video = None # type: Any + self.device = None # type: Any + self.outputs = [] + self.start_robot_neutral = start_robot_neutral + self.modalities = [] # ["vis", "lang"] if self.lang else ["vis"] + self.embeddings = None + self.add_goal_thumbnail = add_goal_thumbnail + self.lang_folder = lang_folder + self.current_epoch = 0 + self.pick_task_ids = partial( + eval(id_selection_strategy), min_window_size=min_window_size, max_window_size=max_window_size + ) + + def on_validation_start(self, trainer: Trainer, pl_module: LightningModule) -> None: + """Called when the validation loop begins.""" + if self.env is None: + self.modalities = trainer.datamodule.modalities # type: ignore + self.device = pl_module.device + dataset = trainer.val_dataloaders[0].dataset.datasets["vis"] # type: ignore + from policy_models.rollout.rollout_long_horizon import RolloutLongHorizon + + for callback in trainer.callbacks: + if isinstance(callback, RolloutLongHorizon) and callback.env is not None: + self.env = callback.env + break + else: + self.env = hydra.utils.instantiate(self.env_cfg, dataset, pl_module.device) + if self.video: + self.rollout_video = RolloutVideo( + logger=pl_module.logger, + empty_cache=self.empty_cache, + log_to_file=self.log_video_to_file, + save_dir=self.save_dir, + ) + self.embeddings = ( + np.load(dataset.abs_datasets_dir / self.lang_folder / "embeddings.npy", allow_pickle=True).item() + if "lang" in self.modalities + else None + ) + + def on_validation_batch_end( + self, + trainer: Trainer, + pl_module: LightningModule, + outputs: Any, + batch: Any, + batch_idx: int, + dataloader_idx: int, + ) -> None: + batch = batch["vis"] if isinstance(batch, dict) else batch + if pl_module.current_epoch >= self.skip_epochs and (pl_module.current_epoch + 1) % self.rollout_freq == 0: + # in first validation epoch collect groundtruth task information of current validation batch + if self.task_to_id_dict is None: + outputs["task_ids"], outputs["batch_seq_ids"] = self.get_task_info_of_batch(batch) + else: + # do rollout for batch + outputs["rollout_task_counter"] = self.env_rollouts(batch, pl_module) + self.outputs.append(outputs) + + def on_validation_epoch_end(self, trainer: Trainer, pl_module: LightningModule, dataloader_idx: int, *args) -> None: # type: ignore + # TODO: remove lightning fixes callback hook + outputs = [self.outputs] + + if pl_module.current_epoch == 0: + pl_module.log("tasks/average_sr", torch.tensor(0.0), on_step=False, sync_dist=True) + elif pl_module.current_epoch >= self.skip_epochs and (pl_module.current_epoch + 1) % self.rollout_freq == 0: + # after first validation epoch, create task lookup dictionaries + if self.current_epoch == pl_module.current_epoch: + pass + else: + if self.task_to_id_dict is None: + self.build_task_dict(outputs, pl_module) + else: + self.current_epoch = pl_module.current_epoch + if self.video: + # log rollout videos + self.rollout_video.log(pl_module.global_step) + # collect the task rollout counters of all validation batches and sum across tasks + acc_score = torch.tensor(0.0, device=pl_module.device) + for mod in self.modalities: + rollout_task_counter = reduce(add, [x["rollout_task_counter"][mod] for x in outputs[0]]) + if dist.is_available() and dist.is_initialized(): + rollout_task_counter = torch.sum( + pl_module.all_gather(rollout_task_counter), dim=0 + ) # shape: (num_tasks,) + score = ( + torch.sum(rollout_task_counter) / torch.sum(self.groundtruth_task_counter) + if torch.sum(self.groundtruth_task_counter) > 0 + else torch.tensor(0.0) + ) + pl_module.log( + f"tasks/average_sr_{mod}", + score, + on_step=False, + sync_dist=True, + ) + acc_score += score + print() + log_rank_0(f"Evaluating {mod} task success rates:") + for i in range(rollout_task_counter.shape[0]): + if self.groundtruth_task_counter[i] > 0: + # log the ratio of successful task executions per task + # log to tensorboard + pl_module.log( + f"tasks/{self.tasks.id_to_task[i]}_{mod}", + rollout_task_counter[i] / self.groundtruth_task_counter[i], + on_step=False, + sync_dist=True, + ) + # log to cmd line + log_rank_0( + f"{self.tasks.id_to_task[i]}: " + + f"{rollout_task_counter[i] / self.groundtruth_task_counter[i] * 100:.0f}%" + + f" ({rollout_task_counter[i]} / {self.groundtruth_task_counter[i]})" + ) + print() + pl_module.log( + "tasks/average_sr", + acc_score / len(self.modalities), + on_step=False, + sync_dist=True, + ) + self.outputs = [] + + def build_task_dict(self, validation_step_outputs, pl_module): + """ + Called once after the first validation epoch. + It creates: + self.task_to_id_dict: maps from task name to indices of sequences in the validation dataset, in which this + task was solved. To be reused in later validation epochs. + Contains maximum self.num_rollouts_per_task sequence ids + self.id_to_task_dict: reverse map of self.task_to_id_dict + Values are sets since more than one task may be solved in one sequence. + self.groundtruth_task_counter: Tensor of shape (n_tasks,) that counts the number of successful groundtruth + tasks per task. + """ + batch_seq_ids = torch.LongTensor(reduce(add, [x["batch_seq_ids"] for x in validation_step_outputs[0]])).to( + self.device + ) + task_ids = torch.LongTensor(reduce(add, [x["task_ids"] for x in validation_step_outputs[0]])).to(self.device) + + if dist.is_available() and dist.is_initialized(): + # since task may be distributed unevenly across the validation splits on different gpus we have to truncate + # task_ids and batch_seq_ids to the min length before calling self.all_gather + len_b = torch.LongTensor([len(batch_seq_ids)]).to(self.device) + len_t = torch.LongTensor([len(task_ids)]).to(self.device) + len_b = int(torch.min(pl_module.all_gather(len_b))) + len_t = int(torch.min(pl_module.all_gather(len_t))) + batch_seq_ids = batch_seq_ids[:len_b] + task_ids = task_ids[:len_t] + batch_seq_ids = pl_module.all_gather(batch_seq_ids) # shape: (world_size, validation_sequence_ids) + task_ids = pl_module.all_gather(task_ids) + # transpose and flatten is used to later distribute tasks evenly among gpus when using ddp + batch_seq_ids = batch_seq_ids.cpu().numpy().T.flatten() + task_ids = task_ids.cpu().numpy().T.flatten() + self.task_to_id_dict = defaultdict(list) + self.full_task_to_id_dict = defaultdict(list) + unique_task_ids = np.unique(task_ids) + # how many rollouts we want to test per task each validation epoch + n_tasks = self.num_rollouts_per_task + for task_id in unique_task_ids: + all_task_ids = batch_seq_ids[np.where(task_ids == task_id)[0]] + self.task_to_id_dict[self.tasks.id_to_task[task_id]] = self.pick_task_ids(all_task_ids, n_tasks) + self.full_task_to_id_dict[self.tasks.id_to_task[task_id]] = all_task_ids + self.id_to_task_dict = defaultdict(set) + self.groundtruth_task_counter = torch.LongTensor([0] * self.tasks.num_tasks) # .to(self.device) + for k, v in self.task_to_id_dict.items(): + for i in v: + self.id_to_task_dict[i] |= {k} + self.groundtruth_task_counter[self.tasks.task_to_id[k]] = len(v) + + def env_rollouts( + self, + batch: Dict[ + str, + Dict, + ], + pl_module: LightningModule, + ) -> Dict[str, torch.Tensor]: + """ + Args: + batch: tuple( + val_obs: Tensor, + val_rgbs: tuple(Tensor, ), + val_depths: tuple(Tensor, ), + val_acts: Tensor, + val_lang: Tensor, + info: Dict, + idx: int + pl_module: LightningModule + Returns: + rollout_task_counter: tensor counting the number of successful tasks rollouts in this batch + """ + state_obs = batch["robot_obs"] + rgb_obs = batch["rgb_obs"] + depth_obs = batch["depth_obs"] + reset_info = batch["state_info"] + idx = batch["idx"] + # create tensor of zeros to count number of successful tasks in + counter = {} + + for mod in self.modalities: + rollout_task_counter = torch.LongTensor([0] * self.tasks.num_tasks).to(self.device) + for i, global_idx in enumerate(idx): + # check if sequence should be evaluated with rollout + if int(global_idx) in self.id_to_task_dict: + # get set of task(s) that where originally performed. Use set because theoretically + # there can be more than one task solved in one sequence + groundtruth_task = self.id_to_task_dict[int(global_idx)] + # reset env to state of first step in the episode + obs = self.env.reset(reset_info, i, 0) + start_info = self.env.get_info() + + if mod == "lang": + _task = np.random.choice(list(groundtruth_task)) + task_embeddings = self.embeddings[_task]["emb"] + language_instruction = self.embeddings[_task]["ann"][0] + goal = { + "lang": torch.tensor(task_embeddings[np.random.randint(task_embeddings.shape[0])]) + .to(self.device) + .float() + } + else: + # goal image is last step of the episode + goal = { + "rgb_obs": {k: v[i, -1].unsqueeze(0).unsqueeze(0) for k, v in rgb_obs.items()}, # type: ignore + "depth_obs": {k: v[i, -1].unsqueeze(0).unsqueeze(0) for k, v in depth_obs.items()}, # type: ignore + "robot_obs": state_obs[i, -1].unsqueeze(0).unsqueeze(0), + } + + # only save video of first task execution per rollout + record_video = self.video and np.any( + np.asarray([int(global_idx) == self.task_to_id_dict[task][0] for task in groundtruth_task]) + ) + if record_video: + self.rollout_video.new_video(tag=get_video_tag(groundtruth_task, mod)) + pl_module.reset() # type: ignore + success = False + for step in range(self.ep_len): + action = pl_module.step(obs, goal) # type: ignore + obs, _, _, current_info = self.env.step(action) + if record_video: + # update video + self.rollout_video.update(obs["rgb_obs"]["rgb_static"]) + # check if current step solves a task + current_task_info = self.tasks.get_task_info_for_set(start_info, current_info, groundtruth_task) + # check if a task was achieved and if that task is a subset of the original tasks + # we do not just want to solve any task, we want to solve the task that was proposed + if len(current_task_info) > 0: + for task in current_task_info: + task_id = self.tasks.task_to_id[task] + # count successful task rollouts + rollout_task_counter[task_id] += 1 + # skip current sequence if task was achieved + success = True + break + if record_video: + if self.add_goal_thumbnail: + if mod == "lang": + self.rollout_video.add_language_instruction(language_instruction) + else: + self.rollout_video.add_goal_thumbnail(rgb_obs["rgb_static"][i, -1]) + self.rollout_video.draw_outcome(success) + self.rollout_video.write_to_tmp() + + counter[mod] = rollout_task_counter # type: ignore + # return counter of successful tasks for this batch + return counter + + def get_task_info_of_batch( + self, + batch: Dict[ + str, + Any, + ], + ) -> Tuple[List, List]: + """ + Called in the first validation epoch for every batch. This method checks which tasks where successfully + performed in batch by resetting env to first and last state of the sequence. + Args: + batch: tuple( + val_obs: Tensor, + val_rgbs: tuple(Tensor, ), + val_depths: tuple(Tensor, ), + val_acts: Tensor, + val_lang: Tensor, + info: Dict, + idx: int + Returns: + task_ids: list of task ids of successful tasks in this batch + batch_seq_ids: list sequence indices of successful tasks in this batch + """ + task_ids = [] + batch_seq_ids = [] + reset_info = batch["state_info"] + state_obs = batch["robot_obs"] + idx = batch["idx"] + batch_size = state_obs.shape[0] + for i in get_portion_of_batch_ids(self.check_percentage_of_batch, batch_size): + # reset env to state of last step in the episode (goal state) + self.env.reset(reset_info, i, -1) + goal_info = self.env.get_info() + # reset env to state of first step in the episode + self.env.reset(reset_info, i, 0) + start_info = self.env.get_info() + + # check if task was achieved in sequence + task_info = self.tasks.get_task_info(start_info, goal_info) + if len(task_info) != 1: + continue + for task in task_info: + task_ids.append(self.tasks.task_to_id[task]) + batch_seq_ids.append(idx.cpu().numpy()[i]) + return task_ids, batch_seq_ids + + def on_save_checkpoint(self, trainer, pl_module, checkpoint): + checkpoint["task_to_id_dict"] = self.task_to_id_dict + checkpoint["id_to_task_dict"] = self.id_to_task_dict + checkpoint["groundtruth_task_counter"] = self.groundtruth_task_counter + return checkpoint + + def on_load_checkpoint( # type: ignore + self, trainer: Trainer, pl_module: LightningModule, callback_state: Dict[str, Any] + ) -> None: + self.task_to_id_dict = callback_state.get("task_to_id_dict", None) + self.id_to_task_dict = callback_state.get("id_to_task_dict", None) + self.groundtruth_task_counter = callback_state.get("groundtruth_task_counter", None) diff --git a/code/policy_models/rollout/rollout_long_horizon.py b/code/policy_models/rollout/rollout_long_horizon.py new file mode 100644 index 0000000000000000000000000000000000000000..5828d566cb94fbd1caa393ff8623be8328a65e5a --- /dev/null +++ b/code/policy_models/rollout/rollout_long_horizon.py @@ -0,0 +1,264 @@ +from collections import Counter +from itertools import chain +import logging +import multiprocessing +import os +from typing import Any + +import hydra +import numpy as np +from pytorch_lightning import Callback, LightningModule, Trainer +from termcolor import colored +import torch +import torch.distributed as dist +from tqdm import tqdm + +from policy_evaluation import get_sequences +from policy_evaluation import get_env_state_for_initial_condition, join_vis_lang, LangEmbeddings +from policy_models.rollout.rollout_video import RolloutVideo + +log_print = logging.getLogger(__name__) + + +def log_rank_0(*args, **kwargs): + # when using ddp, only log with rank 0 process + if dist.is_available() and dist.is_initialized() and dist.get_rank() != 0: + return + log_print.info(*args, **kwargs) + + +def divide_across_ranks(elements, world_size, rank): + """ + Divide a number across subprocesses in multiprocessing. + Example: distribute 4 elements in a world of size 3 + rank 0->2, rank 1->1, rank 2->1 + """ + assert rank < world_size + rest = lambda n, w, i: 1 if n % w > i else 0 + return elements // world_size + rest(elements, world_size, rank) + + + +def sequences_for_rank(num_sequences): + """ + When using ddp, determine how many sequences every process should evaluate. + """ + rank = dist.get_rank() + ws = dist.get_world_size() + num_seq_per_gpu = divide_across_ranks(num_sequences, ws, rank) + num_workers = multiprocessing.cpu_count() // ws + print(num_workers) + print(num_seq_per_gpu) + print(ws) + print(rank) + sequences = get_sequences(num_sequences, num_workers=num_workers) + # print("Sequences:", sequences) + + print(f"Type of sequences: {type(sequences)}") + print(f"Length of sequences: {len(sequences)}") + print(f"First few elements of sequences: {sequences[:5]}") + + def manual_split(seq, n): + avg = len(seq) // n + remain = len(seq) % n + last = 0 + results = [] + for _ in range(n): + step = avg + (1 if remain > 0 else 0) + results.append(seq[last:last+step]) + last += step + remain -= 1 + return results + + try: + sequences_np = np.array(sequences) + except Exception as e: + print(f"Exception when converting to numpy array: {e}") + + return manual_split(get_sequences(num_sequences, num_workers=num_workers), ws)[rank][:num_seq_per_gpu] + + +def gather_results(local_results): + """ + Collect eval results from all processes. + """ + if not (dist.is_available() and dist.is_initialized()): + return local_results + results = [None for _ in range(torch.distributed.get_world_size())] + torch.distributed.all_gather_object(results, local_results) + return list(chain(*results)) + + +def get_video_tag(i): + if dist.is_available() and dist.is_initialized(): + i = i * dist.get_world_size() + dist.get_rank() + return f"_long_horizon/sequence_{i}" + + +class RolloutLongHorizon(Callback): + """ + A class for performing rollouts during validation step. + """ + + def __init__( + self, + env_cfg, + skip_epochs, + rollout_freq, + num_videos, + num_sequences, + replan_freq, + ep_len, + tasks, + log_video_to_file, + save_dir, + lang_folder, + empty_cache, + val_annotations, + debug, + ): + self.env = None # type: Any + self.env_cfg = env_cfg + self.task_checker = hydra.utils.instantiate(tasks) + self.skip_epochs = skip_epochs + self.rollout_freq = rollout_freq + self.num_videos = num_videos + self.num_sequences = num_sequences + self.replan_freq = replan_freq + self.ep_len = ep_len + self.log_video_to_file = log_video_to_file + self.save_dir = save_dir + self.rollout_video = None # type: Any + self.empty_cache = empty_cache + self.device = None # type: Any + self.lang_embeddings = None + self.lang_folder = lang_folder + self.eval_sequences = None + self.val_annotations = val_annotations + self.debug = debug + + def on_validation_start(self, trainer: Trainer, pl_module: LightningModule, dataloader_idx: int =0) -> None: + """Called when the validation loop begins.""" + if self.env is None: + self.device = pl_module.device + dataset = trainer.val_dataloaders[0].dataset.datasets["lang"] if 'lang' in trainer.val_dataloaders[0].dataset.datasets else trainer.val_dataloaders[0].dataset.datasets['vis'] # type: ignore + + #for callback in trainer.callbacks: + # if isinstance(callback, Rollout) and callback.env is not None: + # self.env = callback.env + # break + #else: + # self.env = hydra.utils.instantiate(self.env_cfg, dataset, pl_module.device) + if self.num_videos > 0: + if dist.is_available() and dist.is_initialized(): + self.num_videos = divide_across_ranks(self.num_videos, dist.get_world_size(), dist.get_rank()) + self.rollout_video = RolloutVideo( + logger=pl_module.logger, + empty_cache=self.empty_cache, + log_to_file=self.log_video_to_file, + save_dir=self.save_dir, + ) + self.lang_embeddings = LangEmbeddings( + dataset.abs_datasets_dir, dataset.lang_folder, device=pl_module.device + ) + if dist.is_available() and dist.is_initialized(): + self.eval_sequences = sequences_for_rank(self.num_sequences) + else: + self.eval_sequences = get_sequences(self.num_sequences) + + def on_validation_epoch_end(self, trainer: Trainer, pl_module: LightningModule, dataloader_idx: int =0, *args) -> None: # type: ignore + if pl_module.current_epoch == 0 and self.skip_epochs > 0: + for i in range(1, 6): + pl_module.log(f"eval_lh/sr_chain_{i}", torch.tensor(0.0), on_step=False, sync_dist=True) + pl_module.log("eval_lh/avg_seq_len", torch.tensor(0.0), on_step=False, sync_dist=True) + elif pl_module.current_epoch == self.skip_epochs or ((pl_module.current_epoch - self.skip_epochs) >= 0 and (pl_module.current_epoch - self.skip_epochs) % self.rollout_freq == 0): + results = self.evaluate_policy(pl_module) + + if self.num_videos > 0: + # log rollout videos + self.rollout_video.log(pl_module.global_step) + + results = gather_results(results) + count = Counter(results) # type: ignore + print() + for i in range(1, 6): + n_success = sum(count[j] for j in reversed(range(i, 6))) + sr = n_success / len(results) + pl_module.log(f"eval_lh/sr_chain_{i}", torch.tensor(sr), on_step=False, sync_dist=True) + log_rank_0(f"{i} / 5 subtasks: {n_success} / {len(results)} sequences, SR: {sr * 100:.1f}%") + avg_seq_len = np.mean(results) + pl_module.log("eval_lh/avg_seq_len", torch.tensor(avg_seq_len), on_epoch=True, sync_dist=True) + log_rank_0(f"Average successful sequence length: {avg_seq_len:.1f}") + print() + + def evaluate_policy(self, model): + results = [] + total_evaluations = len(self.eval_sequences) + + for i, (initial_state, eval_sequence) in enumerate(tqdm(self.eval_sequences, desc="Evaluating Policy", total=total_evaluations)): + record = i < self.num_videos + result = self.evaluate_sequence(model, initial_state, eval_sequence, record, i) + results.append(result) + if record: + self.rollout_video.write_to_tmp() + return results + + def evaluate_sequence(self, model, initial_state, eval_sequence, record, i): + robot_obs, scene_obs = get_env_state_for_initial_condition(initial_state) + self.env.reset(robot_obs=robot_obs, scene_obs=scene_obs) + if record: + caption = " | ".join(eval_sequence) + self.rollout_video.new_video(tag=get_video_tag(i), caption=caption) + success_counter = 0 + if self.debug: + print() + print() + print(f"Evaluating sequence: {' -> '.join(eval_sequence)}") + print("Subtask: ", end="") + for subtask in eval_sequence: + if record: + self.rollout_video.new_subtask() + success = self.rollout(model, subtask, record) + if record: + self.rollout_video.draw_outcome(success) + if success: + success_counter += 1 + else: + return success_counter + return success_counter + + def rollout(self, model, subtask, record): + if self.debug: + print(f"{subtask} ", end="") + obs = self.env.get_obs() + # get lang annotation for subtask + lang_annotation = self.val_annotations[subtask][0] + # get language goal embedding + goal = self.lang_embeddings.get_lang_goal(lang_annotation) + goal['lang_text'] = lang_annotation + model.reset() + start_info = self.env.get_info() + success = False + for step in range(self.ep_len): + action = model.step(obs, goal) + # print(action.shape) + obs, _, _, current_info = self.env.step(action) + if self.debug and os.environ.get("DISPLAY") is not None: + img = self.env.render(mode="rgb_array") + join_vis_lang(img, lang_annotation) + if record: + # update video + self.rollout_video.update(obs["rgb_obs"]["rgb_static"]) + # check if current step solves a task + current_task_info = self.task_checker.get_task_info_for_set(start_info, current_info, {subtask}) + if len(current_task_info) > 0: + success = True + break + if self.debug: + if success: + print(colored("success", "green"), end=" ") + else: + print(colored("fail", "red"), end=" ") + if record: + self.rollout_video.add_language_instruction(lang_annotation) + return success diff --git a/code/policy_models/rollout/rollout_video.py b/code/policy_models/rollout/rollout_video.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3ff177723770e7659c2c1204d4bc3fd7f36f0a --- /dev/null +++ b/code/policy_models/rollout/rollout_video.py @@ -0,0 +1,357 @@ +import logging +import os +from pathlib import Path +from typing import List, Set + +from PIL import Image +import numpy as np +from pytorch_lightning.loggers import TensorBoardLogger, WandbLogger +import torch +import torch.distributed as dist +from torchvision.transforms.functional import resize +import wandb +import wandb.util +from moviepy.editor import ImageSequenceClip + +from policy_models.utils.utils import add_text + +log = logging.getLogger(__name__) + +flatten = lambda t: [item for sublist in t for item in sublist] +flatten_list_of_dicts = lambda t: {k: v for d in t for k, v in d.items()} + + +def _unnormalize(img): + return img / 2 + 0.5 + + +def delete_tmp_video(path): + try: + os.remove(path) + except FileNotFoundError: + pass + + +def add_modality(tasks, mod): + return {f"{mod}/{task}" for task in tasks} + + +class RolloutVideo: + def __init__(self, logger, empty_cache, log_to_file, save_dir, resolution_scale=1): + self.videos = [] + self.video_paths = {} + self.tags = [] + self.captions = [] + self.logger = logger + self.empty_cache = empty_cache + self.log_to_file = log_to_file + self.save_dir = Path(save_dir) + self.sub_task_beginning = 0 + self.step_counter = 0 + self.resolution_scale = resolution_scale + if self.log_to_file: + os.makedirs(self.save_dir, exist_ok=True) + if ( + isinstance(self.logger, TensorBoardLogger) + and dist.is_available() + and dist.is_initialized() + and not self.log_to_file + ): + log.warning("Video logging with tensorboard and ddp can lead to OOM errors.") + + def new_video(self, tag: str, caption: str = None) -> None: + """ + Begin a new video with the first frame of a rollout. + Args: + tag: name of the video + caption: caption of the video + """ + # (1, 1, channels, height, width) + self.videos.append(torch.Tensor()) + self.tags.append(tag) + self.captions.append(caption) + self.step_counter = 0 + self.sub_task_beginning = 0 + + def draw_outcome(self, successful): + """ + Draw red or green border around video depening on successful execution + and repeat last frames. + Args: + successful: bool + """ + c = 1 if successful else 0 + not_c = list({0, 1, 2} - {c}) + border = 3 + frames = 5 + self.videos[-1][:, -1:, c, :, :border] = 1 + self.videos[-1][:, -1:, not_c, :, :border] = 0 + self.videos[-1][:, -1:, c, :, -border:] = 1 + self.videos[-1][:, -1:, not_c, :, -border:] = 0 + self.videos[-1][:, -1:, c, :border, :] = 1 + self.videos[-1][:, -1:, not_c, :border, :] = 0 + self.videos[-1][:, -1:, c, -border:, :] = 1 + self.videos[-1][:, -1:, not_c, -border:, :] = 0 + repeat_frames = torch.repeat_interleave(self.videos[-1][:, -1:], repeats=frames, dim=1) + self.videos[-1] = torch.cat([self.videos[-1], repeat_frames], dim=1) + self.step_counter += frames + + def new_subtask(self): + self.sub_task_beginning = self.step_counter + + def update(self, rgb_obs: torch.Tensor) -> None: + """ + Add new frame to video. + Args: + rgb_obs: static camera RGB images + """ + img = rgb_obs.detach().cpu() + self.videos[-1] = torch.cat([self.videos[-1], _unnormalize(img)], dim=1) # shape 1, t, c, h, w + self.step_counter += 1 + + def add_goal_thumbnail(self, goal_img): + size = self.videos[-1].shape[-2:] + i_h = int(size[0] / 3) + i_w = int(size[1] / 3) + img = resize(_unnormalize(goal_img.detach().cpu()), [i_h, i_w]) + self.videos[-1][:, self.sub_task_beginning :, ..., -i_h:, :i_w] = img + + def add_language_instruction(self, instruction): + img_text = np.zeros(self.videos[-1].shape[2:][::-1], dtype=np.uint8) + 127 + add_text(img_text, instruction) + img_text = ((img_text.transpose(2, 0, 1).astype(float) / 255.0) * 2) - 1 + self.videos[-1][:, self.sub_task_beginning :, ...] += torch.from_numpy(img_text) + self.videos[-1] = torch.clip(self.videos[-1], -1, 1) + + def write_to_tmp(self): + """ + In case of logging with WandB, save the videos as GIF in tmp directory, + then log them at the end of the validation epoch from rank 0 process. + """ + if isinstance(self.logger, WandbLogger) and not self.log_to_file: + for video, tag in zip(self.videos, self.tags): + video = np.clip(video.numpy() * 255, 0, 255).astype(np.uint8) + wandb_vid = wandb.Video(video, fps=10, format="gif") + self.video_paths[tag] = wandb_vid._path + self.videos = [] + self.tags = [] + + @staticmethod + def _empty_cache(): + """ + Clear GPU reserved memory. Do not call this unnecessarily. + """ + mem1 = torch.cuda.memory_reserved(dist.get_rank()) + torch.cuda.empty_cache() + mem2 = torch.cuda.memory_reserved(dist.get_rank()) + log.info(f"GPU: {dist.get_rank()} freed {(mem1 - mem2) / 10**9:.1f}GB of reserved memory") + + def log(self, global_step: int) -> None: + """ + Call this method at the end of a validation epoch to log videos to tensorboard, wandb or filesystem. + Args: + global_step: global step of the training + """ + if self.log_to_file: + self._log_videos_to_file(global_step) + elif isinstance(self.logger, WandbLogger): + self._log_videos_to_wandb() + elif isinstance(self.logger, TensorBoardLogger): + self._log_videos_to_tb(global_step) + else: + raise NotImplementedError + self.videos = [] + self.tags = [] + self.captions = [] + self.video_paths = {} + + def _log_videos_to_tb(self, global_step): + if dist.is_available() and dist.is_initialized(): + if self.empty_cache: + self._empty_cache() + + all_videos = [None for _ in range(torch.distributed.get_world_size())] + all_tags = [None for _ in range(torch.distributed.get_world_size())] + try: + torch.distributed.all_gather_object(all_videos, self.videos) + torch.distributed.all_gather_object(all_tags, self.tags) + except RuntimeError as e: + log.warning(e) + return + # only log videos from rank 0 process + if dist.get_rank() != 0: + return + videos = flatten(all_videos) + tags = flatten(all_tags) + + for video, tag in zip(videos, tags): + self._plot_video_tb(video, tag, global_step) + else: + for video, tag in zip(self.videos, self.tags): + self._plot_video_tb(video, tag, global_step) + + def _plot_video_tb(self, video, tag, global_step): + video = video.unsqueeze(0) + self.logger.experiment.add_video(f"video{tag}", video, global_step=global_step, fps=10) + + def _log_videos_to_wandb(self): + if dist.is_available() and dist.is_initialized(): + all_video_paths = [None for _ in range(torch.distributed.get_world_size())] + all_captions = [None for _ in range(torch.distributed.get_world_size())] + try: + torch.distributed.all_gather_object(all_video_paths, self.video_paths) + torch.distributed.all_gather_object(all_captions, self.captions) + except RuntimeError as e: + log.warning(e) + return + # only log videos from rank 0 process + if dist.get_rank() != 0: + return + video_paths = flatten_list_of_dicts(all_video_paths) + captions = flatten(all_captions) + else: + video_paths = self.video_paths + captions = self.captions + for (task, path), caption in zip(video_paths.items(), captions): + self.logger.experiment.log({f"video{task}": wandb.Video(path, fps=20, format="gif", caption=caption)}) + delete_tmp_video(path) + + def _resize_video(self, video_tensor): + """ + Rescale the video tensor using the provided scale. + """ + t, h, w, c = video_tensor.shape + new_h, new_w = int(h * self.resolution_scale), int(w * self.resolution_scale) + + # Resize each frame using moviepy's ImageClip + resized_video = [ImageSequenceClip([frame], durations=[1]).resize(height=new_h, width=new_w).get_frame(0) for frame in video_tensor] + return np.array(resized_video) + + def _log_videos_to_file(self, global_step, save_as_video=False): + """ + Mostly taken from WandB + """ + for video, tag in zip(self.videos, self.tags): + if len(video.shape) == 4: + video = video.unsqueeze(0) + video = np.clip(video.numpy() * 255, 0, 255).astype(np.uint8) + + mpy = wandb.util.get_module( + "moviepy.editor", + required='wandb.Video requires moviepy and imageio when passing raw data. Install with "pip install moviepy imageio"', + ) + tensor = self._prepare_video(video) + # Resize tensor if resolution scale is not 1.0 + if self.resolution_scale != 1.0: + tensor = self._resize_video(tensor) + _, _height, _width, _channels = tensor.shape + + if save_as_video: + # encode sequence of images into gif string + clip = mpy.ImageSequenceClip(list(tensor), fps=30) + else: + clip = mpy.ImageSequenceClip(list(tensor), fps=20) + + tag = tag.replace("/", "_") + if save_as_video: + filename = str(self.save_dir / f"{tag}_{global_step}.mp4") + else: + filename = self.save_dir / f"{tag}_{global_step}.gif" + if save_as_video: + clip.write_videofile(filename, codec='libx264', bitrate="5000k") # You can adjust the bitrate as needed + else: + clip.write_gif(filename, logger=None) + + def _log_currentvideos_to_file(self, current_step, save_as_video=False): + """ + Mostly taken from WandB + """ + video = self.videos[-1] + tag = self.tags[-1] + + if len(video.shape) == 4: + video = video.unsqueeze(0) + video = np.clip(video.numpy() * 255, 0, 255).astype(np.uint8) + + mpy = wandb.util.get_module( + "moviepy.editor", + required='wandb.Video requires moviepy and imageio when passing raw data. Install with "pip install moviepy imageio"', + ) + tensor = self._prepare_video(video) + # Resize tensor if resolution scale is not 1.0 + if self.resolution_scale != 1.0: + tensor = self._resize_video(tensor) + _, _height, _width, _channels = tensor.shape + + if save_as_video: + # encode sequence of images into gif string + clip = mpy.ImageSequenceClip(list(tensor), fps=30) + else: + clip = mpy.ImageSequenceClip(list(tensor), fps=20) + + tag = tag.replace("/", "_") + if save_as_video: + filename = str(self.save_dir / f"{tag}_{current_step}.mp4") + else: + filename = self.save_dir / f"{tag}_{current_step}.gif" + if save_as_video: + clip.write_videofile(filename, codec='libx264', bitrate="5000k") # You can adjust the bitrate as needed + else: + clip.write_gif(filename, logger=None) + + def save_frames_to_subfolder(self, n, rollout_index): + # Ensure n is a valid number + if n <= 0 or not isinstance(n, int): + raise ValueError("n must be a positive integer.") + + # Create a new subfolder for the rollout + subfolder_path = self.save_dir / f'rollout_{rollout_index}' + os.makedirs(subfolder_path, exist_ok=True) + + # Iterate through all videos in self.videos + for video_idx, video_tensor in enumerate(self.videos): + # Assuming video_tensor shape is (1, t, c, h, w) + _, total_frames, channels, height, width = video_tensor.shape + + # Create a sub-subfolder for each video + video_subfolder_path = subfolder_path / f'video_{video_idx}' + os.makedirs(video_subfolder_path, exist_ok=True) + + # Iterate through the video tensor and save every nth frame to the subfolder + for frame_index in range(0, total_frames, n): + frame = video_tensor[0, frame_index].permute(1, 2, 0).cpu().numpy() + if channels == 1: # If grayscale, remove the color dimension + frame = frame.squeeze(-1) + frame_image = Image.fromarray((frame * 255).astype('uint8')) # Assuming frame values are normalized + frame_image.save(video_subfolder_path / f'frame_{frame_index}.png') + + print(f'Saved frames from {len(self.videos)} videos to {subfolder_path}') + + @staticmethod + def _prepare_video(video): + """This logic was mostly taken from tensorboardX""" + if video.ndim < 4: + raise ValueError("Video must be atleast 4 dimensions: time, channels, height, width") + if video.ndim == 4: + video = video.reshape(1, *video.shape) + b, t, c, h, w = video.shape + + if video.dtype != np.uint8: + logging.warning("Converting video data to uint8") + video = video.astype(np.uint8) + + def is_power2(num): + return num != 0 and ((num & (num - 1)) == 0) + + # pad to nearest power of 2, all at once + if not is_power2(video.shape[0]): + len_addition = int(2 ** video.shape[0].bit_length() - video.shape[0]) + video = np.concatenate((video, np.zeros(shape=(len_addition, t, c, h, w))), axis=0) + + n_rows = 2 ** ((b.bit_length() - 1) // 2) + n_cols = video.shape[0] // n_rows + + video = np.reshape(video, newshape=(n_rows, n_cols, t, c, h, w)) + video = np.transpose(video, axes=(2, 0, 4, 1, 5, 3)) + video = np.reshape(video, newshape=(t, n_rows * h, n_cols * w, c)) + return video diff --git a/code/policy_models/utils/__init__.py b/code/policy_models/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code/policy_models/utils/__pycache__/__init__.cpython-310.pyc b/code/policy_models/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aab4b55d47c8aff11b3c19ca5bc2917d2587c910 Binary files /dev/null and b/code/policy_models/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/utils/__pycache__/__init__.cpython-39.pyc b/code/policy_models/utils/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ecf5ef5d91655271e7c2cc45f7ae05b8795484e Binary files /dev/null and b/code/policy_models/utils/__pycache__/__init__.cpython-39.pyc differ diff --git a/code/policy_models/utils/__pycache__/clip_tokenizer.cpython-310.pyc b/code/policy_models/utils/__pycache__/clip_tokenizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dac58f60bd2b94594805d14e02ba1110913ddbc4 Binary files /dev/null and b/code/policy_models/utils/__pycache__/clip_tokenizer.cpython-310.pyc differ diff --git a/code/policy_models/utils/__pycache__/clip_tokenizer.cpython-39.pyc b/code/policy_models/utils/__pycache__/clip_tokenizer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa31732c09832983723bde1e2ee3706cd46cb165 Binary files /dev/null and b/code/policy_models/utils/__pycache__/clip_tokenizer.cpython-39.pyc differ diff --git a/code/policy_models/utils/__pycache__/transforms.cpython-310.pyc b/code/policy_models/utils/__pycache__/transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e98af53c34849baacfa88ed56829d32fcdb147f2 Binary files /dev/null and b/code/policy_models/utils/__pycache__/transforms.cpython-310.pyc differ diff --git a/code/policy_models/utils/__pycache__/utils.cpython-310.pyc b/code/policy_models/utils/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c201912943b4cb4894161fb21b29a14f281b3530 Binary files /dev/null and b/code/policy_models/utils/__pycache__/utils.cpython-310.pyc differ diff --git a/code/policy_models/utils/automatic_lang_annotator_mp.py b/code/policy_models/utils/automatic_lang_annotator_mp.py new file mode 100644 index 0000000000000000000000000000000000000000..13daa958e51c2865cf7074611b93364031e0605a --- /dev/null +++ b/code/policy_models/utils/automatic_lang_annotator_mp.py @@ -0,0 +1,371 @@ +from collections import Counter +from functools import reduce +import logging +from operator import add +import os +from pathlib import Path +from typing import Any, Optional + +import hydra +import numpy as np +from omegaconf import DictConfig, OmegaConf +from pytorch_lightning import Callback, LightningModule, seed_everything, Trainer +from pytorch_lightning.plugins import DDPPlugin +from pytorch_lightning.utilities import rank_zero_only +import torch +import torch.distributed as dist +from torch.nn import Linear + +import policy_models +from policy_training.training import is_multi_gpu_training, log_rank_0 + +"""This script will collect data snt store it with a fixed window size""" + +logger = logging.getLogger(__name__) + + +def merge_data(list_of_data): + merged_data = { + "language": {"ann": [], "task": [], "emb": []}, + "info": {"episodes": [], "indx": []}, + } + for d in list_of_data: + for k in d: + for k2, v2 in d[k].items(): + if isinstance(v2, list): + merged_data[k][k2] += v2 + elif isinstance(v2, np.ndarray) and len(merged_data[k][k2]) == 0: + merged_data[k][k2] = v2 + elif isinstance(v2, np.ndarray) and len(merged_data[k][k2]) != 0: + merged_data[k][k2] = np.concatenate((merged_data[k][k2], v2), axis=0) + else: + print(type(v2)) + raise ValueError + return merged_data + + +class Annotator(Callback): + def __init__(self, cfg): + self.envs = None # type: Any + self.cfg = cfg + self.device = None + self.lang_folder = cfg.lang_folder + self.tasks = hydra.utils.instantiate(cfg.callbacks.rollout.tasks) + self.demo_task_counter_train = Counter() + self.demo_task_counter_val = Counter() + self.train_dataset = None + self.val_dataset = None + self.file_name = "auto_lang_ann.npy" # + save_format + self.train_lang_folder = None + self.val_lang_folder = None + self.collected_data_train = { + "language": {"ann": [], "task": [], "emb": []}, + "info": {"episodes": [], "indx": []}, + } + self.collected_data_val = { + "language": {"ann": [], "task": [], "emb": []}, + "info": {"episodes": [], "indx": []}, + } + self.lang_model = None + self.num_samples_train = None + self.num_samples_val = None + self.finished_annotation_val = False + self.scene_idx_info = None + + @rank_zero_only + def create_folders(self): + self.train_lang_folder = self.train_dataset.abs_datasets_dir / self.lang_folder + self.train_lang_folder.mkdir(parents=True, exist_ok=True) + + self.val_lang_folder = self.val_dataset.abs_datasets_dir / self.lang_folder + self.val_lang_folder.mkdir(parents=True, exist_ok=True) + + @rank_zero_only + def compute_val_embeddings(self): + val_sent = OmegaConf.load(Path(policy_models.__file__).parent / f"../conf/annotations/{self.cfg.rollout_sentences}.yaml") + embeddings = {} + for task, ann in val_sent.items(): + embeddings[task] = {} + language_embedding = self.lang_model(list(ann)) + embeddings[task]["emb"] = language_embedding.cpu().numpy() + embeddings[task]["ann"] = ann + np.save(self.val_lang_folder / "embeddings", embeddings) + logger.info("Done saving val language embeddings for Rollouts !") + + def init_vars(self, trainer, pl_module): + self.device = pl_module.device + self.val_dataset = trainer.val_dataloaders[0].dataset.datasets["vis"] # type: ignore + self.train_dataset = trainer.train_dataloader.dataset.datasets["vis"] + self.scene_idx_info = np.load(self.train_dataset.abs_datasets_dir / "scene_info.npy", allow_pickle=True).item() + + self.envs = { + scene: hydra.utils.instantiate( + self.cfg.callbacks.rollout.env_cfg, self.val_dataset, pl_module.device, scene=scene, cameras=() + ) + for scene, _ in self.scene_idx_info.items() + } + if self.cfg.validation_scene not in self.envs: + self.envs[self.cfg.validation_scene] = hydra.utils.instantiate( + self.cfg.callbacks.rollout.env_cfg, + self.val_dataset, + pl_module.device, + scene=self.cfg.validation_scene, + cameras=(), + ) + + self.create_folders() + self.lang_model = hydra.utils.instantiate(self.cfg.model) + self.compute_val_embeddings() + self.num_samples_train = int(self.cfg.eps * len(self.train_dataset) / len(self.cfg.annotations.keys())) + self.num_samples_val = int(self.cfg.eps * len(self.val_dataset) / len(self.cfg.annotations.keys())) + + def on_validation_start(self, trainer: Trainer, pl_module: LightningModule, dataloader_idx: int) -> None: + """Called when the validation loop begins.""" + if self.envs is None: + self.init_vars(trainer, pl_module) + + def on_train_start(self, trainer: Trainer, pl_module: LightningModule) -> None: + if self.envs is None: + self.init_vars(trainer, pl_module) + + def on_validation_batch_end( + self, + trainer: Trainer, + pl_module: LightningModule, + outputs: Any, + batch: Any, + batch_idx: int, + dataloader_idx: int, + ) -> None: + batch = batch["vis"] if isinstance(batch, dict) else batch + self.collected_data_val, self.demo_task_counter_val, current_task_counter = self.annotate( + batch, + self.val_dataset, + self.collected_data_val, + self.demo_task_counter_val, + self.num_samples_val, + ) + if dist.is_available() and dist.is_initialized(): + global_counters = [None for _ in range(torch.distributed.get_world_size())] + torch.distributed.all_gather_object(global_counters, current_task_counter) + current_task_counter = reduce(add, global_counters) + self.demo_task_counter_val += current_task_counter + if self.check_done( + self.demo_task_counter_val, self.num_samples_val, batch_idx, trainer.num_val_batches[0], "val" + ): + print() + print() + print() + logger.info("Finished annotating val dataset") + print() + print() + print() + self.finished_annotation_val = True + + def on_train_batch_end( + self, + trainer: Trainer, + pl_module: LightningModule, + outputs: Any, + batch: Any, + batch_idx: int, + dataloader_idx: int, + unused: Optional[int] = 0, + ) -> None: + batch = batch["vis"] if isinstance(batch, dict) else batch + + self.collected_data_train, self.demo_task_counter_train, current_task_counter = self.annotate( + batch, self.train_dataset, self.collected_data_train, self.demo_task_counter_train, self.num_samples_train + ) + if dist.is_available() and dist.is_initialized(): + global_counters = [None for _ in range(torch.distributed.get_world_size())] + torch.distributed.all_gather_object(global_counters, current_task_counter) + current_task_counter = reduce(add, global_counters) + self.demo_task_counter_train += current_task_counter + if self.check_done( + self.demo_task_counter_train, self.num_samples_train, batch_idx, trainer.num_training_batches, "train" + ): + print() + print() + print() + log_rank_0("Finished annotating train dataset") + print() + print() + print() + pl_module.finished_annotation_train = True # type: ignore + + def on_train_epoch_end(self, trainer: Trainer, pl_module: LightningModule, unused: Optional[int] = None) -> None: + self.save_and_postprocess(self.collected_data_train, self.train_lang_folder, "train", len(self.train_dataset)) + + def on_validation_epoch_end(self, trainer: Trainer, pl_module: LightningModule, dataloader_idx: int) -> None: + self.save_and_postprocess(self.collected_data_val, self.val_lang_folder, "val", len(self.val_dataset)) + + def save_and_postprocess(self, collected_data, lang_folder, mod, length): + if dist.is_available() and dist.is_initialized(): + global_collected_data = [None for _ in range(dist.get_world_size())] + torch.distributed.all_gather_object(global_collected_data, collected_data) + if dist.get_rank() == 0: + global_collected_data = merge_data(global_collected_data) + np.save("lang_ann", global_collected_data) + else: + np.save("lang_ann", collected_data) + if self.cfg.postprocessing: + language = collected_data["language"]["ann"] + language_embedding = self.lang_model(language) + collected_data["language"]["emb"] = language_embedding.cpu().numpy() + logger.info(f"Done extracting {mod} language embeddings !") + + if dist.is_available() and dist.is_initialized(): + global_collected_data = [None for _ in range(dist.get_world_size())] + torch.distributed.all_gather_object(global_collected_data, collected_data) + if dist.get_rank() != 0: + return + collected_data = merge_data(global_collected_data) + + np.save(self.file_name, collected_data) + np.save(lang_folder / self.file_name, collected_data) + logger.info(f"Done saving {mod} language annotations !") + + lang_length = float(len(collected_data["language"]["ann"])) + logger.info( + f"\nVision Dataset contains {length} datapoints " + f"\nLanguage Dataset contains {lang_length} datapoints " + f"\n VISION --> {100.0 * length / (length + lang_length):.3f} %" + f"\n LANGUAGE --> {100.0 * lang_length / (length + lang_length):.3f} %" + ) + + def check_done(self, counter, num_samples, batch_idx, num_batches, mode): + if batch_idx % 10 == 0: + log_rank_0(f"{mode} Tasks Objective: {num_samples}") + log_rank_0(f"Tasks Lang: {self.cfg.annotations.keys()}") + log_rank_0(f"Tasks Annotations Progress: {counter}") + log_rank_0( + "Progress [ " + + "=" * int(0.5 * 100 * batch_idx / num_batches) + + ">" + + "-" * int(0.5 * 100 * (num_batches - batch_idx) / num_batches) + + str(round(100 * batch_idx / num_batches)) + + "%" + + "]" + ) + return len(counter.values()) >= len(self.cfg.annotations) and min(counter.values()) >= num_samples + + def select_env(self, dataset, idx): + if "validation" in dataset.abs_datasets_dir.as_posix(): + return self.envs[self.cfg.validation_scene] + seq_idx = dataset.episode_lookup[idx] + for scene, interval in self.scene_idx_info.items(): + if interval[0] <= seq_idx <= interval[1]: + return self.envs[scene] + raise ValueError + + def annotate(self, episode, dataset, collected_data, global_task_counter, num_samples): + state_obs, rgb_obs, depth_obs, actions, _, reset_info, idx = episode + batch_size, seq_length = state_obs.shape[0], state_obs.shape[1] + current_task_counter = Counter() + for i in range(batch_size): + env = self.select_env(dataset, idx[i]) + # reset env to state of last step in the episode (goal state) + env.reset(reset_info, i, -1) + goal_info = env.get_info() + + prior_steps = np.random.randint(16, 32) + env.reset(reset_info, i, prior_steps) + middle_info = env.get_info() + + env.reset(reset_info, i, seq_length - 16) + close_to_end_info = env.get_info() + + # check if task was achieved in sequence + task_info = self.tasks.get_task_info(middle_info, goal_info) + if ( + len(task_info) != 1 + or not task_info <= self.cfg.annotations.keys() + or len(self.tasks.get_task_info_for_set(middle_info, close_to_end_info, task_info)) + ): + continue + task = list(task_info)[0] + if global_task_counter[task] + current_task_counter[task] >= num_samples: + continue + # reset self.env to state of first step in the episode + env.reset(reset_info, i, 0) + start_info = env.get_info() + + env.reset(reset_info, i, 32) + middle_info2 = env.get_info() + + if len(self.tasks.get_task_info_for_set(start_info, goal_info, task_info)) and not len( + self.tasks.get_task_info(start_info, middle_info2) + ): + start_idx = idx[i] + window_size = seq_length + else: + start_idx = idx[i] + prior_steps + window_size = seq_length - prior_steps + + # seq_length = torch.unique(actions[i], dim=0).shape[0] + current_task_counter += Counter(task_info) + collected_data = self.label_seq(collected_data, dataset, window_size, start_idx, task) + return collected_data, global_task_counter, current_task_counter + + def label_seq(self, collected_data, dataset, seq_length, idx, task): + seq_idx = dataset.episode_lookup[idx] + collected_data["info"]["indx"].append((seq_idx, seq_idx + seq_length)) + task_lang = self.cfg.annotations[task] + lang_ann = task_lang[np.random.randint(len(task_lang))] + collected_data["language"]["ann"].append(lang_ann) + collected_data["language"]["task"].append(task) + return collected_data + + +class LangAnnotationModel(LightningModule): + def __init__(self): + super().__init__() + self.finished_annotation_train = False + self.dummy_net = Linear(1, 1) + + def on_train_batch_start(self, batch: Any, batch_idx: int, unused: Optional[int] = 0) -> None: + if self.finished_annotation_train: + return -1 # type: ignore + + def training_step(self, batch, batch_idx): + return self.dummy_net(torch.Tensor([0.0]).to(self.device)) + + def validation_step(self, *args, **kwargs): + pass + + def configure_optimizers(self): + return torch.optim.Adam(self.parameters(), lr=0.02) + + +@hydra.main(config_path="../../conf", config_name="lang_ann.yaml") +def main(cfg: DictConfig) -> None: + os.environ["TOKENIZERS_PARALLELISM"] = "true" + # sets seeds for numpy, torch, python.random and PYTHONHASHSEED. + seed_everything(cfg.seed) + datamodule = hydra.utils.instantiate(cfg.datamodule) + callbacks = Annotator(cfg) + + dummy_model = LangAnnotationModel() + + trainer_args = { + **cfg.trainer, + "callbacks": callbacks, + "num_sanity_val_steps": 0, + "max_epochs": 1, + "progress_bar_refresh_rate": 0, + "weights_summary": None, + } + # Configure multi-GPU training + if is_multi_gpu_training(trainer_args["gpus"]): # type: ignore + trainer_args["accelerator"] = "ddp" + trainer_args["plugins"] = DDPPlugin(find_unused_parameters=False) + + trainer = Trainer(**trainer_args) + + trainer.fit(dummy_model, datamodule=datamodule) + trainer.validate(dummy_model, datamodule=datamodule) # type: ignore + + +if __name__ == "__main__": + main() diff --git a/code/policy_models/utils/bpe_simple_vocab_16e6.txt.gz b/code/policy_models/utils/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/code/policy_models/utils/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/code/policy_models/utils/clip_tokenizer.py b/code/policy_models/utils/clip_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f884c9a804b09f8f9ad148a8164b3e81588bad --- /dev/null +++ b/code/policy_models/utils/clip_tokenizer.py @@ -0,0 +1,136 @@ +from functools import lru_cache +import gzip +import html +import os + +import ftfy +import regex as re + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) + cs = bs[:] + n = 0 + for b in range(2 ** 8): + if b not in bs: + bs.append(b) + cs.append(2 ** 8 + n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r"\s+", " ", text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe()): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split("\n") + merges = merges[1 : 49152 - 256 - 2 + 1] + merges = [tuple(merge.split()) for merge in merges] # type:ignore + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v + "" for v in vocab] + for merge in merges: + vocab.append("".join(merge)) + vocab.extend(["<|startoftext|>", "<|endoftext|>"]) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {"<|startoftext|>": "<|startoftext|>", "<|endoftext|>": "<|endoftext|>"} + self.pat = re.compile( + r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", + re.IGNORECASE, + ) + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + (token[-1] + "",) + pairs = get_pairs(word) + + if not pairs: + return token + "" + + while True: + bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except Exception as ex: + new_word.extend(word[i:]) + # print(ex.message, ex.args) + break + + if word[i] == first and i < len(word) - 1 and word[i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = " ".join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = "".join(self.byte_encoder[b] for b in token.encode("utf-8")) + bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")) + return bpe_tokens + + def decode(self, tokens): + text = "".join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="replace").replace("", " ") + return text diff --git a/code/policy_models/utils/language_annotator.py b/code/policy_models/utils/language_annotator.py new file mode 100644 index 0000000000000000000000000000000000000000..fc00c3b748f58738379b98d3f3c9d26fa7fc75d9 --- /dev/null +++ b/code/policy_models/utils/language_annotator.py @@ -0,0 +1,86 @@ +import logging +import os.path + +import hydra +from matplotlib.animation import ArtistAnimation +import matplotlib.pyplot as plt +import numpy as np +from omegaconf import DictConfig + +"""This script will collect data snt store it with a fixed window size""" + +logger = logging.getLogger(__name__) + + +@hydra.main(config_path="../../conf", config_name="lang_ann.yaml") +def main(cfg: DictConfig) -> None: + # sets seeds for numpy, torch, python.random and PYTHONHASHSEED. + data_module = hydra.utils.instantiate(cfg.datamodule) + bert = hydra.utils.instantiate(cfg.model) + data_module.setup() + if cfg.training: + dataset = data_module.train_datasets + else: + dataset = data_module.val_datasets # Tupla(obs [32,9], img tuple([32, 3, 300, 300]), tuple(), act [32,9]) + + # To make sure that we dont overwrite previous annotations and always keep adding + file_name = os.path.join(dataset.dataset_loader.abs_datasets_dir, "lang_ann.npy") + if os.path.isfile(file_name): + collected_data = np.load(file_name, allow_pickle=True).reshape(-1)[0] + # start = collected_data['indx'][-1][0] + collected_data['indx'][-1][1] + start = len(collected_data["indx"]) + logger.info("Join the language annotation number {}".format(len(collected_data["indx"]))) + else: + collected_data = {"language": [], "indx": []} + start = 0 + + length = len(dataset) + print(length, len(dataset.dataset_loader.episode_lookup)) + steps = int((length - start) // (length * 0.01)) + total = int(1 // 0.01) + logger.info("Progress --> {} / {}".format(total - steps, total)) + for i in range(start, length, steps): + imgs = [] + seq_img = dataset[i][1][0].numpy() + s, c, h, w = seq_img.shape + seq_img = np.transpose(seq_img, (0, 2, 3, 1)) + print("Seq length: {}".format(s)) + print("From: {} To: {}".format(i, i + s)) + fig = plt.figure() + for j in range(s): + imgRGB = seq_img[j].astype(int) + img = plt.imshow(imgRGB, animated=True) + imgs.append([img]) + ArtistAnimation(fig, imgs, interval=50) + plt.show(block=False) + lang_ann = [input("Which instructions would you give to the robot to do: (press q to quit)\n")] + plt.close() + + if lang_ann[0] == "q": + break + logger.info( + " Added indexes: {}".format( + ( + dataset.dataset_loader.episode_lookup[i], + dataset.dataset_loader.episode_lookup[i] + dataset.window_size, + ) + ) + ) + collected_data["language"].append(lang_ann) + collected_data["indx"].append( + (dataset.dataset_loader.episode_lookup[i], dataset.dataset_loader.episode_lookup[i] + dataset.window_size) + ) + file_name = "lang_ann" + np.save(file_name, collected_data) + + if cfg.postprocessing: + language = [item for sublist in collected_data["language"] for item in sublist] + language_embedding = bert(language) + collected_data["language"] = language_embedding.unsqueeze(1) + file_name = "lang_emb_ann" + np.save(file_name, collected_data) + logger.info("Done extracting language embeddings !") + + +if __name__ == "__main__": + main() diff --git a/code/policy_models/utils/lr_schedulers/__init__.py b/code/policy_models/utils/lr_schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..33acd4e4f51542dd6f4205e14caf5742530e2952 --- /dev/null +++ b/code/policy_models/utils/lr_schedulers/__init__.py @@ -0,0 +1,103 @@ +# MIT License +# +# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from dataclasses import _MISSING_TYPE, dataclass, field +from typing import Any, List, Optional + +SCHEDULER_REGISTRY = {} +SCHEDULER_DATACLASS_REGISTRY = {} + + +def register_scheduler(name: str, dataclass=None): + """ + New scheduler types can be added to OpenSpeech with the :func:`register_scheduler` function decorator. + + For example:: + @register_scheduler('reduce_lr_on_plateau') + class ReduceLROnPlateau: + (...) + + .. note:: All scheduler must implement the :class:`cls.__name__` interface. + + Args: + name (str): the name of the scheduler + """ + + def register_scheduler_cls(cls): + if name in SCHEDULER_REGISTRY: + raise ValueError(f"Cannot register duplicate scheduler ({name})") + + SCHEDULER_REGISTRY[name] = cls + + cls.__dataclass = dataclass + if dataclass is not None: + if name in SCHEDULER_DATACLASS_REGISTRY: + raise ValueError(f"Cannot register duplicate scheduler ({name})") + SCHEDULER_DATACLASS_REGISTRY[name] = dataclass + + return cls + + return register_scheduler_cls + + + +@dataclass +class OpenspeechDataclass: + """OpenSpeech base dataclass that supported fetching attributes and metas""" + + def _get_all_attributes(self) -> List[str]: + return [k for k in self.__dataclass_fields__.keys()] + + def _get_meta(self, attribute_name: str, meta: str, default: Optional[Any] = None) -> Any: + return self.__dataclass_fields__[attribute_name].metadata.get(meta, default) + + def _get_name(self, attribute_name: str) -> str: + return self.__dataclass_fields__[attribute_name].name + + def _get_default(self, attribute_name: str) -> Any: + if hasattr(self, attribute_name): + if str(getattr(self, attribute_name)).startswith("${"): + return str(getattr(self, attribute_name)) + elif str(self.__dataclass_fields__[attribute_name].default).startswith("${"): + return str(self.__dataclass_fields__[attribute_name].default) + elif getattr(self, attribute_name) != self.__dataclass_fields__[attribute_name].default: + return getattr(self, attribute_name) + + f = self.__dataclass_fields__[attribute_name] + if not isinstance(f.default_factory, _MISSING_TYPE): + return f.default_factory() + return f.default + + def _get_type(self, attribute_name: str) -> Any: + return self.__dataclass_fields__[attribute_name].type + + def _get_help(self, attribute_name: str) -> Any: + return self._get_meta(attribute_name, "help") + + + +@dataclass +class LearningRateSchedulerConfigs(OpenspeechDataclass): + """Super class of learning rate dataclass""" + + lr: float = field(default=1e-04, metadata={"help": "Learning rate"}) + \ No newline at end of file diff --git a/code/policy_models/utils/lr_schedulers/__pycache__/__init__.cpython-310.pyc b/code/policy_models/utils/lr_schedulers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a730fb7ef7669a83903e0e19bebc43bfb0343f18 Binary files /dev/null and b/code/policy_models/utils/lr_schedulers/__pycache__/__init__.cpython-310.pyc differ diff --git a/code/policy_models/utils/lr_schedulers/__pycache__/__init__.cpython-39.pyc b/code/policy_models/utils/lr_schedulers/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78e096ab376830613f15051674aca8b0a0661cff Binary files /dev/null and b/code/policy_models/utils/lr_schedulers/__pycache__/__init__.cpython-39.pyc differ diff --git a/code/policy_models/utils/lr_schedulers/__pycache__/lr_scheduler.cpython-310.pyc b/code/policy_models/utils/lr_schedulers/__pycache__/lr_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eca8ef2555439a40087eae07ace34bc16ef05fb Binary files /dev/null and b/code/policy_models/utils/lr_schedulers/__pycache__/lr_scheduler.cpython-310.pyc differ diff --git a/code/policy_models/utils/lr_schedulers/__pycache__/lr_scheduler.cpython-39.pyc b/code/policy_models/utils/lr_schedulers/__pycache__/lr_scheduler.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17edccf327e20d5771b28a9d95eb1d553a48e9cb Binary files /dev/null and b/code/policy_models/utils/lr_schedulers/__pycache__/lr_scheduler.cpython-39.pyc differ diff --git a/code/policy_models/utils/lr_schedulers/__pycache__/tri_stage_scheduler.cpython-310.pyc b/code/policy_models/utils/lr_schedulers/__pycache__/tri_stage_scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d9ed073ab9b926d89e8da0b75f33542fa730486 Binary files /dev/null and b/code/policy_models/utils/lr_schedulers/__pycache__/tri_stage_scheduler.cpython-310.pyc differ diff --git a/code/policy_models/utils/lr_schedulers/__pycache__/tri_stage_scheduler.cpython-39.pyc b/code/policy_models/utils/lr_schedulers/__pycache__/tri_stage_scheduler.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bd5a098c21c3f2574f7ec644e65309ab65e4a5f Binary files /dev/null and b/code/policy_models/utils/lr_schedulers/__pycache__/tri_stage_scheduler.cpython-39.pyc differ diff --git a/code/policy_models/utils/lr_schedulers/lr_scheduler.py b/code/policy_models/utils/lr_schedulers/lr_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..991e4f219825ce6809061907e4b7189d03e2b6b2 --- /dev/null +++ b/code/policy_models/utils/lr_schedulers/lr_scheduler.py @@ -0,0 +1,48 @@ +# MIT License +# +# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from torch.optim.lr_scheduler import _LRScheduler + + +class LearningRateScheduler(_LRScheduler): + r""" + Provides inteface of learning rate scheduler. + + Note: + Do not use this class directly, use one of the sub classes. + """ + + def __init__(self, optimizer, init_lr): + self.optimizer = optimizer + self.init_lr = init_lr + + def step(self, *args, **kwargs): + raise NotImplementedError + + @staticmethod + def set_lr(optimizer, lr): + for g in optimizer.param_groups: + g["lr"] = lr + + def get_lr(self): + for g in self.optimizer.param_groups: + return g["lr"] \ No newline at end of file diff --git a/code/policy_models/utils/lr_schedulers/tri_stage_scheduler.py b/code/policy_models/utils/lr_schedulers/tri_stage_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a12a6e00d0dab3ae2d926626da108fdd1d6626 --- /dev/null +++ b/code/policy_models/utils/lr_schedulers/tri_stage_scheduler.py @@ -0,0 +1,148 @@ +# MIT License +# +# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import math +from dataclasses import dataclass, field +from typing import Optional + +import torch +from omegaconf import DictConfig +from torch.optim import Optimizer + +from . import register_scheduler, LearningRateSchedulerConfigs +from .lr_scheduler import LearningRateScheduler + + +@dataclass +class TriStageLRSchedulerConfigs(LearningRateSchedulerConfigs): + scheduler_name: str = field(default="tri_stage", metadata={"help": "Name of learning rate scheduler."}) + init_lr: float = field(default=1e-7, metadata={"help": "Initial learning rate."}) + init_lr_scale: float = field(default=0.01, metadata={"help": "Initial learning rate scale."}) + final_lr_scale: float = field(default=0.01, metadata={"help": "Final learning rate scale"}) + phase_ratio: str = field( + default="(0.1, 0.4, 0.5)", + metadata={ + "help": "Automatically sets warmup/hold/decay steps to the ratio " + "specified here from max_updates. the ratios must add up to 1.0" + }, + ) + total_steps: int = field(default=400000, metadata={"help": "Total training steps."}) + + +@register_scheduler("tri_stage", dataclass=TriStageLRSchedulerConfigs) +class TriStageLRScheduler(LearningRateScheduler): + r""" + Tri-Stage Learning Rate Scheduler. Implement the learning rate scheduler in "SpecAugment" + + Similar to inverse_squre_root scheduler, but tri_stage learning rate employs + three stages LR scheduling: + + - warmup stage, starting from `lr` * `init_lr_scale`, linearly + increased to `lr` in `warmup_steps` iterations + - hold stage, after `warmup_steps`, keep the LR as `lr` for `hold_steps` + iterations + - decay stage, after hold stage, decay LR exponetially to + `lr` * `final_lr_scale` in `decay_steps`; + after that LR is keep as `final_lr_scale` * `lr` + + During warmup:: + init_lr = cfg.init_lr_scale * cfg.lr + lrs = torch.linspace(init_lr, cfg.lr, cfg.warmup_steps) + lr = lrs[update_num] + + During hold:: + lr = cfg.lr + + During decay:: + decay_factor = - math.log(cfg.final_lr_scale) / cfg.decay_steps + lr = cfg.lr * exp(- (update_num - warmup_steps - decay_steps) * decay_factor) + + Updated it to be CosineAnneaLLR Scheduler + + After that:: + lr = cfg.lr * cfg.final_lr_scale + + Args: + optimizer (Optimizer): wrapped optimizer. + configs (DictConfig): configuration set. + """ + + def __init__( + self, + optimizer: Optimizer, + configs: DictConfig, + ): + super(TriStageLRScheduler, self).__init__(optimizer, configs.lr_scheduler.init_lr) + + self.phase_ratio = eval(configs.lr_scheduler.phase_ratio) + + self.warmup_steps = int(configs.lr_scheduler.total_steps * self.phase_ratio[0]) + self.hold_steps = int(configs.lr_scheduler.total_steps * self.phase_ratio[1]) + self.decay_steps = int(configs.lr_scheduler.total_steps * self.phase_ratio[2]) + + self.peak_lr = configs.lr_scheduler.lr + self.init_lr = configs.lr_scheduler.init_lr_scale * configs.lr_scheduler.lr + self.final_lr = configs.lr_scheduler.final_lr_scale * configs.lr_scheduler.lr + + self.warmup_rate = (self.peak_lr - self.init_lr) / self.warmup_steps if self.warmup_steps != 0 else 0 + self.decay_factor = -math.log(configs.lr_scheduler.final_lr_scale) / self.decay_steps + self.update_step = 0 + self.lr = self.init_lr + + def _decide_stage(self): + if self.update_step < self.warmup_steps: + return 0, self.update_step + + offset = self.warmup_steps + + if self.update_step < offset + self.hold_steps: + return 1, self.update_step - offset + + offset += self.hold_steps + + if self.update_step <= offset + self.decay_steps: + # decay stage + return 2, self.update_step - offset + + offset += self.decay_steps + + return 3, self.update_step - offset + + def step(self, val_loss: Optional[torch.FloatTensor] = None): + stage, steps_in_stage = self._decide_stage() + + if stage == 0: + self.lr = self.init_lr + self.warmup_rate * steps_in_stage + elif stage == 1: + self.lr = self.peak_lr + elif stage == 2: + # self.lr = self.peak_lr * math.exp(-self.decay_factor * steps_in_stage) + self.lr = self.final_lr + 0.5 * (self.peak_lr - self.final_lr) * (1 + math.cos(steps_in_stage / self.decay_steps * math.pi)) + elif stage == 3: + self.lr = self.final_lr + else: + raise ValueError("Undefined stage") + + self.set_lr(self.optimizer, self.lr) + self.update_step += 1 + + return self.lr \ No newline at end of file diff --git a/code/policy_models/utils/lr_schedulers/warmup_lr_scheduler.py b/code/policy_models/utils/lr_schedulers/warmup_lr_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..47ef824ec3b5e24f8c9b79fdcc1c471ceabd8d04 --- /dev/null +++ b/code/policy_models/utils/lr_schedulers/warmup_lr_scheduler.py @@ -0,0 +1,76 @@ +# MIT License +# +# Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from dataclasses import dataclass, field +from typing import Optional + +import torch +from omegaconf import DictConfig +from torch.optim import Optimizer + +from tacorl.utils.lr_schedulers import register_scheduler, LearningRateSchedulerConfigs +from tacorl.utils.lr_schedulers.lr_scheduler import LearningRateScheduler + + +@dataclass +class WarmupLRSchedulerConfigs(LearningRateSchedulerConfigs): + scheduler_name: str = field(default="warmup", metadata={"help": "Name of learning rate scheduler."}) + peak_lr: float = field(default=1e-04, metadata={"help": "Maximum learning rate."}) + init_lr: float = field(default=1e-7, metadata={"help": "Initial learning rate."}) + warmup_steps: int = field( + default=4000, metadata={"help": "Warmup the learning rate linearly for the first N updates"} + ) + total_steps: int = field(default=200000, metadata={"help": "Total training steps."}) + + +@register_scheduler("warmup", dataclass=WarmupLRSchedulerConfigs) +class WarmupLRScheduler(LearningRateScheduler): + """ + Warmup learning rate until `total_steps` + + Args: + optimizer (Optimizer): wrapped optimizer. + configs (DictConfig): configuration set. + """ + + def __init__( + self, + optimizer: Optimizer, + configs: DictConfig, + ) -> None: + super(WarmupLRScheduler, self).__init__(optimizer, configs.lr_scheduler.init_lr) + if configs.lr_scheduler.warmup_steps != 0: + warmup_rate = configs.lr_scheduler.peak_lr - configs.lr_scheduler.init_lr + self.warmup_rate = warmup_rate / configs.lr_scheduler.warmup_steps + else: + self.warmup_rate = 0 + self.update_steps = 1 + self.lr = configs.lr_scheduler.init_lr + self.warmup_steps = configs.lr_scheduler.warmup_steps + + def step(self, val_loss: Optional[torch.FloatTensor] = None): + if self.update_steps < self.warmup_steps: + lr = self.init_lr + self.warmup_rate * self.update_steps + self.set_lr(self.optimizer, lr) + self.lr = lr + self.update_steps += 1 + return self.lr \ No newline at end of file diff --git a/code/policy_models/utils/transforms.py b/code/policy_models/utils/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..654fc06f665916df01f765396f5afcdd55020d7b --- /dev/null +++ b/code/policy_models/utils/transforms.py @@ -0,0 +1,124 @@ +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ScaleImageTensor(object): + """Scale tensor of shape (batch, C, H, W) containing images to [0, 1] range + + Args: + tensor (torch.tensor): Tensor to be scaled. + Returns: + Tensor: Scaled tensor. + """ + + def __call__(self, tensor: torch.Tensor) -> torch.Tensor: + assert isinstance(tensor, torch.Tensor) + return tensor.float().div(255) + + +class NormalizeVector(object): + """Normalize a tensor vector with mean and standard deviation.""" + + def __init__(self, mean=[0.0], std=[1.0]): + self.std = torch.Tensor(std) + self.std[self.std == 0.0] = 1.0 + self.mean = torch.Tensor(mean) + + def __call__(self, tensor: torch.Tensor) -> torch.Tensor: + assert isinstance(tensor, torch.Tensor) + return (tensor - self.mean) / self.std + + def __repr__(self): + return self.__class__.__name__ + "(mean={0}, std={1})".format(self.mean, self.std) + + +class AddGaussianNoise(object): + def __init__(self, mean=0.0, std=1.0): + self.std = torch.tensor(std) + self.mean = torch.tensor(mean) + + def __call__(self, tensor: torch.Tensor) -> torch.Tensor: + assert isinstance(tensor, torch.Tensor) + return tensor + torch.randn(tensor.size()) * self.std + self.mean + + def __repr__(self): + return self.__class__.__name__ + "(mean={0}, std={1})".format(self.mean, self.std) + + +class AddDepthNoise(object): + """Add multiplicative gamma noise to depth image. + This is adapted from the DexNet 2.0 code. + Their code: https://github.com/BerkeleyAutomation/gqcnn/blob/master/gqcnn/training/tf/trainer_tf.py""" + + def __init__(self, shape=1000.0, rate=1000.0): + self.shape = torch.tensor(shape) + self.rate = torch.tensor(rate) + self.dist = torch.distributions.gamma.Gamma(torch.tensor(shape), torch.tensor(rate)) + + def __call__(self, tensor: torch.Tensor) -> torch.Tensor: + assert isinstance(tensor, torch.Tensor) + multiplicative_noise = self.dist.sample() + return multiplicative_noise * tensor + + def __repr__(self): + # return self.__class__.__name__ + f"{self.shape=},{self.rate=},{self.dist=}" + return self.__class__.__name__ + f"(shape={self.shape}, rate={self.rate}, dist={self.dist})" + + + + +# source: https://github.com/facebookresearch/drqv2/blob/main/drqv2.py +class RandomShiftsAug(nn.Module): + def __init__(self, pad): + super().__init__() + self.pad = pad + + def forward(self, x): + x = x.float() + n, c, h, w = x.size() + assert h == w + padding = tuple([self.pad] * 4) + x = F.pad(x, padding, "replicate") + eps = 1.0 / (h + 2 * self.pad) + arange = torch.linspace(-1.0 + eps, 1.0 - eps, h + 2 * self.pad, device=x.device, dtype=x.dtype)[:h] + arange = arange.unsqueeze(0).repeat(h, 1).unsqueeze(2) + base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2) + base_grid = base_grid.unsqueeze(0).repeat(n, 1, 1, 1) + + shift = torch.randint(0, 2 * self.pad + 1, size=(n, 1, 1, 2), device=x.device, dtype=x.dtype) + shift *= 2.0 / (h + 2 * self.pad) + + grid = base_grid + shift + return F.grid_sample(x, grid, padding_mode="zeros", align_corners=False) + + +class RelativeActions(object): + """Transform absolute actions to relative""" + + def __init__(self, max_pos, max_orn): + self.max_pos = max_pos + self.max_orn = max_orn + + @staticmethod + def batch_angle_between(a, b): + diff = b - a + return (diff + np.pi) % (2 * np.pi) - np.pi + + def __call__(self, action_and_obs): + actions, robot_obs = action_and_obs + assert isinstance(actions, np.ndarray) + assert isinstance(robot_obs, np.ndarray) + + rel_pos = actions[:, :3] - robot_obs[:, :3] + rel_pos = np.clip(rel_pos, -self.max_pos, self.max_pos) / self.max_pos + + rel_orn = self.batch_angle_between(robot_obs[:, 3:6], actions[:, 3:6]) + rel_orn = np.clip(rel_orn, -self.max_orn, self.max_orn) / self.max_orn + + gripper = actions[:, -1:] + return np.concatenate([rel_pos, rel_orn, gripper], axis=1) + + def __repr__(self): + return self.__class__.__name__ + f"(max_pos={self.max_pos}, max_orn={self.max_orn})" diff --git a/code/policy_models/utils/utils.py b/code/policy_models/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2c226bbc4e8fc449dffed592f5b8d3d69fa202fd --- /dev/null +++ b/code/policy_models/utils/utils.py @@ -0,0 +1,195 @@ +import os +from pathlib import Path +import shutil +import time +from typing import Dict, List, Union + +import cv2 +import git +import hydra +import numpy as np +import pytorch_lightning +from pytorch_lightning.utilities.cloud_io import load as pl_load +import torch +import tqdm + + +def timeit(method): + def timed(*args, **kw): + ts = time.time() + result = method(*args, **kw) + te = time.time() + if "log_time" in kw: + name = kw.get("log_name", method.__name__.upper()) + kw["log_time"][name] = int((te - ts) * 1000) + else: + print("%r %2.2f ms" % (method.__name__, (te - ts) * 1000)) + return result + + return timed + + +def initialize_pretrained_weights(model, cfg): + pretrain_chk = pl_load(format_sftp_path(Path(cfg.pretrain_chk)), map_location=lambda storage, loc: storage) + # batch_size = model.plan_recognition.position_embeddings.weight.shape[0] + # weight = "plan_recognition.position_embeddings.weight" + # pretrain_chk["state_dict"][weight] = pretrain_chk["state_dict"][weight][:batch_size] + if "pretrain_exclude_pr" in cfg and cfg.pretrain_exclude_pr: + for key in list(pretrain_chk["state_dict"].keys()): + if key.startswith("plan_recognition"): + del pretrain_chk["state_dict"][key] + model.load_state_dict(pretrain_chk["state_dict"], strict=False) + + +def get_git_commit_hash(repo_path: Path) -> str: + try: + repo = git.Repo(search_parent_directories=True, path=repo_path.parent) + except git.exc.InvalidGitRepositoryError: + return "Not a git repository. Are you using pycharm remote interpreter?" + + changed_files = [item.a_path for item in repo.index.diff(None)] + if changed_files: + print("WARNING uncommitted modified files: {}".format(",".join(changed_files))) + return repo.head.object.hexsha + + +def get_checkpoints_for_epochs(experiment_folder: Path, epochs: Union[List, str]) -> List: + if isinstance(epochs, str): + epochs = epochs.split(",") + epochs = list(map(int, epochs)) + ep = lambda s: int(s.stem.split("=")[1]) + return [chk for chk in get_all_checkpoints(experiment_folder) if ep(chk) in epochs] + + +def get_all_checkpoints(experiment_folder: Path) -> List: + if experiment_folder.is_dir(): + checkpoint_folder = experiment_folder / "saved_models" + if checkpoint_folder.is_dir(): + checkpoints = sorted(Path(checkpoint_folder).iterdir(), key=lambda chk: chk.stat().st_mtime) + if len(checkpoints): + return [chk for chk in checkpoints if chk.suffix == ".pt"] + return [] + + +def get_last_checkpoint(experiment_folder: Path) -> Union[Path, None]: + # return newest checkpoint according to creation time + checkpoints = get_all_checkpoints(experiment_folder) + if len(checkpoints): + return checkpoints[-1] + return None + + +def save_executed_code() -> None: + print(hydra.utils.get_original_cwd()) + print(os.getcwd()) + shutil.copytree( + os.path.join(hydra.utils.get_original_cwd(), "models"), + os.path.join(hydra.utils.get_original_cwd(), f"{os.getcwd()}/code/models"), + ) + + +def info_cuda() -> Dict[str, Union[str, List[str]]]: + return { + "GPU": [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())], + # 'nvidia_driver': get_nvidia_driver_version(run_lambda), + "available": str(torch.cuda.is_available()), + "version": torch.version.cuda, + } + + +def info_packages() -> Dict[str, str]: + return { + "numpy": np.__version__, + "pyTorch_version": torch.__version__, + "pyTorch_debug": str(torch.version.debug), + "pytorch-lightning": pytorch_lightning.__version__, + "tqdm": tqdm.__version__, + } + + +def nice_print(details: Dict, level: int = 0) -> List: + lines = [] + LEVEL_OFFSET = "\t" + KEY_PADDING = 20 + for k in sorted(details): + key = f"* {k}:" if level == 0 else f"- {k}:" + if isinstance(details[k], dict): + lines += [level * LEVEL_OFFSET + key] + lines += nice_print(details[k], level + 1) + elif isinstance(details[k], (set, list, tuple)): + lines += [level * LEVEL_OFFSET + key] + lines += [(level + 1) * LEVEL_OFFSET + "- " + v for v in details[k]] + else: + template = "{:%is} {}" % KEY_PADDING + key_val = template.format(key, details[k]) + lines += [(level * LEVEL_OFFSET) + key_val] + return lines + + +def print_system_env_info(): + details = { + "Packages": info_packages(), + "CUDA": info_cuda(), + } + lines = nice_print(details) + text = os.linesep.join(lines) + return text + + +def get_portion_of_batch_ids(percentage: float, batch_size: int) -> np.ndarray: + """ + Select percentage * batch_size indices spread out evenly throughout array + Examples + ________ + >>> get_portion_of_batch_ids(percentage=0.5, batch_size=32) + array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]) + >>> get_portion_of_batch_ids(percentage=0.2, batch_size=32) + array([ 0, 5, 10, 16, 21, 26]) + >>> get_portion_of_batch_ids(percentage=0.01, batch_size=64) + array([], dtype=int64) + """ + num = int(batch_size * percentage) + if num == 0: + return np.array([], dtype=np.int64) + indices = np.arange(num).astype(float) + stretch = batch_size / num + indices *= stretch + return np.unique(indices.astype(np.int64)) + + +def add_text(img, lang_text): + height, width, _ = img.shape + if lang_text != "": + coord = (1, int(height - 10)) + font_scale = (0.7 / 500) * width + thickness = 1 + cv2.putText( + img, + text=lang_text, + org=coord, + fontFace=cv2.FONT_HERSHEY_SIMPLEX, + fontScale=font_scale, + color=(0, 0, 0), + thickness=thickness * 3, + lineType=cv2.LINE_AA, + ) + cv2.putText( + img, + text=lang_text, + org=coord, + fontFace=cv2.FONT_HERSHEY_SIMPLEX, + fontScale=font_scale, + color=(255, 255, 255), + thickness=thickness, + lineType=cv2.LINE_AA, + ) + + +def format_sftp_path(path): + """ + When using network mount from nautilus, format path + """ + if path.as_posix().startswith("sftp"): + uid = os.getuid() + path = Path(f"/run/user/{uid}/gvfs/sftp:host={path.as_posix()[6:]}") + return path diff --git a/code/policy_models/wrappers/__pycache__/hulc_wrapper.cpython-310.pyc b/code/policy_models/wrappers/__pycache__/hulc_wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1afe705d9861f3704a23bf8f2a013fd388f9125b Binary files /dev/null and b/code/policy_models/wrappers/__pycache__/hulc_wrapper.cpython-310.pyc differ diff --git a/code/policy_models/wrappers/hulc_wrapper.py b/code/policy_models/wrappers/hulc_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..144a1e28d3cf9aa481c2c0fd984dffde5de83b9e --- /dev/null +++ b/code/policy_models/wrappers/hulc_wrapper.py @@ -0,0 +1,114 @@ +import logging +import os +from typing import Any, Dict, Tuple, Union + +import gym +import numpy as np +import torch + +from calvin_env.envs.play_table_env import get_env +from calvin_env.utils.utils import EglDeviceNotFoundError, get_egl_device_id +from policy_models.datasets.utils.episode_utils import process_depth, process_rgb, process_state + +logger = logging.getLogger(__name__) + + +class HulcWrapper(gym.Wrapper): + def __init__(self, dataset_loader, device, show_gui=False, **kwargs): + self.set_egl_device(device) + env = get_env( + dataset_loader.abs_datasets_dir, show_gui=show_gui, obs_space=dataset_loader.observation_space, **kwargs + ) + super(HulcWrapper, self).__init__(env) + self.observation_space_keys = dataset_loader.observation_space + self.transforms = dataset_loader.transforms + self.proprio_state = dataset_loader.proprio_state + self.device = device + self.relative_actions = "rel_actions" in self.observation_space_keys["actions"] + logger.info(f"Initialized PlayTableEnv for device {self.device}") + + @staticmethod + def set_egl_device(device): + if "EGL_VISIBLE_DEVICES" in os.environ: + logger.warning("Environment variable EGL_VISIBLE_DEVICES is already set. Is this intended?") + cuda_id = device.index if device.type == "cuda" else 0 + try: + egl_id = get_egl_device_id(cuda_id) + except EglDeviceNotFoundError: + logger.warning( + "Couldn't find correct EGL device. Setting EGL_VISIBLE_DEVICE=0. " + "When using DDP with many GPUs this can lead to OOM errors. " + "Did you install PyBullet correctly? Please refer to calvin env README" + ) + egl_id = 0 + os.environ["EGL_VISIBLE_DEVICES"] = str(egl_id) + logger.info(f"EGL_DEVICE_ID {egl_id} <==> CUDA_DEVICE_ID {cuda_id}") + + def transform_observation(self, obs: Dict[str, Any]) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]: + obs['rgb_obs']['cond_static'] = obs['rgb_obs']['rgb_static'] + obs['rgb_obs']['cond_gripper'] = obs['rgb_obs']['rgb_gripper'] + state_obs = process_state(obs, self.observation_space_keys, self.transforms, self.proprio_state) + rgb_obs = process_rgb(obs["rgb_obs"], self.observation_space_keys, self.transforms) + depth_obs = process_depth(obs["depth_obs"], self.observation_space_keys, self.transforms) + + state_obs["robot_obs"] = state_obs["robot_obs"].to(self.device).unsqueeze(0) + rgb_obs.update({"rgb_obs": {k: v.to(self.device).unsqueeze(0) for k, v in rgb_obs["rgb_obs"].items()}}) + depth_obs.update({"depth_obs": {k: v.to(self.device).unsqueeze(0) for k, v in depth_obs["depth_obs"].items()}}) + + obs_dict: Dict = { + **rgb_obs, + **state_obs, + **depth_obs, + "robot_obs_raw": torch.from_numpy(obs["robot_obs"]).to(self.device), + } + return obs_dict + + def step( + self, action_tensor: torch.Tensor + ) -> Tuple[Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]], int, bool, Dict]: + if self.relative_actions: + action = action_tensor.squeeze().cpu().detach().numpy() + assert len(action) == 7 + else: + if action_tensor.shape[-1] == 7: + slice_ids = [3, 6] + elif action_tensor.shape[-1] == 8: + slice_ids = [3, 7] + else: + logger.error("actions are required to have length 8 (for euler angles) or 9 (for quaternions)") + raise NotImplementedError + action = np.split(action_tensor.squeeze().cpu().detach().numpy(), slice_ids) + action[-1] = 1 if action[-1] > 0 else -1 + o, r, d, i = self.env.step(action) + #o['rgb_obs']['cond_static'] = o['rgb_obs']['rgb_static'] + #o['rgb_obs']['cond_gripper'] = o['rgb_obs']['rgb_gripper'] + #print('cond_static_shape: ', o['rgb_obs']['cond_static']) + obs = self.transform_observation(o) + return obs, r, d, i + + def reset( + self, + reset_info: Dict[str, Any] = None, + batch_idx: int = 0, + seq_idx: int = 0, + scene_obs: Any = None, + robot_obs: Any = None, + ) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]: + if reset_info is not None: + obs = self.env.reset( + robot_obs=reset_info["robot_obs"][batch_idx, seq_idx], + scene_obs=reset_info["scene_obs"][batch_idx, seq_idx], + ) + elif scene_obs is not None or robot_obs is not None: + obs = self.env.reset(scene_obs=scene_obs, robot_obs=robot_obs) + else: + obs = self.env.reset() + + return self.transform_observation(obs) + + def get_info(self): + return self.env.get_info() + + def get_obs(self): + obs = self.env.get_obs() + return self.transform_observation(obs)