diff --git a/starVLA/dinov3/dinov3/eval/text/tokenizer.py b/starVLA/dinov3/dinov3/eval/text/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..5834418f0c8220280d6059c89bb6ae55f5972789 --- /dev/null +++ b/starVLA/dinov3/dinov3/eval/text/tokenizer.py @@ -0,0 +1,67 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from typing import List, Union + +import torch +from dinov3.thirdparty.CLIP.clip.simple_tokenizer import SimpleTokenizer + + +class Tokenizer(SimpleTokenizer): + def __init__(self, vocab_path: str): + SimpleTokenizer.__init__(self, bpe_path=vocab_path) + + def tokenize( + self, texts: Union[str, List[str]], context_length: int = 77 + ) -> 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 + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + sot_token = self.encoder["<|startoftext|>"] + eot_token = self.encoder["<|endoftext|>"] + all_tokens = [[sot_token] + self.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: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, : len(tokens)] = torch.tensor(tokens) + + return result + + +def get_tokenizer(bpe_path_or_url: str) -> Tokenizer | None: + import urllib + from io import BytesIO + + from .tokenizer import Tokenizer + + if urllib.parse.urlparse(bpe_path_or_url).scheme: + try: + with urllib.request.urlopen(bpe_path_or_url) as response: + file_buf = BytesIO(response.read()) + return Tokenizer(vocab_path=file_buf) + except Exception as e: + raise FileNotFoundError( + f"Failed to download file from url {bpe_path_or_url} with error last: {e}" + ) + else: + with open(bpe_path_or_url, "rb") as f: + file_buf = BytesIO(f.read()) + return Tokenizer(vocab_path=file_buf) diff --git a/starVLA/dinov3/dinov3/eval/text/train_dinotxt.py b/starVLA/dinov3/dinov3/eval/text/train_dinotxt.py new file mode 100644 index 0000000000000000000000000000000000000000..295b04c475719c6a75ee260f0cd1bbcc00de42dd --- /dev/null +++ b/starVLA/dinov3/dinov3/eval/text/train_dinotxt.py @@ -0,0 +1,339 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import gc +import logging +from functools import partial +import math +import os +import sys +from pathlib import Path +from typing import Callable + +import dinov3.distributed as distributed +import torch +from dinov3.checkpointer import ( + find_latest_checkpoint, + keep_last_n_checkpoints, + load_checkpoint, + save_checkpoint, +) +from dinov3.configs import setup_job +from dinov3.data import SamplerType, make_data_loader, make_dataset +from dinov3.eval.text.build_dinotxt import build_model_and_tokenizer +from dinov3.eval.text.clip_loss import memory_efficient_clip_loss +from dinov3.eval.text.dinotxt_model import DINOTxt, DINOTxtConfig +from dinov3.eval.text.gram_loss import gram_loss_fn +from dinov3.logging import MetricLogger, setup_logging +from dinov3.train.cosine_lr_scheduler import linear_warmup_cosine_decay +from omegaconf import OmegaConf +from torch import optim + +logger = logging.getLogger("dinov3") + + +def unwrap_model(model): + return getattr(model, "module", model) + + +def test( + model: DINOTxt, + iteration: str, + output_dir: str, +): + eval_dir = Path(output_dir) / "eval" / str(iteration) + if distributed.is_subgroup_main_process(): + eval_dir.mkdir(parents=True, exist_ok=True) + + ckpt_dir = eval_dir / str("sharded_model_checkpoint") + save_checkpoint(ckpt_dir, iteration=iteration, model=model) + + +def apply_learning_rate(optimizer, lr: float): + for param_group in optimizer.param_groups: + param_group["lr"] = lr + + +def exclude(n: str, p: torch.Tensor) -> bool: + return p.ndim < 2 or "bn" in n or "ln" in n or "bias" in n or "logit_scale" in n + + +def include(n: str, p: torch.Tensor) -> bool: + return not exclude(n, p) + + +def train( + train_dataset, + model: DINOTxt, + tokenizer: Callable, + max_iteration: int, + warmup_length: int, + checkpointing_period: int, + output_dir: str, + dtype_str: str, + sampler_type: SamplerType, + lr_scheduler_type: str, + lr: float, + weight_decay: float, + batch_size: int = 256, + beta1: float = 0.9, + beta2: float = 0.99, + eps: float = 1e-8, + num_workers: int = 10, + eval_freq: int = 1000, + gc_freq: int = 100, + use_gram_loss: bool = False, + patch_sampling_rate_for_gram_loss: float = 0.5, + normalize_patch_tokens_for_gram_loss: bool = False, + gram_loss_weight: float = 1.0, + max_checkpoints_to_keep: int = None, + resume: bool = False, + seed: int = 11, +): + named_parameters = list(model.named_parameters()) + gain_or_bias_params = [ + p for n, p in named_parameters if exclude(n, p) and p.requires_grad + ] + gain_or_bias_params_names = [ + n for n, p in named_parameters if exclude(n, p) and p.requires_grad + ] + rest_params = [p for n, p in named_parameters if include(n, p) and p.requires_grad] + rest_params_names = [ + n for n, p in named_parameters if include(n, p) and p.requires_grad + ] + logger.info(f"Gain or bias params: {gain_or_bias_params_names}") + logger.info(f"Rest params: {rest_params_names}") + logger.info( + f"Learning rate: {lr}, batch_size_per_gpu: {batch_size}, weight_decay: {weight_decay}" + ) + optimizer = optim.AdamW( + [ + {"params": gain_or_bias_params, "weight_decay": 0.0}, + {"params": rest_params, "weight_decay": weight_decay}, + ], + lr=lr, + betas=(beta1, beta2), + eps=eps, + ) + learning_rates = linear_warmup_cosine_decay( + 0, lr, 0, warmup_iterations=warmup_length, total_iterations=max_iteration + ) + logger.info( + f"Init lr scheduler: {lr_scheduler_type}, warmup length: {warmup_length}, base_lr: {lr}, max iter: {max_iteration}" + ) + + if ( + resume + and (ckpt_dir := find_latest_checkpoint(os.path.join(output_dir, "ckpt"))) + is not None + ): + iteration = load_checkpoint(ckpt_dir, model=model, optimizer=optimizer) + start_iteration = iteration + 1 + del iteration, ckpt_dir + else: + logger.info("Initializing from scratch") + start_iteration = 0 + + def collate_fn(batch): + images, captions = list(zip(*batch))[:2] + return torch.stack(images), tokenizer.tokenize(captions) + + train_data_loader = make_data_loader( + dataset=train_dataset, + batch_size=batch_size, + num_workers=num_workers, + shuffle=False, + seed=seed, + sampler_type=sampler_type, + sampler_advance=start_iteration, + drop_last=True, + persistent_workers=True, + collate_fn=collate_fn, + ) + rank = distributed.get_rank() + world_size = distributed.get_world_size() + logger.info( + f"Init loss function: rank: {distributed.get_rank()}, world size: {world_size}" + ) + clip_loss = partial(memory_efficient_clip_loss, group=torch.distributed.group.WORLD) + cur_iteration = start_iteration + logger.info(f"Starting training from iteration {start_iteration}...") + header = "Training" + metric_logger = MetricLogger(delimiter=" ") + gc.disable() + device_id = rank % torch.cuda.device_count() + + for batch in metric_logger.log_every( + train_data_loader, + 10, + header, + max_iteration, + start_iteration, + ): + images, text_tokens = batch + images = images.to(device=device_id, non_blocking=True) + text_tokens = text_tokens.to(device=device_id, non_blocking=True) + ( + image_embeddings, + text_embeddings, + logit_scale, + patch_tokens, + backbone_patch_tokens, + ) = model(images, text_tokens) + contrastive_loss = clip_loss(image_embeddings, text_embeddings, logit_scale) + total_loss = contrastive_loss + if use_gram_loss: + gram_loss = gram_loss_fn( + patch_tokens, + backbone_patch_tokens, + patch_sampling_rate_for_gram_loss, + normalize_patch_tokens_for_gram_loss, + ) + total_loss = contrastive_loss + gram_loss_weight * gram_loss + + if total_loss.isnan(): + msg = f"Loss is NaN at iteration {cur_iteration}, aborting..." + logger.error(msg) + raise RuntimeError(msg) + apply_learning_rate(optimizer=optimizer, lr=learning_rates[cur_iteration]) + optimizer.zero_grad() + total_loss.backward() + optimizer.step() + + # This clamping trick is from OpenCLIP reposistory which MetaCLIP follows. Orginally used in CLIP training. + # NOTE: we clamp to 4.6052 = ln(100), as in the original paper. + with torch.no_grad(): + unwrap_model(model).logit_scale.clamp_(0, math.log(100)) + metric_logger.update(contrastive_loss=contrastive_loss.item()) + if use_gram_loss: + metric_logger.update(gram_loss=gram_loss.item()) + metric_logger.update(lr=optimizer.param_groups[0]["lr"]) + metric_logger.update(logit_scale=logit_scale.item()) + is_last_iteration = (cur_iteration + 1) == max_iteration + is_ckpt_iteration = ( + (cur_iteration + 1) % checkpointing_period == 0 + ) or is_last_iteration + if is_ckpt_iteration: + ckpt_dir = Path(output_dir, "ckpt").expanduser() + save_checkpoint( + ckpt_dir / str(cur_iteration), + iteration=cur_iteration, + model=model, + optimizer=optimizer, + ) + if distributed.is_main_process(): + keep_last_n_checkpoints(ckpt_dir, max_checkpoints_to_keep) + if eval_freq > 0 and (cur_iteration + 1) % eval_freq == 0: + test( + model, + iteration=f"training_{cur_iteration}", + batch_size=batch_size, + num_workers=num_workers, + output_dir=output_dir, + dtype_str=dtype_str, + ) + torch.cuda.synchronize() + if (cur_iteration + 1) % gc_freq == 0: + logger.info("Garbage collection...") + gc.collect() + cur_iteration += 1 + + +def write_config( + model_config: DINOTxtConfig, output_dir, name="clip_model_config.yaml" +): + logger.info(OmegaConf.to_yaml(model_config)) + saved_cfg_path = os.path.join(output_dir, name) + with open(saved_cfg_path, "w") as f: + OmegaConf.save(config=model_config, f=f) + return saved_cfg_path + + +def main(argv=None): + if argv is None: + argv = sys.argv[1:] + args_dict = OmegaConf.to_container(OmegaConf.from_cli(argv)) + logger.info(args_dict) + config = OmegaConf.load(args_dict["trainer_config_file"]) + logger.info(config) + if "output_dir" in args_dict: + config.output_dir = args_dict["--output-dir"] + setup_job(output_dir=config.output_dir, seed=config.seed) + setup_logging(output=os.path.join(config.output_dir, "nan_logs"), name="nan_logger") + logger.info("Trainer config:") + logger.info(config) + model_config = DINOTxtConfig( + embed_dim=config.embed_dim, + text_backbone_config=config.text_backbone_config, + vision_backbone_config=config.vision_backbone_config, + text_backbone_pretrained_weights=config.text_backbone_pretrained_weights, + vision_backbone_pretrained_weights=config.vision_backbone_pretrained_weights, + vision_model_train_img_size=config.vision_model_train_img_size, + vision_model_use_class_token=config.vision_model_use_class_token, + vision_model_use_patch_tokens=config.vision_model_use_patch_tokens, + vision_model_num_head_blocks=config.vision_model_num_head_blocks, + vision_model_head_blocks_drop_path=config.vision_model_head_blocks_drop_path, + vision_model_use_linear_projection=config.vision_model_use_linear_projection, + vision_model_patch_tokens_pooler_type=config.vision_model_patch_tokens_pooler_type, + vision_model_patch_token_layer=config.vision_model_patch_token_layer, + text_model_freeze_backbone=config.text_model_freeze_backbone, + text_model_num_head_blocks=config.text_model_num_head_blocks, + text_model_head_blocks_is_causal=config.text_model_head_blocks_is_causal, + text_model_head_blocks_drop_prob=config.text_model_head_blocks_drop_prob, + text_model_tokens_pooler_type=config.text_model_tokens_pooler_type, + text_model_use_linear_projection=config.text_model_use_linear_projection, + text_vocab_path_or_url=config.text_vocab_path_or_url, + init_logit_scale=config.init_logit_scale, + freeze_logit_scale=config.freeze_logit_scale, + init_logit_bias=config.init_logit_bias, + ) + write_config(model_config=model_config, output_dir=config.output_dir) + model, transform, tokenizer = build_model_and_tokenizer( + model_config, + use_fsdp=config.use_fsdp, + do_compile=config.do_compile, + use_ac=config.use_ac, + use_cuda_graphs=config.use_cuda_graphs, + ) + + train_dataset = make_dataset( + dataset_str=config.train_dataset_str, + transform=transform, + ) + sampler_type = ( + SamplerType.SHARDED_INFINITE + if config.dataset_use_cache + else SamplerType.INFINITE + ) + train( + train_dataset=train_dataset, + model=model, + tokenizer=tokenizer, + max_iteration=config.max_iteration, + warmup_length=config.warmup_length, + checkpointing_period=config.checkpointing_period, + output_dir=config.output_dir, + dtype_str=config.dtype_str, + lr_scheduler_type=config.lr_scheduler_type, + lr=config.lr, + weight_decay=config.weight_decay, + batch_size=config.batch_size, + beta1=config.beta1, + beta2=config.beta2, + eps=config.eps, + sampler_type=sampler_type, + eval_freq=config.eval_freq, + gc_freq=config.gc_freq, + max_checkpoints_to_keep=config.max_checkpoints_to_keep, + use_gram_loss=config.vision_model_use_gram_loss, + patch_sampling_rate_for_gram_loss=config.vision_model_patch_sampling_rate_for_gram_loss, + normalize_patch_tokens_for_gram_loss=config.vision_model_normalize_patch_tokens_for_gram_loss, + gram_loss_weight=config.vision_model_gram_loss_weight, + resume=not config.no_resume, + ) + + +if __name__ == "__main__": + main() diff --git a/starVLA/dinov3/dinov3/eval/text/vision_tower.py b/starVLA/dinov3/dinov3/eval/text/vision_tower.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b8b389ce8675f5d598921e535b92f82c5c4399 --- /dev/null +++ b/starVLA/dinov3/dinov3/eval/text/vision_tower.py @@ -0,0 +1,207 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +from functools import partial +from typing import Optional, Tuple + +import torch +from torch import nn + +from dinov3.layers import SelfAttentionBlock, SwiGLUFFN +from dinov3.models.vision_transformer import init_weights_vit +from dinov3.utils import named_apply + +logger = logging.getLogger("dinov3") + + +class VisionHead(nn.Module): + def __init__( + self, + input_dim: int, + embed_dim: int, + num_heads: int, + num_blocks: int, + blocks_drop_path: float, + use_class_token: bool, + use_patch_tokens: bool, + use_linear_projection: bool, + ): + super().__init__() + block_list = [nn.Identity()] + self.ln_final = nn.Identity() + if num_blocks > 0: + block_list = [ + SelfAttentionBlock( + input_dim, + num_heads, + ffn_layer=partial(SwiGLUFFN, align_to=64), + init_values=1e-5, + drop_path=blocks_drop_path, + ) + for _ in range(num_blocks) + ] + self.ln_final = nn.LayerNorm(input_dim) + self.blocks = nn.ModuleList(block_list) + self.num_blocks = num_blocks + multiplier = 2 if use_class_token and use_patch_tokens else 1 + self.linear_projection = nn.Identity() + if multiplier * input_dim != embed_dim or use_linear_projection: + logger.info( + f"Vision Tower: Using a linear projection from {input_dim} to {embed_dim}" + ) + assert embed_dim % multiplier == 0, ( + f"Expects {embed_dim} to be divisible by {multiplier}" + ) + self.linear_projection = nn.Linear( + input_dim, embed_dim // multiplier, bias=False + ) + + def init_weights(self): + if self.num_blocks > 0: + for i in range(self.num_blocks): + block = self.blocks[i] + named_apply(init_weights_vit, block) + self.ln_final.reset_parameters() + if isinstance(self.linear_projection, nn.Linear): + nn.init.normal_( + self.linear_projection.weight, + std=self.linear_projection.in_features**-0.5, + ) + + def forward(self, image_tokens: torch.Tensor) -> torch.Tensor: + # FIXME(cijose) ROPE embeddings are not used in DINOv2, refactor to use it in the future + for block in self.blocks: + image_tokens = block(image_tokens) + image_tokens = self.ln_final(image_tokens) + return self.linear_projection(image_tokens) + + +class VisionTower(nn.Module): + def __init__( + self, + backbone: nn.Module, + freeze_backbone: bool, + embed_dim: int, + num_head_blocks: int, + head_blocks_block_drop_path: float, + use_class_token: bool, + use_patch_tokens: bool, + patch_token_layer: int, + patch_tokens_pooler_type: str, + use_linear_projection: bool, + ): + super().__init__() + self.backbone = backbone + self.freeze_backbone = freeze_backbone + self.use_class_token = use_class_token + self.use_patch_tokens = use_patch_tokens + self.patch_token_layer = patch_token_layer + self.patch_tokens_pooler_type = patch_tokens_pooler_type + self.num_register_tokens = 0 + if hasattr(self.backbone, "num_register_tokens"): + self.num_register_tokens = self.backbone.num_register_tokens + elif hasattr(self.backbone, "n_storage_tokens"): + self.num_register_tokens = self.backbone.n_storage_tokens + backbone_out_dim = self.backbone.embed_dim + logger.info(f"Visual backbone embedding dimension: {backbone_out_dim}") + self.head = VisionHead( + backbone_out_dim, + embed_dim, + self.backbone.num_heads, + num_head_blocks, + head_blocks_block_drop_path, + use_class_token, + use_patch_tokens, + use_linear_projection, + ) + + def init_weights(self): + self.backbone.init_weights() + self.head.init_weights() + + def get_backbone_features( + self, images: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + tokens = self.backbone.get_intermediate_layers( + images, + n=self.patch_token_layer, + return_class_token=True, + return_extra_tokens=True, + ) + class_token = tokens[-1][1] + patch_tokens = tokens[0][0] + register_tokens = tokens[0][2] + return class_token, patch_tokens, register_tokens + + def get_class_and_patch_tokens( + self, images: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + class_token, patch_tokens, register_tokens = self.get_backbone_features(images) + image_tokens = self.head( + torch.cat([class_token.unsqueeze(1), register_tokens, patch_tokens], dim=1) + ) + return ( + image_tokens[:, 0], + image_tokens[:, self.num_register_tokens + 1 :], + patch_tokens, + ) + + def forward(self, images: torch.Tensor) -> torch.Tensor: + class_token, patch_tokens, backbone_patch_tokens = ( + self.get_class_and_patch_tokens(images) + ) + features = [] + if self.use_class_token: + features.append(class_token) + if self.use_patch_tokens: + if self.patch_tokens_pooler_type == "mean": + features.append(torch.mean(patch_tokens, dim=1)) + elif self.patch_tokens_pooler_type == "max": + features.append(torch.max(patch_tokens, dim=1).values) + else: + raise ValueError( + f"Unknown patch tokens pooler type: {self.patch_tokens_pooler_type}" + ) + return torch.cat(features, dim=-1), patch_tokens, backbone_patch_tokens + + +def build_vision_model( + embed_dim: int, + backbone_model_config: str, + freeze_backbone: bool, + num_head_blocks: int, + blocks_drop_path: float, + use_class_token: bool, + use_patch_tokens: bool, + patch_token_layer: int, + patch_tokens_pooler_type: str, + use_linear_projection: bool, + backbone: Optional[nn.Module] = None, +): + if backbone is None: + if backbone_model_config is not None: + from omegaconf import OmegaConf + + from dinov3.models import build_model_from_cfg as build_vision_backbone + + cfg = OmegaConf.load(backbone_model_config) + backbone, _ = build_vision_backbone(cfg, only_teacher=True) + else: + raise RuntimeError( + "Failed to create, vision backbone, either backbone or backbone_model_config should be not None" + ) + return VisionTower( + backbone, + freeze_backbone, + embed_dim, + num_head_blocks, + blocks_drop_path, + use_class_token, + use_patch_tokens, + patch_token_layer, + patch_tokens_pooler_type, + use_linear_projection, + ) diff --git a/starVLA/dinov3/dinov3/eval/utils.py b/starVLA/dinov3/dinov3/eval/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c72096a22f896b443f072f84ef1d01a1b19e09fd --- /dev/null +++ b/starVLA/dinov3/dinov3/eval/utils.py @@ -0,0 +1,286 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import gc +import logging +import os +from enum import Enum +from typing import Any, Dict, List, Optional + +import numpy as np +import torch +from torch import nn +from torchmetrics import Metric + +import dinov3.distributed as distributed +from dinov3.data import DatasetWithEnumeratedTargets, SamplerType, make_data_loader +from dinov3.eval.accumulators import NoOpAccumulator, ResultsAccumulator +from dinov3.logging import MetricLogger + +logger = logging.getLogger("dinov3") + + +class LossType(Enum): + CROSS_ENTROPY = "cross_entropy" + BINARY_CROSS_ENTROPY = "binary_cross_entropy" + + +class ModelWithNormalize(torch.nn.Module): + def __init__(self, model: torch.nn.Module) -> None: + super().__init__() + self._model = model + + def forward(self, samples): + return nn.functional.normalize(self._model(samples), dim=1, p=2) + + +class ModelWithMultiScale(torch.nn.Module): + def __init__(self, model: torch.nn.Module, mode: str = "bilinear") -> None: + super().__init__() + self._model = model + self._mode = mode + + def forward(self, samples): + output = None + for scale in (1, 0.5**0.5, 0.5): + if scale == 1: + resized_samples = samples.clone() + else: + resized_samples = nn.functional.interpolate( + samples, scale_factor=scale, mode=self._mode, align_corners=False + ) + scale_output = self._model(resized_samples).clone() + if output is None: + output = scale_output + else: + output += scale_output + return output / 3 + + +def wrap_model( + model: nn.Module, + *, + normalize: bool = True, + multi_scale: bool = False, +) -> nn.Module: + logger.info("multi-scale: {}".format("enabled" if multi_scale else "disabled")) + if multi_scale: + model = ModelWithMultiScale(model) + + logger.info("normalize: {}".format("enabled" if normalize else "disabled")) + if normalize: + model = ModelWithNormalize(model) + return model + + +class ModelWithIntermediateLayers(nn.Module): + def __init__(self, feature_model, n, autocast_ctx, reshape=False, return_class_token=True): + super().__init__() + self.feature_model = feature_model + self.feature_model.eval() + self.n = n # Layer indices (Sequence) or n last layers (int) to take + self.autocast_ctx = autocast_ctx + self.reshape = reshape + self.return_class_token = return_class_token + + def forward(self, images): + with torch.inference_mode(): + with self.autocast_ctx(): + features = self.feature_model.get_intermediate_layers( + images, + n=self.n, + reshape=self.reshape, + return_class_token=self.return_class_token + ) + return features + + +@torch.inference_mode() +def evaluate( + model: nn.Module, + data_loader, + postprocessors: Dict[str, nn.Module], + metrics: Dict[str, Metric], + device: torch.device, + criterion: Optional[nn.Module] = None, + accumulate_results: bool = False, +): + gc.collect() # Avoids garbage collection errors in DataLoader workers + model.eval() + if criterion is not None: + criterion.eval() + + for metric in metrics.values(): + metric = metric.to(device) + + metric_logger = MetricLogger(delimiter=" ") + header = "Test:" + + accumulator_class = ResultsAccumulator if accumulate_results else NoOpAccumulator + accumulators = {k: accumulator_class() for k in postprocessors.keys()} + + # Dataset needs to be wrapped in fairvit.data.adapters.DatasetWithEnumeratedTargets + for samples, (index, targets), *_ in metric_logger.log_every(data_loader, 10, header): + samples, targets, index = samples[index >= 0], targets[index >= 0], index[index >= 0] + if len(index) == 0: + continue + + outputs = model(samples.to(device)) + index = index.to(device) + targets = targets.to(device) + + if criterion is not None: + loss = criterion(outputs, targets) + metric_logger.update(loss=loss.item()) + + for k, metric in metrics.items(): + metric_inputs = postprocessors[k](outputs, targets) + metric.update(**metric_inputs) + accumulators[k].update(preds=metric_inputs["preds"], target=metric_inputs["target"], index=index) + + metric_logger.synchronize_between_processes() + logger.info(f"Averaged stats: {metric_logger}") + stats = {k: metric.compute() for k, metric in metrics.items()} + metric_logger_stats = {k: meter.global_avg for k, meter in metric_logger.meters.items()} + + # accumulator.accumulate() returns None for the NoOpAccumulator + accumulated_results = {k: accumulator.accumulate() for k, accumulator in accumulators.items()} + + return metric_logger_stats, stats, accumulated_results + + +def all_gather_and_flatten(tensor_rank): + tensor_all_ranks = torch.empty( + distributed.get_world_size(), + *tensor_rank.shape, + dtype=tensor_rank.dtype, + device=tensor_rank.device, + ) + tensor_list = list(tensor_all_ranks.unbind(0)) + torch.distributed.all_gather(tensor_list, tensor_rank.contiguous()) + return tensor_all_ranks.flatten(end_dim=1) + + +def extract_features(model, dataset, batch_size, num_workers, gather_on_cpu=False): + dataset_with_enumerated_targets = DatasetWithEnumeratedTargets(dataset) + sample_count = len(dataset_with_enumerated_targets) + data_loader = make_data_loader( + dataset=dataset_with_enumerated_targets, + batch_size=batch_size, + num_workers=num_workers, + sampler_type=SamplerType.DISTRIBUTED, + drop_last=False, + shuffle=False, + ) + return extract_features_with_dataloader(model, data_loader, sample_count, gather_on_cpu) + + +@torch.inference_mode() +def extract_features_with_dataloader(model, data_loader, sample_count, gather_on_cpu=False): + gather_device = torch.device("cpu") if gather_on_cpu else torch.device("cuda") + metric_logger = MetricLogger(delimiter=" ") + features, all_labels = None, None + for samples, (index, labels_rank) in metric_logger.log_every(data_loader, 10): + samples = samples.cuda(non_blocking=True) + labels_rank = labels_rank.cuda(non_blocking=True) + index = index.cuda(non_blocking=True) + features_rank = model(samples).float() + + # init storage feature matrix + if features is None: + features = torch.zeros(sample_count, features_rank.shape[-1], device=gather_device) + labels_shape = list(labels_rank.shape) + labels_shape[0] = sample_count + all_labels = torch.full(labels_shape, fill_value=-1, device=gather_device) + logger.info(f"Storing features into tensor of shape {features.shape}") + + # share indexes, features and labels between processes + index_all = all_gather_and_flatten(index).to(gather_device) + features_all_ranks = all_gather_and_flatten(features_rank).to(gather_device) + labels_all_ranks = all_gather_and_flatten(labels_rank).to(gather_device) + + # update storage feature matrix + if len(index_all) > 0: + features.index_copy_(0, index_all, features_all_ranks) + all_labels.index_copy_(0, index_all, labels_all_ranks) + + logger.info(f"Features Shape {features.shape}") + logger.info(f"Labels Shape {all_labels.shape}") + + return features, all_labels + + +def save_features_dict(features_dict: Dict[str, torch.Tensor], path: str) -> None: + logger.info(f'saving features to "{path}"') + + for key, value in features_dict.items(): + assert isinstance(key, str) + assert isinstance(value, torch.Tensor) + + _, ext = os.path.splitext(path) + if ext == ".pt": + torch.save(features_dict, path) + elif ext == ".npy": + numpy_features_dict = { # Convert to NumPy arrays (if possible) + key: value.cpu().numpy() for key, value in features_dict.items() + } + np.save(path, numpy_features_dict, allow_pickle=True) + else: + raise ValueError(f'Unsupported features dict extension "{ext}"') + + +def load_features_dict(path: str) -> Dict[str, torch.Tensor]: + logger.info(f'loading features from "{path}"') + + _, ext = os.path.splitext(path) + if ext == ".pt": + features_dict = torch.load(path) + elif ext == ".npy": + numpy_features_dict = np.load(path, allow_pickle=True).item() + features_dict = {key: torch.from_numpy(value) for key, value in numpy_features_dict.items()} + else: + raise ValueError(f'Unsupported features dict extension "{ext}"') + + for key, value in features_dict.items(): + assert isinstance(key, str) + assert isinstance(value, torch.Tensor) + + return features_dict + + +def average_metrics(eval_metrics_dict: dict[Any, dict[str, torch.Tensor]], ignore_keys: List[str] = []): + """ + Function that computes the average and the std on a metrics dict. + A linear evaluation dictionary contains "best_classifier", + so this specific key is removed for computing aggregated metrics. + """ + output_metrics_dict = {} + metrics = [metric for metric in eval_metrics_dict[0].keys() if metric not in ignore_keys] + for metric in metrics: + stats_tensor = torch.tensor([stat[metric] for stat in eval_metrics_dict.values()]) + output_metrics_dict[metric + "_mean"] = stats_tensor.mean().item() + output_metrics_dict[metric + "_std"] = torch.std(stats_tensor).item() + + return output_metrics_dict + + +def save_results( + preds: torch.Tensor, + target: torch.Tensor, + output_dir: str, + filename_suffix: Optional[str] = None, +) -> None: + """ + Helper to save predictions from a model and their associated targets, aligned by their index + """ + filename_suffix = "" if filename_suffix is None else f"_{filename_suffix}" + preds_filename = f"preds{filename_suffix}.npy" + target_filename = f"target{filename_suffix}.npy" + preds_path = os.path.join(output_dir, preds_filename) + target_path = os.path.join(output_dir, target_filename) + logger.info(f"Saving to {preds_path}") + np.save(preds_path, preds.cpu().numpy()) + logger.info(f"Saving to {target_path}") + np.save(target_path, target.cpu().numpy()) diff --git a/starVLA/dinov3/dinov3/fsdp/__init__.py b/starVLA/dinov3/dinov3/fsdp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dinov3/dinov3/fsdp/ac_compile_parallelize.py b/starVLA/dinov3/dinov3/fsdp/ac_compile_parallelize.py new file mode 100644 index 0000000000000000000000000000000000000000..dc7aa3e1c7eb28f15738c5d9af6a750215e96293 --- /dev/null +++ b/starVLA/dinov3/dinov3/fsdp/ac_compile_parallelize.py @@ -0,0 +1,220 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +from functools import partial +from typing import Any, Dict, List + +import torch +import torch.distributed as dist +import torch.nn as nn +from torch.distributed._composable.fsdp import MixedPrecisionPolicy, fully_shard +from torch.distributed.device_mesh import DeviceMesh, init_device_mesh +from torch.distributed.fsdp import register_fsdp_forward_method +from torch.distributed.fsdp._fully_shard._fsdp_state import FSDPState +from torch.utils.checkpoint import create_selective_checkpoint_contexts + +from dinov3.utils import utils + + +logger = logging.getLogger("dinov3") + + +def get_activation_checkpoint_wrapper(cfg): + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper + + if cfg.train.checkpointing_full: + _checkpointing_wrapper = checkpoint_wrapper + logger.info("using selective checkpointing on backbone with full checkpointing policy") + else: + _save_list = [ + # mm + torch.ops.aten.mm.default, + torch.ops.aten._scaled_mm.default, + # attentions + torch.ops.aten._scaled_dot_product_efficient_attention.default, + torch.ops.aten._scaled_dot_product_flash_attention.default, + torch.ops._c10d_functional.reduce_scatter_tensor.default, + ] + _checkpointing_wrapper = partial( + checkpoint_wrapper, + context_fn=partial(create_selective_checkpoint_contexts, _save_list), + preserve_rng_state=True, + ) + logger.info("using selective checkpointing on backbone with selective policy") + return _checkpointing_wrapper + + +def activation_checkpoint_convnext(cfg, model: nn.Module): + _checkpointing_wrapper = get_activation_checkpoint_wrapper(cfg) + for stage_id, stage in enumerate(model.stages): + for block_id, block in enumerate(stage): + model.stages[stage_id][block_id] = _checkpointing_wrapper(block) + for dsl_id, dsl in enumerate(model.downsample_layers): + model.downsample_layers[dsl_id] = _checkpointing_wrapper(dsl) + + +def activation_checkpoint_transformer(cfg, model: nn.Module): + _checkpointing_wrapper = get_activation_checkpoint_wrapper(cfg) + for block_id, b in enumerate(model.blocks): + model.blocks[block_id] = _checkpointing_wrapper(b) + + +def wrap_compile_block(module: nn.Module, use_cuda_graphs: bool, is_backbone_block: bool) -> nn.Module: + if use_cuda_graphs and is_backbone_block: + module.compile(fullgraph=True, dynamic=False, options={"triton.cudagraphs": True}) + else: + module.compile() + return module + + +def compile_convnext(cfg, model: nn.Module): + assert isinstance(model.stages, nn.ModuleList) + # Compile at stage level + for stage_id, stage in enumerate(model.stages): + model.stages[stage_id] = wrap_compile_block(stage, cfg.train.cudagraphs, is_backbone_block=False) + assert isinstance(model.downsample_layers, nn.ModuleList) + for dsl_id, dsl in enumerate(model.downsample_layers): + model.downsample_layers[dsl_id] = wrap_compile_block(dsl, cfg.train.cudagraphs, is_backbone_block=False) + + +def compile_transformer(cfg, model: nn.Module): + assert isinstance(model.blocks, nn.ModuleList) + for block_id, block in enumerate(model.blocks): + model.blocks[block_id] = wrap_compile_block(block, cfg.train.cudagraphs, is_backbone_block=True) + + +def fsdp_convnext(fsdp_config: Dict[str, Any], model: nn.Module): + stages = model.stages + assert isinstance(stages, nn.ModuleList) + # FSDP wrap at stage level + for stage_id, stage in enumerate(stages): + stage_reshard: int | bool = True + stages[stage_id] = fully_shard(stage, **fsdp_config, reshard_after_forward=stage_reshard) + downsample_layers = model.downsample_layers + assert isinstance(downsample_layers, nn.ModuleList) + for dsl_id, dsl in enumerate(downsample_layers): + dsl_reshard: int | bool = True + downsample_layers[dsl_id] = fully_shard(dsl, **fsdp_config, reshard_after_forward=dsl_reshard) + dsl: FSDPState + stage: FSDPState + for dsl, stage in zip(downsample_layers, stages): + dsl.set_modules_to_forward_prefetch([stage]) + stage.set_modules_to_backward_prefetch([dsl]) + fully_shard(model, **fsdp_config, reshard_after_forward=True) + register_fsdp_forward_method(model, "get_intermediate_layers") + + +def fsdp_transformer(fsdp_config: Dict[str, Any], model: nn.Module): + # Backbone - FSDP every block + blocks = model.blocks + assert isinstance(blocks, nn.ModuleList) + for block_id, block in enumerate(blocks): + block_reshard: int | bool = True + blocks[block_id] = fully_shard(block, **fsdp_config, reshard_after_forward=block_reshard) + prev_block: FSDPState + next_block: FSDPState + for prev_block, next_block in zip(blocks, blocks[1:]): + prev_block.set_modules_to_forward_prefetch([next_block]) + next_block.set_modules_to_backward_prefetch([prev_block]) + fully_shard(model, **fsdp_config, reshard_after_forward=True) + register_fsdp_forward_method(model, "get_intermediate_layers") + + +def ac_compile_parallelize( + trained_model: nn.ModuleDict, + inference_only_models: List[nn.ModuleDict], + cfg: Any, + trained_model_process_group: dist.ProcessGroup | None = None, + inference_only_models_process_groups: List[dist.ProcessGroup] | None = None, +) -> None: + """ + Order of the wrappers: + 1/ Activation checkpointing on blocks + 2/ Compile blocks + 3/ FSDP blocks + global model + """ + assert ( + isinstance(trained_model, nn.ModuleDict) and "backbone" in trained_model.keys() + ), f"{trained_model} does not contain a backbone?" + logger.info("DISTRIBUTED FSDP -- preparing model for distributed training") + if utils.has_batchnorms(trained_model): + raise NotImplementedError + + from dinov3.models.convnext import ConvNeXt + from dinov3.models.vision_transformer import DinoVisionTransformer + + # FSDP utils for each architecture type + ARCH_TYPE_MAP = { + ConvNeXt: dict( + compile_fn=compile_convnext, + fsdp_fn=fsdp_convnext, + activation_checkpointing_fn=activation_checkpoint_convnext, + ), + DinoVisionTransformer: dict( + compile_fn=compile_transformer, + fsdp_fn=fsdp_transformer, + activation_checkpointing_fn=activation_checkpoint_transformer, + ), + } + + # 1/ AC on blocks + if cfg.train.checkpointing: + ARCH_TYPE_MAP[type(trained_model.backbone)]["activation_checkpointing_fn"](cfg, trained_model["backbone"]) + # 2/ Compile blocks + all_models = [trained_model] + inference_only_models + if trained_model_process_group is None and inference_only_models_process_groups is None: + all_pgs = [None] * len(all_models) + elif trained_model_process_group is None: + all_pgs = [None] + inference_only_models_process_groups + elif inference_only_models_process_groups is None: + all_pgs = [trained_model_process_group] + [None] * len(inference_only_models_process_groups) + else: + all_pgs = [trained_model_process_group] + inference_only_models_process_groups + if cfg.train.compile: + for model in all_models: + for k in model.keys(): + if k == "backbone": + ARCH_TYPE_MAP[type(model[k])]["compile_fn"](cfg, model[k]) + else: + model[k] = wrap_compile_block(model[k], use_cuda_graphs=False, is_backbone_block=False) + DTYPE_MAP = { + "fp16": torch.float16, + "bf16": torch.bfloat16, + "fp32": torch.float32, + } + mp_policy = MixedPrecisionPolicy( + param_dtype=DTYPE_MAP[cfg.compute_precision.param_dtype], + reduce_dtype=DTYPE_MAP[cfg.compute_precision.reduce_dtype], + ) + for model, pg in zip(all_models, all_pgs): + if pg is None: + world_mesh = init_device_mesh( + "cuda", + mesh_shape=(dist.get_world_size(),), + mesh_dim_names=("dp",), + ) + else: + world_mesh = DeviceMesh.from_group(pg, "cuda") + fsdp_config = {"mesh": world_mesh, "mp_policy": mp_policy} + for k in model.keys(): + if k == "backbone": + ARCH_TYPE_MAP[type(model[k])]["fsdp_fn"](fsdp_config, model[k]) + else: + model[k] = fully_shard(model[k], **fsdp_config, reshard_after_forward=True) + + # 4/ Move to `cuda` device + for model in all_models: + model.to_empty(device="cuda") + + # 5/ FSDP2: Reshard immediately after forward for inference-only models + for model in inference_only_models: + for k in model.keys(): + fsdp_state: FSDPState = model[k]._get_fsdp_state() + if not fsdp_state._fsdp_param_group: + continue + mi = fsdp_state._fsdp_param_group.post_forward_mesh_info + fsdp_state._lazy_init() + fsdp_state._fsdp_param_group.post_forward_mesh_info = mi diff --git a/starVLA/dinov3/dinov3/hub/__init__.py b/starVLA/dinov3/dinov3/hub/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dinov3/dinov3/hub/backbones.py b/starVLA/dinov3/dinov3/hub/backbones.py new file mode 100644 index 0000000000000000000000000000000000000000..b81e8ea7f308091060091710ed5bc688b6250f98 --- /dev/null +++ b/starVLA/dinov3/dinov3/hub/backbones.py @@ -0,0 +1,612 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import os +from enum import Enum +from typing import List, Optional, Union +from urllib.parse import urlparse +from pathlib import Path + +from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url + + +class Weights(Enum): + LVD1689M = "LVD1689M" + SAT493M = "SAT493M" + + +def is_url(path: str) -> bool: + parsed = urlparse(path) + return parsed.scheme in ("https", "file") + + +def convert_path_or_url_to_url(path: str) -> str: + if is_url(path): + return path + return Path(path).expanduser().resolve().as_uri() + + +def _make_dinov3_vit_model_arch( + *, + patch_size: int = 16, + compact_arch_name: str = "vitb", +): + if "plus" in compact_arch_name: + model_arch = compact_arch_name.replace("plus", f"{patch_size}plus") + else: + model_arch = f"{compact_arch_name}{patch_size}" + return model_arch + + +def _make_dinov3_vit_model_url( + *, + patch_size: int = 16, + compact_arch_name: str = "vitb", + version: Optional[str] = None, + weights: Union[Weights, str] = Weights.LVD1689M, + hash: Optional[str] = None, +): + model_name = "dinov3" + model_arch = _make_dinov3_vit_model_arch(patch_size=patch_size, compact_arch_name=compact_arch_name) + version_suffix = f"_{version}" if version else "" + weights_name = weights.value.lower() + hash_suffix = f"-{hash}" if hash else "" + model_dir = f"{model_name}_{model_arch}" + model_filename = f"{model_name}_{model_arch}_pretrain_{weights_name}{version_suffix}{hash_suffix}.pth" + return os.path.join(_DINOV3_BASE_URL, model_dir, model_filename) + + +def _make_dinov3_vit( + *, + img_size: int = 224, + patch_size: int = 16, + in_chans: int = 3, + compact_arch_name: str = "vitb", + pos_embed_rope_base: float = 100.0, + pos_embed_rope_min_period: float | None = None, + pos_embed_rope_max_period: float | None = None, + pos_embed_rope_normalize_coords: str = "separate", + pos_embed_rope_shift_coords: float | None = None, + pos_embed_rope_jitter_coords: float | None = None, + pos_embed_rope_rescale_coords: float | None = None, + pos_embed_rope_dtype: str = "fp32", + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + ffn_ratio: float = 4.0, + qkv_bias: bool = True, + drop_path_rate: float = 0.0, + layerscale_init: float | None = None, + norm_layer: str = "layernorm", + ffn_layer: str = "mlp", + ffn_bias: bool = True, + proj_bias: bool = True, + n_storage_tokens: int = 0, + mask_k_bias: bool = False, + pretrained: bool = True, + version: Optional[str] = None, + weights: Union[Weights, str] = Weights.LVD1689M, + hash: Optional[str] = None, + check_hash: bool = False, + **kwargs, +): + from ..models.vision_transformer import DinoVisionTransformer + + vit_kwargs = dict( + img_size=img_size, + patch_size=patch_size, + in_chans=in_chans, + pos_embed_rope_base=pos_embed_rope_base, + pos_embed_rope_min_period=pos_embed_rope_min_period, + pos_embed_rope_max_period=pos_embed_rope_max_period, + pos_embed_rope_normalize_coords=pos_embed_rope_normalize_coords, + pos_embed_rope_shift_coords=pos_embed_rope_shift_coords, + pos_embed_rope_jitter_coords=pos_embed_rope_jitter_coords, + pos_embed_rope_rescale_coords=pos_embed_rope_rescale_coords, + pos_embed_rope_dtype=pos_embed_rope_dtype, + embed_dim=embed_dim, + depth=depth, + num_heads=num_heads, + ffn_ratio=ffn_ratio, + qkv_bias=qkv_bias, + drop_path_rate=drop_path_rate, + layerscale_init=layerscale_init, + norm_layer=norm_layer, + ffn_layer=ffn_layer, + ffn_bias=ffn_bias, + proj_bias=proj_bias, + n_storage_tokens=n_storage_tokens, + mask_k_bias=mask_k_bias, + ) + vit_kwargs.update(**kwargs) + model = DinoVisionTransformer(**vit_kwargs) + if pretrained: + if type(weights) is Weights and weights not in {Weights.LVD1689M, Weights.SAT493M}: + raise ValueError(f"Unsupported weights for the backbone: {weights}") + elif type(weights) is Weights: + url = _make_dinov3_vit_model_url( + patch_size=patch_size, + compact_arch_name=compact_arch_name, + version=version, + weights=weights, + hash=hash, + ) + else: + url = convert_path_or_url_to_url(weights) + state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash) + model.load_state_dict(state_dict, strict=True) + else: + model.init_weights() + return model + + +def _make_dinov3_convnext_model_url( + *, + compact_arch_name: str = "convnext_base", + weights: Union[Weights, str] = Weights.LVD1689M, + hash: Optional[str] = None, +): + model_name = "dinov3" + weights_name = weights.value.lower() + hash_suffix = f"-{hash}" if hash else "" + + model_dir = f"{model_name}_{compact_arch_name}" + model_filename = f"{model_name}_{compact_arch_name}_pretrain_{weights_name}{hash_suffix}.pth" + return os.path.join(_DINOV3_BASE_URL, model_dir, model_filename) + + +def _make_dinov3_convnext( + in_chans: int = 3, + depths: List[int] = [3, 3, 27, 3], + dims: List[int] = [128, 256, 512, 1024], + compact_arch_name: str = "convnext_base", + drop_path_rate: float = 0.0, + layer_scale_init_value: float = 1e-6, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + hash: Optional[str] = None, + **kwargs, +): + from ..models.convnext import ConvNeXt + + model_kwargs = dict( + in_chans=in_chans, + depths=depths, + dims=dims, + drop_path_rate=drop_path_rate, + layer_scale_init_value=layer_scale_init_value, + ) + model_kwargs.update(**kwargs) + model = ConvNeXt(**model_kwargs) + if pretrained: + if type(weights) is Weights and weights not in {Weights.LVD1689M, Weights.SAT493M}: + raise ValueError(f"Unsupported weights for the backbone: {weights}") + elif type(weights) is Weights: + url = _make_dinov3_convnext_model_url( + compact_arch_name=compact_arch_name, + weights=weights, + hash=hash, + ) + else: + url = convert_path_or_url_to_url(weights) + state_dict = _safe_load_state_dict_from_url(url, map_location="cpu") + model.load_state_dict(state_dict, strict=True) + return model + + +def dinov3_vits16( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + if "hash" not in kwargs: + kwargs["hash"] = "08c60483" + kwargs["version"] = None + return _make_dinov3_vit( + img_size=224, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=384, + depth=12, + num_heads=6, + ffn_ratio=4, + qkv_bias=True, + drop_path_rate=0.0, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="mlp", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, + pretrained=pretrained, + weights=weights, + compact_arch_name="vits", + check_hash=check_hash, + **kwargs, + ) + + +def dinov3_vits16plus( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + if "hash" not in kwargs: + kwargs["hash"] = "4057cbaa" + kwargs["version"] = None + return _make_dinov3_vit( + img_size=224, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=384, + depth=12, + num_heads=6, + ffn_ratio=6, + qkv_bias=True, + drop_path_rate=0.0, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="swiglu", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, + pretrained=pretrained, + weights=weights, + compact_arch_name="vitsplus", + check_hash=check_hash, + **kwargs, + ) + + +def dinov3_vitb16( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + if "hash" not in kwargs: + kwargs["hash"] = "73cec8be" + kwargs["version"] = None + return _make_dinov3_vit( + img_size=224, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=768, + depth=12, + num_heads=12, + ffn_ratio=4, + qkv_bias=True, + drop_path_rate=0.0, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="mlp", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, + pretrained=pretrained, + weights=weights, + compact_arch_name="vitb", + check_hash=check_hash, + **kwargs, + ) + + +def dinov3_vitl16( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + untie_global_and_local_cls_norm = False + if weights == Weights.LVD1689M: + if "hash" not in kwargs: + kwargs["hash"] = "8aa4cbdd" + elif weights == Weights.SAT493M: + if "hash" not in kwargs: + kwargs["hash"] = "eadcf0ff" + untie_global_and_local_cls_norm = True + elif type(weights) is str: + import re + + pattern = r"-(.{8}).pth" + matches = re.findall(pattern, weights) + if len(matches) != 1: + raise ValueError(f"Unexpected weights specification for the ViT-L backbone: {weights}") + hash = matches[0] + if hash == "eadcf0ff": + untie_global_and_local_cls_norm = True + kwargs["version"] = None + return _make_dinov3_vit( + img_size=224, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=1024, + depth=24, + num_heads=16, + ffn_ratio=4, + qkv_bias=True, + drop_path_rate=0.0, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="mlp", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, + untie_global_and_local_cls_norm=untie_global_and_local_cls_norm, + pretrained=pretrained, + weights=weights, + compact_arch_name="vitl", + check_hash=check_hash, + **kwargs, + ) + + +def dinov3_vitl16plus( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + if "hash" not in kwargs: + kwargs["hash"] = "46503df0" + + return _make_dinov3_vit( + img_size=224, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=1024, + depth=24, + num_heads=16, + ffn_ratio=6.0, + qkv_bias=True, + drop_path_rate=0.0, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="swiglu", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, + pretrained=pretrained, + weights=weights, + compact_arch_name="vitlplus", + check_hash=check_hash, + **kwargs, + ) + + +def dinov3_vith16plus( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + if "hash" not in kwargs: + kwargs["hash"] = "7c1da9a5" + + return _make_dinov3_vit( + img_size=224, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=1280, + depth=32, + num_heads=20, + ffn_ratio=6.0, + qkv_bias=True, + drop_path_rate=0.0, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="swiglu", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, + pretrained=pretrained, + weights=weights, + compact_arch_name="vithplus", + check_hash=check_hash, + **kwargs, + ) + + +def dinov3_vit7b16( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + if weights == Weights.LVD1689M: + if "hash" not in kwargs: + kwargs["hash"] = "a955f4ea" + elif weights == Weights.SAT493M: + if "hash" not in kwargs: + kwargs["hash"] = "a6675841" + kwargs["version"] = None + untie_global_and_local_cls_norm = True + return _make_dinov3_vit( + img_size=224, + patch_size=16, + in_chans=3, + pos_embed_rope_base=100, + pos_embed_rope_normalize_coords="separate", + pos_embed_rope_rescale_coords=2, + pos_embed_rope_dtype="fp32", + embed_dim=4096, + depth=40, + num_heads=32, + ffn_ratio=3, + qkv_bias=False, + drop_path_rate=0.0, + layerscale_init=1.0e-05, + norm_layer="layernormbf16", + ffn_layer="swiglu64", + ffn_bias=True, + proj_bias=True, + n_storage_tokens=4, + mask_k_bias=True, + untie_global_and_local_cls_norm=untie_global_and_local_cls_norm, + pretrained=pretrained, + weights=weights, + compact_arch_name="vit7b", + check_hash=check_hash, + **kwargs, + ) + + +def dinov3_convnext_tiny( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + **kwargs, +): + _hash_convnext = "21b726bb" + if "hash" not in kwargs: + kwargs["hash"] = _hash_convnext + + from ..models.convnext import convnext_sizes + + size_dict = convnext_sizes["tiny"] + + model = _make_dinov3_convnext( + in_chans=3, + depths=size_dict["depths"], + dims=size_dict["dims"], + compact_arch_name="convnext_tiny", + drop_path_rate=0, + layer_scale_init_value=1e-6, + pretrained=pretrained, + weights=weights, + **kwargs, + ) + if not pretrained: + model.init_weights() + return model + + +def dinov3_convnext_small( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + **kwargs, +): + _hash_convnext = "296db49d" + if "hash" not in kwargs: + kwargs["hash"] = _hash_convnext + + from ..models.convnext import convnext_sizes + + size_dict = convnext_sizes["small"] + + model = _make_dinov3_convnext( + in_chans=3, + depths=size_dict["depths"], + dims=size_dict["dims"], + compact_arch_name="convnext_small", + drop_path_rate=0, + layer_scale_init_value=1e-6, + pretrained=pretrained, + weights=weights, + **kwargs, + ) + if not pretrained: + model.init_weights() + return model + + +def dinov3_convnext_base( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + **kwargs, +): + _hash_convnext = "801f2ba9" + if "hash" not in kwargs: + kwargs["hash"] = _hash_convnext + + from ..models.convnext import convnext_sizes + + size_dict = convnext_sizes["base"] + + model = _make_dinov3_convnext( + in_chans=3, + depths=size_dict["depths"], + dims=size_dict["dims"], + compact_arch_name="convnext_base", + drop_path_rate=0, + layer_scale_init_value=1e-6, + pretrained=pretrained, + weights=weights, + **kwargs, + ) + if not pretrained: + model.init_weights() + return model + + +def dinov3_convnext_large( + *, + pretrained: bool = True, + weights: Union[Weights, str] = Weights.LVD1689M, + **kwargs, +): + _hash_convnext = "61fa432d" + if "hash" not in kwargs: + kwargs["hash"] = _hash_convnext + + from ..models.convnext import convnext_sizes + + size_dict = convnext_sizes["large"] + + model = _make_dinov3_convnext( + in_chans=3, + depths=size_dict["depths"], + dims=size_dict["dims"], + compact_arch_name="convnext_large", + drop_path_rate=0, + layer_scale_init_value=1e-6, + pretrained=pretrained, + weights=weights, + **kwargs, + ) + if not pretrained: + model.init_weights() + return model diff --git a/starVLA/dinov3/dinov3/hub/classifiers.py b/starVLA/dinov3/dinov3/hub/classifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..ab53b3f4a18082782ed9e2bbaaa5579aa459e9e6 --- /dev/null +++ b/starVLA/dinov3/dinov3/hub/classifiers.py @@ -0,0 +1,113 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import os +from enum import Enum + +import torch +import torch.nn as nn + +from .backbones import ( + dinov3_vit7b16, + Weights as BackboneWeights, + convert_path_or_url_to_url, +) + +from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url + + +class ClassifierWeights(Enum): + IMAGENET1K = "IMAGENET1K" + + +def _make_dinov3_linear_classification_head( + *, + backbone_name: str = "dinov3_vit7b16", + embed_dim: int = 8192, + pretrained: bool = True, + classifier_weights: ClassifierWeights | str = ClassifierWeights.IMAGENET1K, + check_hash: bool = False, + **kwargs, +): + linear_head = nn.Linear(embed_dim, 1_000) + if pretrained: + if type(classifier_weights) is ClassifierWeights: + assert classifier_weights == ClassifierWeights.IMAGENET1K, ( + f"Unsupported weights for linear classifier: {classifier_weights}" + ) + weights_name = classifier_weights.value.lower() + hash = kwargs["hash"] if "hash" in kwargs else "90d8ed92" + model_filename = f"{backbone_name}_{weights_name}_linear_head-{hash}.pth" + url = os.path.join(_DINOV3_BASE_URL, backbone_name, model_filename) + else: + url = convert_path_or_url_to_url(classifier_weights) + state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash) + linear_head.load_state_dict(state_dict, strict=True) + return linear_head + + +class _LinearClassifierWrapper(nn.Module): + def __init__(self, *, backbone: nn.Module, linear_head: nn.Module): + super().__init__() + self.backbone = backbone + self.linear_head = linear_head + + def forward(self, x): + x = self.backbone.forward_features(x) + cls_token = x["x_norm_clstoken"] + patch_tokens = x["x_norm_patchtokens"] + linear_input = torch.cat( + [ + cls_token, + patch_tokens.mean(dim=1), + ], + dim=1, + ) + return self.linear_head(linear_input) + + +def _make_dinov3_linear_classifier( + *, + backbone_name: str = "dinov3_vit7b16", + pretrained: bool = True, + classifier_weights: ClassifierWeights | str = ClassifierWeights.IMAGENET1K, + backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + if backbone_name == "dinov3_vit7b16": + backbone = dinov3_vit7b16(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash) + else: + raise AssertionError(f"Unsupported backbone: {backbone_name}, linear classifiers are provided only for ViT-7b") + embed_dim = backbone.embed_dim + linear_head = _make_dinov3_linear_classification_head( + backbone_name=backbone_name, + embed_dim=2 * embed_dim, + pretrained=pretrained, + classifier_weights=classifier_weights, + **kwargs, + ) + return _LinearClassifierWrapper(backbone=backbone, linear_head=linear_head) + + +def dinov3_vit7b16_lc( + *, + pretrained: bool = True, + weights: ClassifierWeights | str = ClassifierWeights.IMAGENET1K, + backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + """ + Linear classifier on top of a DINOv3 ViT-7B/16 backbone pretrained on the LVD-1689M dataset and trained on ImageNet-1k. + """ + return _make_dinov3_linear_classifier( + backbone_name="dinov3_vit7b16", + pretrained=pretrained, + classifier_weights=weights, + backbone_weights=backbone_weights, + check_hash=check_hash, + **kwargs, + ) diff --git a/starVLA/dinov3/dinov3/hub/depthers.py b/starVLA/dinov3/dinov3/hub/depthers.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0ad5eb8cfdf234c51705cb8f4570505201c214 --- /dev/null +++ b/starVLA/dinov3/dinov3/hub/depthers.py @@ -0,0 +1,197 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from enum import Enum +from typing import Optional, Tuple + +import torch +from dinov3.eval.depth.models import DecoderConfig, make_depther_from_config + +from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url +from .backbones import ( + Weights as BackboneWeights, + dinov3_vitl16, + dinov3_vit7b16, + convert_path_or_url_to_url, +) + + +class DepthWeights(Enum): + CHMV2 = "CHMV2" + SYNTHMIX = "SYNTHMIX" + + +def _get_depth_range(dataset: DepthWeights): + depth_ranges = { + DepthWeights.SYNTHMIX: (0.001, 100.0), + } + return depth_ranges[dataset] + + +_DPT_HEAD_CONFIG_DICT = dict( + use_backbone_norm=True, + use_batchnorm=True, + use_cls_token=False, + n_output_channels=256, + depth_weights=DepthWeights.SYNTHMIX, + backbone_weights=BackboneWeights.LVD1689M, +) + + +def _get_out_layers(backbone_name): + if "vitl" in backbone_name: + return [4, 11, 17, 23] + elif "vit7b" in backbone_name: + return [9, 19, 29, 39] + else: + raise ValueError(f"Unrecognized backbone name {backbone_name}") + + +def _get_post_process_channels(backbone_name): + if "vitl" in backbone_name: + return [1024, 1024, 1024, 1024] + elif "vit7b" in backbone_name: + return [2048, 2048, 2048, 2048] + + +_BACKBONE_DICT = { + "dinov3_vit7b16": dinov3_vit7b16, + "dinov3_vitl16": dinov3_vitl16, +} + + +def _get_depther_config( + backbone_name: str = "dinov3_vit7b16", + depth_range: Optional[Tuple[float, float]] = None, + **kwargs, +): + out_index = _get_out_layers(backbone_name) + post_process_channels = _get_post_process_channels(backbone_name) + + depth_range = depth_range or _get_depth_range(DepthWeights(_DPT_HEAD_CONFIG_DICT["depth_weights"])) + min_depth, max_depth = depth_range + depther_config = DecoderConfig( + min_depth=min_depth, + max_depth=max_depth, + backbone_out_layers=out_index, + n_output_channels=_DPT_HEAD_CONFIG_DICT["n_output_channels"], # type: ignore + use_backbone_norm=bool(_DPT_HEAD_CONFIG_DICT["use_backbone_norm"]), + use_batchnorm=bool(_DPT_HEAD_CONFIG_DICT["use_batchnorm"]), + use_cls_token=bool(_DPT_HEAD_CONFIG_DICT["use_cls_token"]), + type="dpt", + # DPTHead args + head_kwargs=dict( + channels=512, + post_process_channels=post_process_channels, + ), + **kwargs, + ) + return depther_config + + +def _make_dinov3_dpt_depther( + *, + backbone_name: str = "dinov3_vit7b16", + pretrained: bool = True, + depther_weights: DepthWeights | str = DepthWeights.SYNTHMIX, + backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M, + depth_range: Optional[Tuple[float, float]] = None, + check_hash: bool = False, + autocast_dtype: torch.dtype = torch.float32, + **kwargs, +): + backbone: torch.nn.Module = _BACKBONE_DICT[backbone_name]( + pretrained=pretrained, + weights=backbone_weights, + ) + + depther = make_depther_from_config( + backbone, + config=_get_depther_config(backbone_name, depth_range), + autocast_dtype=autocast_dtype, + ) + + if pretrained: + if isinstance(depther_weights, DepthWeights): + assert depther_weights == DepthWeights.SYNTHMIX, f"Unsupported depther weights {depther_weights}" + weights_name = depther_weights.value.lower() + hash = kwargs["hash"] if "hash" in kwargs else "02040be1" + url = _DINOV3_BASE_URL + f"/{backbone_name}/{backbone_name}_{weights_name}_dpt_head-{hash}.pth" + else: + url = convert_path_or_url_to_url(depther_weights) + checkpoint = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash) + depther.decoder.load_state_dict(checkpoint, strict=True) + return depther + + +def dinov3_vit7b16_dd( + *, + pretrained: bool = True, + weights: DepthWeights | str = DepthWeights.SYNTHMIX, + backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M, + check_hash: bool = False, + autocast_dtype: torch.dtype = torch.float32, + **kwargs, +): + return _make_dinov3_dpt_depther( + backbone_name="dinov3_vit7b16", + pretrained=pretrained, + depther_weights=weights, + backbone_weights=backbone_weights, + check_hash=check_hash, + autocast_dtype=autocast_dtype, + **kwargs, + ) + + +def _get_chmv2_config( + **kwargs, +): + return DecoderConfig( + min_depth=0.001, + max_depth=96.0, + backbone_out_layers=[5, 11, 17, 23], + n_output_channels=256, + use_backbone_norm=True, + use_batchnorm=False, + use_cls_token=True, + type="dpt", + bins_strategy="chmv2_mixlog", + norm_strategy="chmv2_mixlog", + head_kwargs={ + "n_hidden_channels": 128, + "use_bias": True, + "projection_after_fusion": False, + }, + **kwargs, + ) + + +def dinov3_vitl16_chmv2( + pretrained: bool = True, + weights: DepthWeights | str = DepthWeights.CHMV2, + backbone_weights: BackboneWeights | str = BackboneWeights.SAT493M, + check_hash: bool = False, + autocast_dtype: torch.dtype = torch.float32, + **kwargs, +): + backbone: torch.nn.Module = dinov3_vitl16(pretrained=pretrained, weights=backbone_weights) + + chmv2_depther = make_depther_from_config( + backbone, + config=_get_chmv2_config(), + autocast_dtype=autocast_dtype, + ) + + if pretrained: + if isinstance(weights, DepthWeights): + assert weights == DepthWeights.CHMV2, f"Unsupported chmv2 weights {weights}" + weights_name = weights.value.lower() + url = _DINOV3_BASE_URL + f"/chmv2/dinov3_vitl16_{weights_name}_dpt_head-3703d643.pth" + else: + url = convert_path_or_url_to_url(weights) + checkpoint = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash) + chmv2_depther.decoder.load_state_dict(checkpoint, strict=True) + return chmv2_depther diff --git a/starVLA/dinov3/dinov3/hub/detectors.py b/starVLA/dinov3/dinov3/hub/detectors.py new file mode 100644 index 0000000000000000000000000000000000000000..019ba2a994ade074789106a93232ab0ef1986b44 --- /dev/null +++ b/starVLA/dinov3/dinov3/hub/detectors.py @@ -0,0 +1,132 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import os +from enum import Enum + +import torch + +from dinov3.eval.detection.config import DetectionHeadConfig +from dinov3.eval.detection.models.detr import PostProcess, build_model +from dinov3.eval.detection.models.position_encoding import PositionEncoding + +from .backbones import Weights as BackboneWeights, dinov3_vit7b16, dinov3_vitl16plus, convert_path_or_url_to_url +from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url + + +class DetectionWeights(Enum): + COCO2017 = "COCO2017" + + +class DetectorWithProcessor(torch.nn.Module): + """ + takes as input a list of (3, H, W) normalized image tensors and outputs + a list of dicts with keys "scores", "labels" and "boxes" (format XYXY) + """ + + def __init__(self, detector, postprocessor): + super().__init__() + self.detector = detector + self.postprocessor = postprocessor + + def forward(self, samples: list[torch.Tensor]): + outputs = self.detector(samples) + sizes_tensor = torch.tensor([sample.shape[1:] for sample in samples], device=samples[0].device) # N * [3, H, W] + return self.postprocessor(outputs, target_sizes=sizes_tensor, original_target_sizes=sizes_tensor) + + +def _make_dinov3_detector( + *, + backbone_name: str, + pretrained: bool = True, + detector_weights: str | DetectionWeights, + backbone_weights: str | BackboneWeights, + check_hash: bool = False, + **kwargs, +): + detection_kwargs = dict( + with_box_refine=True, + two_stage=True, + mixed_selection=True, + look_forward_twice=True, + k_one2many=6, + lambda_one2many=1.0, + num_queries_one2one=1500, + num_queries_one2many=1500, + reparam=True, + position_embedding=PositionEncoding.SINE, + num_feature_levels=1, + dec_layers=6, + dim_feedforward=2048, + dropout=0.0, + norm_type="pre_norm", + proposal_feature_levels=4, + proposal_min_size=50, + decoder_type="global_rpe_decomp", + decoder_use_checkpoint=False, + decoder_rpe_hidden_dim=512, + decoder_rpe_type="linear", + layers_to_use=None, + blocks_to_train=None, + add_transformer_encoder=True, + num_encoder_layers=6, + backbone_use_layernorm=False, + num_classes=91, # 91 classes in COCO + aux_loss=True, + topk=1500, + hidden_dim=768, + nheads=8, + ) + config = DetectionHeadConfig(**detection_kwargs) + backbone_class = dict(dinov3_vit7b16=dinov3_vit7b16, dinov3_vitl16plus=dinov3_vitl16plus)[backbone_name] + n_windows_sqrt = dict(dinov3_vit7b16=3, dinov3_vitl16plus=2)[backbone_name] + backbone = backbone_class(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash) + backbone.eval() + + config.n_windows_sqrt = n_windows_sqrt + config.proposal_in_stride = backbone.patch_size + config.proposal_tgt_strides = [int(m * backbone.patch_size) for m in (0.5, 1, 2, 4)] + + if config.layers_to_use is None: + # e.g. [2, 5, 8, 11] for a backbone with 12 blocks, similar to depth evaluation + config.layers_to_use = [m * backbone.n_blocks // 4 - 1 for m in range(1, 5)] + + detector = build_model(backbone, config) + if pretrained: + if type(detector_weights) is DetectionWeights and detector_weights == DetectionWeights.COCO2017: + assert detector_weights == DetectionWeights.COCO2017, f"Unsupported detector weights {detector_weights}" + detection_weights_name = detector_weights.value.lower() + hash = kwargs["hash"] if "hash" in kwargs else "b0235ff7" + model_filename = f"{backbone_name}_{detection_weights_name}_detr_head-{hash}.pth" + url = os.path.join(_DINOV3_BASE_URL, backbone_name, model_filename) + else: + url = convert_path_or_url_to_url(detector_weights) + state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)["model"] + detector.load_state_dict(state_dict, strict=False) + # Necessary for inference + detector.num_queries = detector.num_queries_one2one + detector.transformer.two_stage_num_proposals = detector.num_queries + + postprocessor = PostProcess(config.topk, config.reparam) + model = DetectorWithProcessor(detector=detector, postprocessor=postprocessor) + return model + + +def dinov3_vit7b16_de( + *, + pretrained: bool = True, + weights: DetectionWeights | str = DetectionWeights.COCO2017, + backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M, + check_hash: bool = False, + **kwargs, +): + return _make_dinov3_detector( + backbone_name="dinov3_vit7b16", + pretrained=pretrained, + detector_weights=weights, + backbone_weights=backbone_weights, + check_hash=check_hash, + **kwargs, + ) diff --git a/starVLA/dinov3/dinov3/hub/dinotxt.py b/starVLA/dinov3/dinov3/hub/dinotxt.py new file mode 100644 index 0000000000000000000000000000000000000000..58eca2ef701a468044fdbbc4ad933d40f72af3d6 --- /dev/null +++ b/starVLA/dinov3/dinov3/hub/dinotxt.py @@ -0,0 +1,83 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import math +from typing import Any, Tuple, Union +from enum import Enum + +from torch import nn + +from .backbones import dinov3_vitl16, Weights as BackboneWeights, convert_path_or_url_to_url +from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url + + +class DINOTxtWeights(Enum): + LVTD2300M = "LVTD2300M" + + +# returns dinotxt model and tokenizer +def dinov3_vitl16_dinotxt_tet1280d20h24l( + *, + pretrained: bool = True, + weights: Union[DINOTxtWeights, str] = DINOTxtWeights.LVTD2300M, + backbone_weights: Union[BackboneWeights, str] = BackboneWeights.LVD1689M, + bpe_path_or_url: str = "https://dl.fbaipublicfiles.com/dinov3/thirdparty/bpe_simple_vocab_16e6.txt.gz", + check_hash: bool = False, +) -> Tuple[nn.Module, Any]: + from dinov3.eval.text.dinotxt_model import DINOTxt, DINOTxtConfig + from dinov3.eval.text.text_transformer import TextTransformer + from dinov3.eval.text.tokenizer import get_tokenizer + + dinotxt_config = DINOTxtConfig( + embed_dim=2048, + vision_model_freeze_backbone=True, + vision_model_train_img_size=224, + vision_model_use_class_token=True, + vision_model_use_patch_tokens=True, + vision_model_num_head_blocks=2, + vision_model_head_blocks_drop_path=0.3, + vision_model_use_linear_projection=False, + vision_model_patch_tokens_pooler_type="mean", + vision_model_patch_token_layer=1, # which layer to take patch tokens from + # 1 - last layer, 2 - second last layer, etc. + text_model_freeze_backbone=False, + text_model_num_head_blocks=0, + text_model_head_blocks_is_causal=False, + text_model_head_blocks_drop_prob=0.0, + text_model_tokens_pooler_type="argmax", + text_model_use_linear_projection=True, + init_logit_scale=math.log(1 / 0.07), + init_logit_bias=None, + freeze_logit_scale=False, + ) + vision_backbone = dinov3_vitl16(pretrained=pretrained, weights=backbone_weights) + text_backbone = TextTransformer( + context_length=77, + vocab_size=49408, + dim=1280, + num_heads=20, + num_layers=24, + ffn_ratio=4, + is_causal=True, + ls_init_value=None, + dropout_prob=0.0, + ) + model = DINOTxt(model_config=dinotxt_config, vision_backbone=vision_backbone, text_backbone=text_backbone) + if pretrained: + model.visual_model.backbone = vision_backbone + model.eval() + if type(weights) is DINOTxtWeights and weights == DINOTxtWeights.LVTD2300M: + url = f"{_DINOV3_BASE_URL}/dinov3_vitl16/dinov3_vitl16_dinotxt_vision_head_and_text_encoder-a442d8f5.pth" + elif type(weights) is DINOTxtWeights and weights != DINOTxtWeights.LVTD2300M: + raise AssertionError(f"Unsuported weights for DINOTxt: {weights}") + else: + url = convert_path_or_url_to_url(weights) + vision_head_and_text_encoder_state_dict = _safe_load_state_dict_from_url( + url, map_location="cpu", check_hash=check_hash + ) + model.load_state_dict(vision_head_and_text_encoder_state_dict, strict=False) + else: + model.init_weights() + return model, get_tokenizer(bpe_path_or_url=bpe_path_or_url) diff --git a/starVLA/dinov3/dinov3/hub/segmentors.py b/starVLA/dinov3/dinov3/hub/segmentors.py new file mode 100644 index 0000000000000000000000000000000000000000..65013bbad55b4ea2c8403439c58db8d2bd358b99 --- /dev/null +++ b/starVLA/dinov3/dinov3/hub/segmentors.py @@ -0,0 +1,85 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import os +from enum import Enum + +import torch +from dinov3.eval.segmentation.models import build_segmentation_decoder + +from .backbones import ( + dinov3_vit7b16, + dinov3_vitl16, + Weights as BackboneWeights, + convert_path_or_url_to_url, +) +from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url + + +class SegmentorWeights(Enum): + ADE20K = "ADE20K" + + +def _make_dinov3_m2f_segmentor( + *, + backbone_name: str = "dinov3_vit7b16", + pretrained: bool = True, + segmentor_weights: SegmentorWeights | str = SegmentorWeights.ADE20K, + backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M, + check_hash: bool = False, + autocast_dtype: torch.dtype = torch.bfloat16, + **kwargs, +): + if backbone_name == "dinov3_vit7b16": + backbone_model = dinov3_vit7b16(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash) + elif backbone_name == "dinov3_vitl16": + backbone_model = dinov3_vitl16(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash) + else: + raise AssertionError(f"No pretrained segmentation checkpoint available for {backbone_name}") + + hidden_dim = 2048 if "hidden_dim" not in kwargs else kwargs["hidden_dim"] + segmentor = build_segmentation_decoder( + backbone_model=backbone_model, + decoder_type="m2f", + hidden_dim=hidden_dim, + autocast_dtype=autocast_dtype, + ) + if pretrained: + if type(segmentor_weights) is SegmentorWeights: + assert segmentor_weights == SegmentorWeights.ADE20K, ( + f"Unsupported weights for segmentor: {segmentor_weights}" + ) + segmentor_weights_name = segmentor_weights.value.lower() + hash = kwargs["hash"] if "hash" in kwargs else "bf307cb1" + model_filename = f"{backbone_name}_{segmentor_weights_name}_m2f_head-{hash}.pth" + url = os.path.join(_DINOV3_BASE_URL, backbone_name, model_filename) + else: + url = convert_path_or_url_to_url(segmentor_weights) + state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash) + missing_keys, unexpected_keys = segmentor.load_state_dict(state_dict, strict=False) + assert len([k for k in missing_keys if "backbone" not in k]) == 0 + assert len(unexpected_keys) == 0 + + return segmentor + + +def dinov3_vit7b16_ms( + *, + pretrained: bool = True, + weights: SegmentorWeights | str = SegmentorWeights.ADE20K, + backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M, + check_hash: bool = False, + autocast_dtype: torch.dtype = torch.bfloat16, + **kwargs, +): + return _make_dinov3_m2f_segmentor( + backbone_name="dinov3_vit7b16", + pretrained=pretrained, + segmentor_weights=weights, + backbone_weights=backbone_weights, + check_hash=check_hash, + autocast_dtype=autocast_dtype, + **kwargs, + ) diff --git a/starVLA/dinov3/dinov3/hub/utils.py b/starVLA/dinov3/dinov3/hub/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5c82f3217a827106f387b76ca9df3549204a9483 --- /dev/null +++ b/starVLA/dinov3/dinov3/hub/utils.py @@ -0,0 +1,18 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import torch + + +_DINOV3_BASE_URL = "https://dl.fbaipublicfiles.com/dinov3" + + +def _safe_load_state_dict_from_url(url: str, **kwargs): + # See https://github.com/pytorch/pytorch/releases/tag/v2.1.0 (Misc / #98479) + if torch.__version__ >= (2, 1): + local_kwargs = {**kwargs, "weights_only": True} + else: + local_kwargs = kwargs + return torch.hub.load_state_dict_from_url(url, **local_kwargs) diff --git a/starVLA/dinov3/dinov3/layers/__init__.py b/starVLA/dinov3/dinov3/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5b82c261aaba6f0b7b871662f3549062e69928f8 --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from .attention import CausalSelfAttention, LinearKMaskedBias, SelfAttention +from .block import CausalSelfAttentionBlock, SelfAttentionBlock +from .ffn_layers import Mlp, SwiGLUFFN +from .fp8_linear import convert_linears_to_fp8 +from .layer_scale import LayerScale +from .patch_embed import PatchEmbed +from .rms_norm import RMSNorm +from .rope_position_encoding import RopePositionEmbedding diff --git a/starVLA/dinov3/dinov3/layers/attention.py b/starVLA/dinov3/dinov3/layers/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..8335b0176fa7ea15808a558fb2c802e06a9bbf9d --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/attention.py @@ -0,0 +1,164 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import math +from typing import List, Tuple + +import torch +import torch.nn.functional as F +from dinov3.utils import cat_keep_shapes, uncat_with_shapes +from torch import Tensor, nn + + +# RoPE-related functions: +def rope_rotate_half(x: Tensor) -> Tensor: + # x: [ x0 x1 x2 x3 x4 x5] + # out: [-x3 -x4 -x5 x0 x1 x2] + x1, x2 = x.chunk(2, dim=-1) + return torch.cat([-x2, x1], dim=-1) + + +def rope_apply(x: Tensor, sin: Tensor, cos: Tensor) -> Tensor: + # x: [..., D], eg [x0, x1, x2, x3, x4, x5] + # sin: [..., D], eg [sin0, sin1, sin2, sin0, sin1, sin2] + # cos: [..., D], eg [cos0, cos1, cos2, cos0, cos1, cos2] + return (x * cos) + (rope_rotate_half(x) * sin) + + +class LinearKMaskedBias(nn.Linear): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + o = self.out_features + assert o % 3 == 0 + if self.bias is not None: + self.register_buffer("bias_mask", torch.full_like(self.bias, fill_value=math.nan)) + + def forward(self, input: Tensor) -> Tensor: + masked_bias = self.bias * self.bias_mask.to(self.bias.dtype) if self.bias is not None else None + return F.linear(input, self.weight, masked_bias) + + +class SelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + mask_k_bias: bool = False, + device=None, + ) -> None: + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + linear_class = LinearKMaskedBias if mask_k_bias else nn.Linear + self.qkv = linear_class(dim, dim * 3, bias=qkv_bias, device=device) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim, bias=proj_bias, device=device) + self.proj_drop = nn.Dropout(proj_drop) + + def apply_rope(self, q: Tensor, k: Tensor, rope: Tensor | Tuple[Tensor, Tensor]) -> Tuple[Tensor, Tensor]: + # All operations will use the dtype of rope, the output is cast back to the dtype of q and k + q_dtype = q.dtype + k_dtype = k.dtype + sin, cos = rope + rope_dtype = sin.dtype + q = q.to(dtype=rope_dtype) + k = k.to(dtype=rope_dtype) + N = q.shape[-2] + prefix = N - sin.shape[-2] + assert prefix >= 0 + q_prefix = q[:, :, :prefix, :] + q = rope_apply(q[:, :, prefix:, :], sin, cos) # [B, head, hw, D//head] + q = torch.cat((q_prefix, q), dim=-2) # [B, head, N, D//head] + k_prefix = k[:, :, :prefix, :] + k = rope_apply(k[:, :, prefix:, :], sin, cos) # [B, head, hw, D//head] + k = torch.cat((k_prefix, k), dim=-2) # [B, head, N, D//head] + q = q.to(dtype=q_dtype) + k = k.to(dtype=k_dtype) + return q, k + + def forward(self, x: Tensor, attn_bias=None, rope: Tensor = None) -> Tensor: + qkv = self.qkv(x) + attn_v = self.compute_attention(qkv=qkv, attn_bias=attn_bias, rope=rope) + x = self.proj(attn_v) + x = self.proj_drop(x) + return x + + def forward_list(self, x_list, attn_bias=None, rope_list=None) -> List[Tensor]: + assert len(x_list) == len(rope_list) # should be enforced by the Block + x_flat, shapes, num_tokens = cat_keep_shapes(x_list) + qkv_flat = self.qkv(x_flat) + qkv_list = uncat_with_shapes(qkv_flat, shapes, num_tokens) + att_out = [] + for _, (qkv, _, rope) in enumerate(zip(qkv_list, shapes, rope_list)): + att_out.append(self.compute_attention(qkv, attn_bias=attn_bias, rope=rope)) + x_flat, shapes, num_tokens = cat_keep_shapes(att_out) + x_flat = self.proj(x_flat) + return uncat_with_shapes(x_flat, shapes, num_tokens) + + def compute_attention(self, qkv: Tensor, attn_bias=None, rope=None) -> Tensor: + assert attn_bias is None + B, N, _ = qkv.shape + C = self.qkv.in_features + + qkv = qkv.reshape(B, N, 3, self.num_heads, C // self.num_heads) + q, k, v = torch.unbind(qkv, 2) + q, k, v = [t.transpose(1, 2) for t in [q, k, v]] + if rope is not None: + q, k = self.apply_rope(q, k, rope) + x = torch.nn.functional.scaled_dot_product_attention(q, k, v) + x = x.transpose(1, 2) + return x.reshape([B, N, C]) + + +class CausalSelfAttention(nn.Module): + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = False, + proj_bias: bool = True, + attn_drop: float = 0.0, + proj_drop: float = 0.0, + ) -> None: + super().__init__() + self.dim = dim + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = attn_drop + self.proj = nn.Linear(dim, dim, bias=proj_bias) + self.proj_drop = nn.Dropout(proj_drop) + + def init_weights( + self, init_attn_std: float | None = None, init_proj_std: float | None = None, factor: float = 1.0 + ) -> None: + init_attn_std = init_attn_std or (self.dim**-0.5) + init_proj_std = init_proj_std or init_attn_std * factor + nn.init.normal_(self.qkv.weight, std=init_attn_std) + nn.init.normal_(self.proj.weight, std=init_proj_std) + if self.qkv.bias is not None: + nn.init.zeros_(self.qkv.bias) + if self.proj.bias is not None: + nn.init.zeros_(self.proj.bias) + + def forward(self, x: Tensor, is_causal: bool = True) -> Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads) + q, k, v = torch.unbind(qkv, 2) + q, k, v = [t.transpose(1, 2) for t in [q, k, v]] + x = torch.nn.functional.scaled_dot_product_attention( + q, k, v, attn_mask=None, dropout_p=self.attn_drop if self.training else 0, is_causal=is_causal + ) + x = x.transpose(1, 2).contiguous().view(B, N, C) + x = self.proj_drop(self.proj(x)) + return x diff --git a/starVLA/dinov3/dinov3/layers/block.py b/starVLA/dinov3/dinov3/layers/block.py new file mode 100644 index 0000000000000000000000000000000000000000..2051a1a607ab8c10c2476fa9d019225f4ba6ab5b --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/block.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from typing import Callable, List, Optional + +import torch +from torch import Tensor, nn + +from dinov3.utils import cat_keep_shapes, uncat_with_shapes + +from .attention import CausalSelfAttention, SelfAttention +from .ffn_layers import Mlp +from .layer_scale import LayerScale # , DropPath + +torch._dynamo.config.automatic_dynamic_shapes = False +torch._dynamo.config.accumulated_cache_size_limit = 1024 + + +class SelfAttentionBlock(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + ffn_ratio: float = 4.0, + qkv_bias: bool = False, + proj_bias: bool = True, + ffn_bias: bool = True, + drop: float = 0.0, + attn_drop: float = 0.0, + init_values=None, + drop_path: float = 0.0, + act_layer: Callable[..., nn.Module] = nn.GELU, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_class: Callable[..., nn.Module] = SelfAttention, + ffn_layer: Callable[..., nn.Module] = Mlp, + mask_k_bias: bool = False, + device=None, + ) -> None: + super().__init__() + # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}") + self.norm1 = norm_layer(dim) + self.attn = attn_class( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attn_drop=attn_drop, + proj_drop=drop, + mask_k_bias=mask_k_bias, + device=device, + ) + self.ls1 = LayerScale(dim, init_values=init_values, device=device) if init_values else nn.Identity() + + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * ffn_ratio) + self.mlp = ffn_layer( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + bias=ffn_bias, + device=device, + ) + self.ls2 = LayerScale(dim, init_values=init_values, device=device) if init_values else nn.Identity() + + self.sample_drop_ratio = drop_path + + @staticmethod + def _maybe_index_rope(rope: tuple[Tensor, Tensor] | None, indices: Tensor) -> tuple[Tensor, Tensor] | None: + if rope is None: + return None + + sin, cos = rope + assert sin.ndim == cos.ndim + if sin.ndim == 4: + # If the rope embedding has a batch dimension (is different for each batch element), index into it + return sin[indices], cos[indices] # [batch, heads, patches, embed_dim] + else: + # No batch dimension, do not index + return sin, cos # [heads, patches, embed_dim] or [patches, embed_dim] + + def _forward(self, x: Tensor, rope=None) -> Tensor: + """ + This is the reference implementation for a single tensor, matching what is done below for a list. + We call the list op on [x] instead of this function. + """ + b, _, _ = x.shape + sample_subset_size = max(int(b * (1 - self.sample_drop_ratio)), 1) + residual_scale_factor = b / sample_subset_size + + if self.training and self.sample_drop_ratio > 0.0: + indices_1 = (torch.randperm(b, device=x.device))[:sample_subset_size] + + x_subset_1 = x[indices_1] + rope_subset = self._maybe_index_rope(rope, indices_1) + residual_1 = self.attn(self.norm1(x_subset_1), rope=rope_subset) + + x_attn = torch.index_add( + x, + dim=0, + source=self.ls1(residual_1), + index=indices_1, + alpha=residual_scale_factor, + ) + + indices_2 = (torch.randperm(b, device=x.device))[:sample_subset_size] + + x_subset_2 = x_attn[indices_2] + residual_2 = self.mlp(self.norm2(x_subset_2)) + + x_ffn = torch.index_add( + x_attn, + dim=0, + source=self.ls2(residual_2), + index=indices_2, + alpha=residual_scale_factor, + ) + else: + x_attn = x + self.ls1(self.attn(self.norm1(x), rope=rope)) + x_ffn = x_attn + self.ls2(self.mlp(self.norm2(x_attn))) + + return x_ffn + + def _forward_list(self, x_list: List[Tensor], rope_list=None) -> List[Tensor]: + """ + This list operator concatenates the tokens from the list of inputs together to save + on the elementwise operations. Torch-compile memory-planning allows hiding the overhead + related to concat ops. + """ + b_list = [x.shape[0] for x in x_list] + sample_subset_sizes = [max(int(b * (1 - self.sample_drop_ratio)), 1) for b in b_list] + residual_scale_factors = [b / sample_subset_size for b, sample_subset_size in zip(b_list, sample_subset_sizes)] + + if self.training and self.sample_drop_ratio > 0.0: + indices_1_list = [ + (torch.randperm(b, device=x.device))[:sample_subset_size] + for x, b, sample_subset_size in zip(x_list, b_list, sample_subset_sizes) + ] + x_subset_1_list = [x[indices_1] for x, indices_1 in zip(x_list, indices_1_list)] + + if rope_list is not None: + rope_subset_list = [ + self._maybe_index_rope(rope, indices_1) for rope, indices_1 in zip(rope_list, indices_1_list) + ] + else: + rope_subset_list = rope_list + + flattened, shapes, num_tokens = cat_keep_shapes(x_subset_1_list) + norm1 = uncat_with_shapes(self.norm1(flattened), shapes, num_tokens) + residual_1_list = self.attn.forward_list(norm1, rope_list=rope_subset_list) + + x_attn_list = [ + torch.index_add( + x, + dim=0, + source=self.ls1(residual_1), + index=indices_1, + alpha=residual_scale_factor, + ) + for x, residual_1, indices_1, residual_scale_factor in zip( + x_list, residual_1_list, indices_1_list, residual_scale_factors + ) + ] + + indices_2_list = [ + (torch.randperm(b, device=x.device))[:sample_subset_size] + for x, b, sample_subset_size in zip(x_list, b_list, sample_subset_sizes) + ] + x_subset_2_list = [x[indices_2] for x, indices_2 in zip(x_attn_list, indices_2_list)] + flattened, shapes, num_tokens = cat_keep_shapes(x_subset_2_list) + norm2_flat = self.norm2(flattened) + norm2_list = uncat_with_shapes(norm2_flat, shapes, num_tokens) + + residual_2_list = self.mlp.forward_list(norm2_list) + + x_ffn = [ + torch.index_add( + x_attn, + dim=0, + source=self.ls2(residual_2), + index=indices_2, + alpha=residual_scale_factor, + ) + for x_attn, residual_2, indices_2, residual_scale_factor in zip( + x_attn_list, residual_2_list, indices_2_list, residual_scale_factors + ) + ] + else: + x_out = [] + for x, rope in zip(x_list, rope_list): + x_attn = x + self.ls1(self.attn(self.norm1(x), rope=rope)) + x_ffn = x_attn + self.ls2(self.mlp(self.norm2(x_attn))) + x_out.append(x_ffn) + x_ffn = x_out + + return x_ffn + + def forward(self, x_or_x_list, rope_or_rope_list=None) -> List[Tensor]: + if isinstance(x_or_x_list, Tensor): + # for reference: + # return self._forward(x_or_x_list, rope=rope_or_rope_list) + # in order to match implementations we call the list op: + return self._forward_list([x_or_x_list], rope_list=[rope_or_rope_list])[0] + elif isinstance(x_or_x_list, list): + if rope_or_rope_list is None: + rope_or_rope_list = [None for x in x_or_x_list] + # return [self._forward(x, rope=rope) for x, rope in zip(x_or_x_list, rope_or_rope_list)] + return self._forward_list(x_or_x_list, rope_list=rope_or_rope_list) + else: + raise AssertionError + + +class CausalSelfAttentionBlock(nn.Module): + def __init__( + self, + dim: int, + num_heads: int, + ffn_ratio: float = 4.0, + ls_init_value: Optional[float] = None, + is_causal: bool = True, + act_layer: Callable = nn.GELU, + norm_layer: Callable = nn.LayerNorm, + dropout_prob: float = 0.0, + ): + super().__init__() + + self.dim = dim + self.is_causal = is_causal + self.ls1 = LayerScale(dim, init_values=ls_init_value) if ls_init_value else nn.Identity() + self.attention_norm = norm_layer(dim) + self.attention = CausalSelfAttention(dim, num_heads, attn_drop=dropout_prob, proj_drop=dropout_prob) + + self.ffn_norm = norm_layer(dim) + ffn_hidden_dim = int(dim * ffn_ratio) + self.feed_forward = Mlp( + in_features=dim, + hidden_features=ffn_hidden_dim, + drop=dropout_prob, + act_layer=act_layer, + ) + + self.ls2 = LayerScale(dim, init_values=ls_init_value) if ls_init_value else nn.Identity() + + def init_weights( + self, + init_attn_std: float | None = None, + init_proj_std: float | None = None, + init_fc_std: float | None = None, + factor: float = 1.0, + ) -> None: + init_attn_std = init_attn_std or (self.dim**-0.5) + init_proj_std = init_proj_std or init_attn_std * factor + init_fc_std = init_fc_std or (2 * self.dim) ** -0.5 + self.attention.init_weights(init_attn_std, init_proj_std) + self.attention_norm.reset_parameters() + nn.init.normal_(self.feed_forward.fc1.weight, std=init_fc_std) + nn.init.normal_(self.feed_forward.fc2.weight, std=init_proj_std) + self.ffn_norm.reset_parameters() + + def forward( + self, + x: torch.Tensor, + ): + + x_attn = x + self.ls1(self.attention(self.attention_norm(x), self.is_causal)) + x_ffn = x_attn + self.ls2(self.feed_forward(self.ffn_norm(x_attn))) + return x_ffn diff --git a/starVLA/dinov3/dinov3/layers/dino_head.py b/starVLA/dinov3/dinov3/layers/dino_head.py new file mode 100644 index 0000000000000000000000000000000000000000..bb71f35fc7ecf15e31963eb76d21626ccdea9b90 --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/dino_head.py @@ -0,0 +1,67 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import torch +import torch.nn as nn +from torch.nn.init import trunc_normal_ + + +class DINOHead(nn.Module): + def __init__( + self, + in_dim, + out_dim, + use_bn=False, + nlayers=3, + hidden_dim=2048, + bottleneck_dim=256, + mlp_bias=True, + ): + super().__init__() + nlayers = max(nlayers, 1) + self.mlp = _build_mlp( + nlayers, + in_dim, + bottleneck_dim, + hidden_dim=hidden_dim, + use_bn=use_bn, + bias=mlp_bias, + ) + self.last_layer = nn.Linear(bottleneck_dim, out_dim, bias=False) + + def init_weights(self) -> None: + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + def forward(self, x, no_last_layer=False, only_last_layer=False): + if not only_last_layer: + x = self.mlp(x) + eps = 1e-6 if x.dtype == torch.float16 else 1e-12 + x = nn.functional.normalize(x, dim=-1, p=2, eps=eps) + if not no_last_layer: + x = self.last_layer(x) + return x + + +def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True): + if nlayers == 1: + return nn.Linear(in_dim, bottleneck_dim, bias=bias) + else: + layers = [nn.Linear(in_dim, hidden_dim, bias=bias)] + if use_bn: + layers.append(nn.BatchNorm1d(hidden_dim)) + layers.append(nn.GELU()) + for _ in range(nlayers - 2): + layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias)) + if use_bn: + layers.append(nn.BatchNorm1d(hidden_dim)) + layers.append(nn.GELU()) + layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias)) + return nn.Sequential(*layers) diff --git a/starVLA/dinov3/dinov3/layers/ffn_layers.py b/starVLA/dinov3/dinov3/layers/ffn_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..749e6be2cd2cd8040bb3233a61a9a306eaea6ca8 --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/ffn_layers.py @@ -0,0 +1,77 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from typing import Callable, List, Optional + +import torch.nn.functional as F +from torch import Tensor, nn + +from dinov3.utils import cat_keep_shapes, uncat_with_shapes + + +class ListForwardMixin(object): + def forward(self, x: Tensor): + raise NotImplementedError + + def forward_list(self, x_list: List[Tensor]) -> List[Tensor]: + x_flat, shapes, num_tokens = cat_keep_shapes(x_list) + x_flat = self.forward(x_flat) + return uncat_with_shapes(x_flat, shapes, num_tokens) + + +class Mlp(nn.Module, ListForwardMixin): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Callable[..., nn.Module] = nn.GELU, + drop: float = 0.0, + bias: bool = True, + device=None, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias, device=device) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias, device=device) + self.drop = nn.Dropout(drop) + + def forward(self, x: Tensor) -> Tensor: + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class SwiGLUFFN(nn.Module, ListForwardMixin): + def __init__( + self, + in_features: int, + hidden_features: Optional[int] = None, + out_features: Optional[int] = None, + act_layer: Optional[Callable[..., nn.Module]] = None, + drop: float = 0.0, + bias: bool = True, + align_to: int = 8, + device=None, + ) -> None: + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + d = int(hidden_features * 2 / 3) + swiglu_hidden_features = d + (-d % align_to) + self.w1 = nn.Linear(in_features, swiglu_hidden_features, bias=bias, device=device) + self.w2 = nn.Linear(in_features, swiglu_hidden_features, bias=bias, device=device) + self.w3 = nn.Linear(swiglu_hidden_features, out_features, bias=bias, device=device) + + def forward(self, x: Tensor) -> Tensor: + x1 = self.w1(x) + x2 = self.w2(x) + hidden = F.silu(x1) * x2 + return self.w3(hidden) diff --git a/starVLA/dinov3/dinov3/layers/fp8_linear.py b/starVLA/dinov3/dinov3/layers/fp8_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd88a179ef7b6d638dc211a1e592ac8a726b4e9 --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/fp8_linear.py @@ -0,0 +1,141 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import re + +import torch + +from dinov3.layers.attention import LinearKMaskedBias +from dinov3.utils import named_replace + +# avoid division by zero when calculating scale +EPS = 1e-12 + + +def scale(t, amax_t): + max_v = torch.finfo(torch.float8_e4m3fn).max + scale_t = torch.clamp(amax_t.float(), min=EPS) / max_v + t_fp8 = (t / scale_t).to(torch.float8_e4m3fn) + return t_fp8, scale_t + + +def matmul(first, amax_first, second_t, amax_second_t, bias): + first_fp8, scale_first = scale(first, amax_first) + second_t_fp8, scale_second_t = scale(second_t, amax_second_t) + # PyTorch's row-wise scaled matmul kernel is based on CUTLASS and is quite + # slow. Hence we fall back to an "unscaled" matmul, which uses cuBLAS, and + # apply the scale manually afterwards. + output = torch._scaled_mm( + first_fp8, + second_t_fp8.t(), + scale_a=scale_first.new_ones((1, 1)), + scale_b=scale_second_t.t().new_ones((1, 1)), + bias=None, + out_dtype=torch.bfloat16, + use_fast_accum=False, + ) + output = (output * scale_first * scale_second_t.t()).to(torch.bfloat16) + if bias is not None: + output = output + bias + return output + + +@torch.compiler.allow_in_graph +class Fp8LinearFn(torch.autograd.Function): + @staticmethod + def forward(ctx, a, b_t, bias): + amax_a = a.abs().amax(dim=-1, keepdim=True) + amax_b_t = b_t.abs().amax(dim=-1, keepdim=True) + out = matmul(a, amax_a, b_t, amax_b_t, bias) + + ctx.a_requires_grad = a.requires_grad + ctx.b_requires_grad = b_t.requires_grad + ctx.bias_requires_grad = bias.requires_grad if bias is not None else False + + ctx.save_for_backward(a, b_t, amax_b_t.max()) + + return out + + @staticmethod + def backward(ctx, grad_out): + a, b_t, amax_b = ctx.saved_tensors + + if ctx.a_requires_grad: + b = b_t.t().contiguous() + amax_grad_out = grad_out.abs().amax(dim=-1, keepdim=True) + amax_b = amax_b.repeat(b.shape[0], 1) + grad_a = matmul(grad_out, amax_grad_out, b, amax_b, None) + else: + grad_a = None + if ctx.b_requires_grad: + grad_b = grad_out.t() @ a + else: + grad_b = None + if ctx.bias_requires_grad: + grad_bias = grad_out.sum(dim=0) + else: + grad_bias = None + + return grad_a, grad_b, grad_bias + + +class Fp8Linear(torch.nn.Linear): + def forward(self, input: torch.Tensor) -> torch.Tensor: + out = Fp8LinearFn.apply(input.flatten(end_dim=-2), self.weight, self.bias) + out = out.unflatten(0, input.shape[:-1]) + return out + + +class Fp8LinearKMaskedBias(LinearKMaskedBias): + def forward(self, input: torch.Tensor) -> torch.Tensor: + masked_bias = self.bias * self.bias_mask if self.bias is not None else None + out = Fp8LinearFn.apply(input.flatten(end_dim=-2), self.weight, masked_bias) + out = out.unflatten(0, input.shape[:-1]) + return out + + +def convert_linears_to_fp8(root_module: torch.nn.Module, *, filter: str) -> torch.nn.Module: + filter_re = re.compile(filter) + total_count = 0 + + def replace(module: torch.nn.Module, name: str) -> torch.nn.Module: + nonlocal total_count + if not isinstance(module, torch.nn.Linear) or not filter_re.search(name): + return module + if type(module) == torch.nn.Linear: + new_cls = Fp8Linear + elif type(module) == LinearKMaskedBias: + new_cls = Fp8LinearKMaskedBias + else: + assert False, str(type(module)) + if module.in_features % 64 != 0 or module.out_features % 64 != 0: + # This is not a strict requirement, but H100 TensorCores for fp8 + # operate on tiles of 64 elements anyways, and Inductor sometimes + # pads inner dims to become multiples of 64. Also, if one day we + # switch back to cuBLAS, it artificially requires dims to be + # multiples of 16. + raise RuntimeError( + "fp8 requires all dimensions to be multiples of 64 " "(consider using ffn_layer=swiglu64 or higher)" + ) + new_module = new_cls( + in_features=module.in_features, + out_features=module.out_features, + bias=module.bias is not None, + dtype=module.weight.dtype, + device=module.weight.device, + ) + new_module.weight = module.weight + new_module.bias = module.bias + total_count += 1 + return new_module + + out = named_replace(replace, root_module) + assert total_count > 0, "fp8: no layer found to convert" + # Force re-compile everything + torch._dynamo.reset_code_caches() + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + return out diff --git a/starVLA/dinov3/dinov3/layers/layer_scale.py b/starVLA/dinov3/dinov3/layers/layer_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..0b72b7c64c9cc38fd4e3db63e9c90f0158caa36c --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/layer_scale.py @@ -0,0 +1,29 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from typing import Union + +import torch +from torch import Tensor, nn + + +class LayerScale(nn.Module): + def __init__( + self, + dim: int, + init_values: Union[float, Tensor] = 1e-5, + inplace: bool = False, + device=None, + ) -> None: + super().__init__() + self.inplace = inplace + self.gamma = nn.Parameter(torch.empty(dim, device=device)) + self.init_values = init_values + + def reset_parameters(self): + nn.init.constant_(self.gamma, self.init_values) + + def forward(self, x: Tensor) -> Tensor: + return x.mul_(self.gamma) if self.inplace else x * self.gamma diff --git a/starVLA/dinov3/dinov3/layers/patch_embed.py b/starVLA/dinov3/dinov3/layers/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..760343f14cd0c1c2bbb2c70d43f82eb0bb1fddf4 --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/patch_embed.py @@ -0,0 +1,89 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import math +from typing import Callable, Tuple, Union + +from torch import Tensor, nn + + +def make_2tuple(x): + if isinstance(x, tuple): + assert len(x) == 2 + return x + + assert isinstance(x, int) + return (x, x) + + +class PatchEmbed(nn.Module): + """ + 2D image to patch embedding: (B,C,H,W) -> (B,N,D) + + Args: + img_size: Image size. + patch_size: Patch token size. + in_chans: Number of input image channels. + embed_dim: Number of linear projection output channels. + norm_layer: Normalization layer. + """ + + def __init__( + self, + img_size: Union[int, Tuple[int, int]] = 224, + patch_size: Union[int, Tuple[int, int]] = 16, + in_chans: int = 3, + embed_dim: int = 768, + norm_layer: Callable | None = None, + flatten_embedding: bool = True, + ) -> None: + super().__init__() + + image_HW = make_2tuple(img_size) + patch_HW = make_2tuple(patch_size) + patch_grid_size = ( + image_HW[0] // patch_HW[0], + image_HW[1] // patch_HW[1], + ) + + self.img_size = image_HW + self.patch_size = patch_HW + self.patches_resolution = patch_grid_size + self.num_patches = patch_grid_size[0] * patch_grid_size[1] + + self.in_chans = in_chans + self.embed_dim = embed_dim + + self.flatten_embedding = flatten_embedding + + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + _, _, H, W = x.shape + # patch_H, patch_W = self.patch_size + # assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}" + # assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}" + + x = self.proj(x) # B C H W + H, W = x.size(2), x.size(3) + x = x.flatten(2).transpose(1, 2) # B HW C + x = self.norm(x) + if not self.flatten_embedding: + x = x.reshape(-1, H, W, self.embed_dim) # B H W C + return x + + def flops(self) -> float: + Ho, Wo = self.patches_resolution + flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) + if self.norm is not None: + flops += Ho * Wo * self.embed_dim + return flops + + def reset_parameters(self): + k = 1 / (self.in_chans * (self.patch_size[0] ** 2)) + nn.init.uniform_(self.proj.weight, -math.sqrt(k), math.sqrt(k)) + if self.proj.bias is not None: + nn.init.uniform_(self.proj.bias, -math.sqrt(k), math.sqrt(k)) diff --git a/starVLA/dinov3/dinov3/layers/rms_norm.py b/starVLA/dinov3/dinov3/layers/rms_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..1d0a89c47c5e71687cadbf47fef567b2c6a2b3b4 --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/rms_norm.py @@ -0,0 +1,24 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import torch +from torch import Tensor, nn + + +class RMSNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-5): + super().__init__() + self.weight = nn.Parameter(torch.ones(dim)) + self.eps = eps + + def reset_parameters(self) -> None: + nn.init.constant_(self.weight, 1) + + def _norm(self, x: Tensor) -> Tensor: + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x: Tensor) -> Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight diff --git a/starVLA/dinov3/dinov3/layers/rope_position_encoding.py b/starVLA/dinov3/dinov3/layers/rope_position_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..2635d09e7732fb4c146f57d3aef19c2d3e5668ec --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/rope_position_encoding.py @@ -0,0 +1,121 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import math +from typing import Literal + +import numpy as np +import torch +from torch import Tensor, nn + + +# RoPE positional embedding with no mixing of coordinates (axial) and no learnable weights +# Supports two parametrizations of the rope parameters: either using `base` or `min_period` and `max_period`. +class RopePositionEmbedding(nn.Module): + def __init__( + self, + embed_dim: int, + *, + num_heads: int, + base: float | None = 100.0, + min_period: float | None = None, + max_period: float | None = None, + normalize_coords: Literal["min", "max", "separate"] = "separate", + shift_coords: float | None = None, + jitter_coords: float | None = None, + rescale_coords: float | None = None, + dtype: torch.dtype | None = None, + device: torch.device | None = None, + ): + super().__init__() + assert embed_dim % (4 * num_heads) == 0 + both_periods = min_period is not None and max_period is not None + if (base is None and not both_periods) or (base is not None and both_periods): + raise ValueError("Either `base` or `min_period`+`max_period` must be provided.") + + D_head = embed_dim // num_heads + self.base = base + self.min_period = min_period + self.max_period = max_period + self.D_head = D_head + self.normalize_coords = normalize_coords + self.shift_coords = shift_coords + self.jitter_coords = jitter_coords + self.rescale_coords = rescale_coords + + # Needs persistent=True because we do teacher.load_state_dict(student.state_dict()) to initialize the teacher + self.dtype = dtype # Don't rely on self.periods.dtype + self.register_buffer( + "periods", + torch.empty(D_head // 4, device=device, dtype=dtype), + persistent=True, + ) + self._init_weights() + + def forward(self, *, H: int, W: int) -> tuple[Tensor, Tensor]: + device = self.periods.device + dtype = self.dtype + dd = {"device": device, "dtype": dtype} + + # Prepare coords in range [-1, +1] + if self.normalize_coords == "max": + max_HW = max(H, W) + coords_h = torch.arange(0.5, H, **dd) / max_HW # [H] + coords_w = torch.arange(0.5, W, **dd) / max_HW # [W] + elif self.normalize_coords == "min": + min_HW = min(H, W) + coords_h = torch.arange(0.5, H, **dd) / min_HW # [H] + coords_w = torch.arange(0.5, W, **dd) / min_HW # [W] + elif self.normalize_coords == "separate": + coords_h = torch.arange(0.5, H, **dd) / H # [H] + coords_w = torch.arange(0.5, W, **dd) / W # [W] + else: + raise ValueError(f"Unknown normalize_coords: {self.normalize_coords}") + coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1) # [H, W, 2] + coords = coords.flatten(0, 1) # [HW, 2] + coords = 2.0 * coords - 1.0 # Shift range [0, 1] to [-1, +1] + + # Shift coords by adding a uniform value in [-shift, shift] + if self.training and self.shift_coords is not None: + shift_hw = torch.empty(2, **dd).uniform_(-self.shift_coords, self.shift_coords) + coords += shift_hw[None, :] + + # Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter] + if self.training and self.jitter_coords is not None: + jitter_max = np.log(self.jitter_coords) + jitter_min = -jitter_max + jitter_hw = torch.empty(2, **dd).uniform_(jitter_min, jitter_max).exp() + coords *= jitter_hw[None, :] + + # Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale] + if self.training and self.rescale_coords is not None: + rescale_max = np.log(self.rescale_coords) + rescale_min = -rescale_max + rescale_hw = torch.empty(1, **dd).uniform_(rescale_min, rescale_max).exp() + coords *= rescale_hw + + # Prepare angles and sin/cos + angles = 2 * math.pi * coords[:, :, None] / self.periods[None, None, :] # [HW, 2, D//4] + angles = angles.flatten(1, 2) # [HW, D//2] + angles = angles.tile(2) # [HW, D] + cos = torch.cos(angles) # [HW, D] + sin = torch.sin(angles) # [HW, D] + + return (sin, cos) # 2 * [HW, D] + + def _init_weights(self): + device = self.periods.device + dtype = self.dtype + if self.base is not None: + periods = self.base ** ( + 2 * torch.arange(self.D_head // 4, device=device, dtype=dtype) / (self.D_head // 2) + ) # [D//4] + else: + base = self.max_period / self.min_period + exponents = torch.linspace(0, 1, self.D_head // 4, device=device, dtype=dtype) # [D//4] range [0, 1] + periods = base**exponents # range [1, max_period / min_period] + periods = periods / base # range [min_period / max_period, 1] + periods = periods * self.max_period # range [min_period, max_period] + self.periods.data = periods diff --git a/starVLA/dinov3/dinov3/layers/sparse_linear.py b/starVLA/dinov3/dinov3/layers/sparse_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb9e103182d10ed94a2dfa13e58060516ff3dbe --- /dev/null +++ b/starVLA/dinov3/dinov3/layers/sparse_linear.py @@ -0,0 +1,90 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +from typing import Callable + +import torch +import torch.nn as nn +import torch.nn.functional as F +import xformers.ops as xops + +from dinov3.utils import named_apply, named_replace + +logger = logging.getLogger("dinov3") + + +class LinearW24(torch.nn.Linear): + ALGO = "largest_abs_values_greedy" + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.sparsity_enabled = False + + def forward(self, input: torch.Tensor) -> torch.Tensor: + if not self.sparsity_enabled: + return super().forward(input) + + input_shape = input.shape + input = input.flatten(end_dim=-2) + dim0 = input.shape[0] + if dim0 % 8 != 0: + # NOTE: This should be torch-compiled away + input = F.pad(input, [0, 0, 0, -dim0 % 8]) + w_sparse = xops.sparsify24( + self.weight, + algo=self.ALGO, + gradient="ste", + backend="cusparselt", + ) + return F.linear(input, w_sparse, self.bias,)[ + :dim0 + ].unflatten(dim=0, sizes=input_shape[:-1]) + + +def replace_linears_with_sparse_linear(root_module: nn.Module, *, filter_fn: Callable[[str], bool]) -> nn.Module: + total_count = 0 + + def replace(module: nn.Module, name: str) -> nn.Module: + nonlocal total_count + if not isinstance(module, nn.Linear) or not filter_fn(name): + return module + assert type(module) == nn.Linear, "Subtypes not supported" + new_module = LinearW24( + in_features=module.in_features, + out_features=module.out_features, + bias=module.bias is not None, + dtype=module.weight.dtype, + device=module.weight.device, + ) + new_module.weight = module.weight + new_module.bias = module.bias + total_count += 1 + return new_module + + out = named_replace(replace, root_module) + assert total_count > 0, "2:4 sparsity: no layer found to sparsify" + return out + + +def update_24sparsity(root_module: nn.Module, enabled: bool) -> int: + num_modified = 0 + + def maybe_apply_sparsity(module: nn.Module, name: str) -> nn.Module: + nonlocal num_modified + if not isinstance(module, LinearW24): + return module + num_modified += 1 + module.sparsity_enabled = enabled + logger.info(f"- {'' if module.sparsity_enabled else 'de'}sparsifying {name}") + return module + + named_apply(maybe_apply_sparsity, root_module) + # Force re-compile everything + torch._dynamo.reset_code_caches() + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + return num_modified diff --git a/starVLA/dinov3/dinov3/logging/__init__.py b/starVLA/dinov3/dinov3/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..118925070ffda3ae73b6c15b0549a772f07d063d --- /dev/null +++ b/starVLA/dinov3/dinov3/logging/__init__.py @@ -0,0 +1,180 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import functools +import logging +import os +import sys +from typing import Optional + +from termcolor import colored + +from dinov3.distributed import TorchDistributedEnvironment + +from dinov3.logging.helpers import MetricLogger, SmoothedValue + +_LEVEL_COLORED_KWARGS = { + logging.DEBUG: {"color": "green", "attrs": ["bold"]}, + logging.INFO: {"color": "green"}, + logging.WARNING: {"color": "yellow"}, + logging.ERROR: {"color": "red"}, + logging.CRITICAL: {"color": "red", "attrs": ["bold"]}, +} + + +class _LevelColoredFormatter(logging.Formatter): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def formatMessage(self, record): + log = super().formatMessage(record) + + colored_kwargs = _LEVEL_COLORED_KWARGS.get(record.levelno) + if colored_kwargs is None: + return log + + msg = record.msg % record.args if record.msg == "%s" else record.msg + index = log.rfind(msg, len(log) - len(msg)) + # Can happen in some cases, like if the msg contains `%s` which + # have been replaced in `formatMessage`. Fallback to no colors + if index == -1: + return log + prefix = log[:index] + prefix = colored(prefix, **colored_kwargs) + return prefix + msg + + +# So that calling _configure_logger multiple times won't add many handlers +@functools.lru_cache() +def _configure_logger( + name: Optional[str] = None, + *, + level: int = logging.DEBUG, + output: Optional[str] = None, + color: bool = True, + log_to_stdout_only_in_main_process: bool = True, +): + """ + Configure a logger. + + Adapted from Detectron2. + + Args: + name: The name of the logger to configure. + level: The logging level to use. + output: A file name or a directory to save log. If None, will not save log file. + If ends with ".txt" or ".log", assumed to be a file name. + Otherwise, logs will be saved to `output/log.txt`. + color: Whether stdout output should be colored (ignored if stdout is not a terminal). + log_to_stdout_only_in_main_process: The main process (rank 0) always logs to stdout, + regardless of this flag. If False, other ranks will also log to their stdout. + + Returns: + The configured logger. + """ + + # Disable colored output if the stdout is not a terminal + color = color and os.isatty(sys.stdout.fileno()) + + logger = logging.getLogger(name) + logger.setLevel(level) + logger.propagate = False + + # Loosely match Google glog format: + # [IWEF]yyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg + # but use a shorter timestamp and include the logger name: + # [IWEF]yyyymmdd hh:mm:ss logger threadid file:line] msg + fmt_prefix = "%(levelname).1s%(asctime)s %(process)s %(name)s %(filename)s:%(lineno)s] " + fmt_message = "%(message)s" + fmt = fmt_prefix + fmt_message + datefmt = "%Y%m%d %H:%M:%S" + plain_formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) + + torch_env = TorchDistributedEnvironment() + + # rank 0 always logs to stdout, for other ranks it depends on log_to_stdout_only_in_main_process + should_log_to_stdout = torch_env.is_main_process or not log_to_stdout_only_in_main_process + if should_log_to_stdout: + handler = logging.StreamHandler(stream=sys.stdout) + handler.setLevel(logging.DEBUG) + + formatter: logging.Formatter + if color: + formatter = _LevelColoredFormatter( + fmt=fmt, + datefmt=datefmt, + ) + else: + formatter = plain_formatter + + handler.setFormatter(formatter) + logger.addHandler(handler) + + # file logging for all workers + if output: + if os.path.splitext(output)[-1] in (".txt", ".log"): + filename = output + else: + filename = os.path.join(output, "logs", "log.txt") + + if not torch_env.is_main_process: + filename = filename + f".rank{torch_env.rank}" + + os.makedirs(os.path.dirname(filename), exist_ok=True) + + handler = logging.StreamHandler(open(filename, "a")) + handler.setLevel(logging.DEBUG) + handler.setFormatter(plain_formatter) + logger.addHandler(handler) + + logger.debug(f"PyTorch distributed environment: {torch_env}") + return logger + + +def setup_logging( + output: Optional[str] = None, + *, + name: Optional[str] = None, + level: int = logging.DEBUG, + color: bool = True, + capture_warnings: bool = True, + log_to_stdout_only_in_main_process: bool = True, +) -> None: + """ + Setup logging. + + Args: + output: A file name or a directory to save log files. If None, log + files will not be saved. If output ends with ".txt" or ".log", it + is assumed to be a file name. + Otherwise, logs will be saved to `output/log.txt`. + name: The name of the logger to configure, by default the root logger. + level: The logging level to use. + color: Whether stdout output should be colored (ignored if stdout is not a terminal). + capture_warnings: Whether warnings should be captured as logs. + log_to_stdout_only_in_main_process: The main process (rank 0) always logs to stdout, + regardless of this flag. If False, other ranks will also log to their stdout. + """ + logging.captureWarnings(capture_warnings) + # Ensure the path is canonical to properly use the cache of `_configure_logger` + output = output if output is None else os.path.realpath(output) + _configure_logger( + name, + level=level, + output=output, + color=color, + log_to_stdout_only_in_main_process=log_to_stdout_only_in_main_process, + ) + + +def cleanup_logging(*, name: Optional[str] = None) -> None: + logger = logging.getLogger(name) + for handler in logger.handlers: + handler.flush() + handler.close() + logger.removeHandler(handler) + + # clears the cache of `_configure_logger` to allow re-initialization + _configure_logger.cache_clear() diff --git a/starVLA/dinov3/dinov3/logging/helpers.py b/starVLA/dinov3/dinov3/logging/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..b01e1f8352a4235ef1707ebb0eddbc6d80d729ef --- /dev/null +++ b/starVLA/dinov3/dinov3/logging/helpers.py @@ -0,0 +1,203 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import datetime +import json +import logging +import time +from collections import defaultdict, deque + +import torch + +import dinov3.distributed as distributed + +logger = logging.getLogger("dinov3") + + +class MetricLogger(object): + def __init__(self, delimiter="\t", output_file=None): + self.meters = defaultdict(SmoothedValue) + self.delimiter = delimiter + self.output_file = output_file + + def update(self, **kwargs): + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.meters[k].update(v) + + def __getattr__(self, attr): + if attr in self.meters: + return self.meters[attr] + if attr in self.__dict__: + return self.__dict__[attr] + raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr)) + + def __str__(self): + loss_str = [] + for name, meter in self.meters.items(): + loss_str.append("{}: {}".format(name, str(meter))) + return self.delimiter.join(loss_str) + + def synchronize_between_processes(self): + for meter in self.meters.values(): + meter.synchronize_between_processes() + + def add_meter(self, name, meter): + self.meters[name] = meter + + def dump_in_output_file(self, iteration, iter_time, data_time): + if self.output_file is None or not distributed.is_main_process(): + return + dict_to_dump = dict( + iteration=iteration, + iter_time=iter_time, + data_time=data_time, + ) + dict_to_dump.update({k: v.median for k, v in self.meters.items()}) + with open(self.output_file, "a") as f: + f.write(json.dumps(dict_to_dump) + "\n") + pass + + def log_every(self, iterable, print_freq, header=None, n_iterations=None, start_iteration=0): + i = start_iteration + if not header: + header = "" + start_time = time.time() + end = time.time() + iter_time = SmoothedValue(fmt="{avg:.6f}") + data_time = SmoothedValue(fmt="{avg:.6f}") + + if n_iterations is None: + n_iterations = len(iterable) + + space_fmt = ":" + str(len(str(n_iterations))) + "d" + + log_list = [ + header, + "[{0" + space_fmt + "}/{1}]", + "eta: {eta}", + "{meters}", + "time: {time}", + "data: {data}", + ] + if torch.cuda.is_available(): + log_list += ["mem: {current_memory:.0f}"] + log_list += ["(max mem: {max_memory:.0f})"] + + log_msg = self.delimiter.join(log_list) + MB = 1024.0 * 1024.0 + for obj in iterable: + if i >= n_iterations: + break + + data_time.update(time.time() - end) + yield obj + iter_time.update(time.time() - end) + if i % print_freq == 0 or i == n_iterations - 1: + self.dump_in_output_file(iteration=i, iter_time=iter_time.avg, data_time=data_time.avg) + eta_seconds = iter_time.global_avg * (n_iterations - i) + eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) + if torch.cuda.is_available(): + logger.info( + log_msg.format( + i, + n_iterations, + eta=eta_string, + meters=str(self), + time=str(iter_time), + data=str(data_time), + current_memory=torch.cuda.memory_allocated() / MB, + max_memory=torch.cuda.max_memory_allocated() / MB, + ) + ) + else: + logger.info( + log_msg.format( + i, + n_iterations, + eta=eta_string, + meters=str(self), + time=str(iter_time), + data=str(data_time), + ) + ) + i += 1 + end = time.time() + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + s_it = total_time / n_iterations if n_iterations > 0 else 0 + logger.info("{} Total time: {} ({:.6f} s / it)".format(header, total_time_str, s_it)) + + +class SmoothedValue: + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + + def __init__(self, window_size=20, fmt=None): + if fmt is None: + fmt = "{median:.4f} ({global_avg:.4f})" + self.deque = deque(maxlen=window_size) + self.total = 0.0 + self.count = 0 + self.fmt = fmt + + def update(self, value, num=1): + self.deque.append(value) + self.count += num + self.total += value * num + + def synchronize_between_processes(self): + """ + Distributed synchronization of the metric + Warning: does not synchronize the deque! + """ + if not distributed.is_enabled(): + return + t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda") + torch.distributed.barrier() + torch.distributed.all_reduce(t) + t = t.tolist() + self.count = int(t[0]) + self.total = t[1] + + @property + def median(self): + d = torch.tensor(list(self.deque)) + return d.median().item() # returns float("nan") when d is empty + + @property + def avg(self): + d = torch.tensor(list(self.deque), dtype=torch.float32) + return d.mean().item() # returns float("nan") when d is empty + + @property + def global_avg(self): + if self.count == 0: + return float("nan") + return self.total / self.count + + @property + def max(self): + if len(self.deque) == 0: + return float("nan") + return max(self.deque) + + @property + def value(self): + if len(self.deque) == 0: + return float("nan") + return self.deque[-1] + + def __str__(self): + return self.fmt.format( + median=self.median, + avg=self.avg, + global_avg=self.global_avg, + max=self.max, + value=self.value, + ) diff --git a/starVLA/dinov3/dinov3/loss/__init__.py b/starVLA/dinov3/dinov3/loss/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9f52a54a7da4f5a48c22b71008136f4e6f6c3a92 --- /dev/null +++ b/starVLA/dinov3/dinov3/loss/__init__.py @@ -0,0 +1,9 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from .dino_clstoken_loss import DINOLoss +from .gram_loss import GramLoss +from .ibot_patch_loss import iBOTPatchLoss +from .koleo_loss import KoLeoLoss, KoLeoLossDistributed diff --git a/starVLA/dinov3/dinov3/loss/dino_clstoken_loss.py b/starVLA/dinov3/dinov3/loss/dino_clstoken_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..40bc68d91b67e42090d6d1ff61569bcdab0f0a24 --- /dev/null +++ b/starVLA/dinov3/dinov3/loss/dino_clstoken_loss.py @@ -0,0 +1,124 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import math + +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import nn + +from dinov3.distributed import get_process_subgroup, get_subgroup_size + + +class DINOLoss(nn.Module): + def __init__( + self, + out_dim, + student_temp=0.1, + center_momentum=0.9, + ): + super().__init__() + self.student_temp = student_temp + self.center_momentum = center_momentum + self.register_buffer("center", torch.full((1, out_dim), math.nan)) + self.updated = True + self.reduce_handle = None + self.len_teacher_output = None + self.async_batch_center = None + + def init_weights(self) -> None: + self.center.zero_() + + @torch.no_grad() + def softmax_center_teacher(self, teacher_output, teacher_temp, update_centers=True): + if update_centers: + self.apply_center_update() + # teacher centering and sharpening + return F.softmax((teacher_output - self.center) / teacher_temp, dim=-1) + + @torch.no_grad() + def sinkhorn_knopp_teacher(self, teacher_output, teacher_temp, n_iterations=3): + # teacher_output: [batch, prototypes] + teacher_output = teacher_output.float() + world_size = get_subgroup_size() if dist.is_initialized() else 1 + Q = torch.exp(teacher_output / teacher_temp).t() # Q is K-by-B for consistency with notations from our paper + B = Q.shape[1] * world_size # number of samples to assign + K = Q.shape[0] # how many prototypes + + # make the matrix sums to 1 + sum_Q = torch.sum(Q) + if dist.is_initialized(): + dist.all_reduce(sum_Q, group=get_process_subgroup()) + Q /= sum_Q + + for _ in range(n_iterations): + # normalize each row: total weight per prototype must be 1/K + sum_of_rows = torch.sum(Q, dim=1, keepdim=True) + if dist.is_initialized(): + dist.all_reduce(sum_of_rows, group=get_process_subgroup()) + Q /= sum_of_rows + Q /= K + + # normalize each column: total weight per sample must be 1/B + Q /= torch.sum(Q, dim=0, keepdim=True) + Q /= B + + Q *= B # the colomns must sum to 1 so that Q is an assignment + return Q.t() + + def forward(self, student_logits, teacher_probs, ignore_diagonal=False): + """ + Cross-entropy between softmax outputs of the teacher and student networks. + student_logits: [student crops, batch, prototypes] + teacher_probs: [teacher crops, batch, prototypes] must sum to 1 over the last dim + + loss = 0 + count = 0 + for each sample `b` in the batch: + for each student crop `s` of this sample: + for each teacher crop `t` of this sample: + if ignore_diagonal and s == t: + continue + loss += cross_entropy(softmax(student_logits[s, b] / student_temp), teacher_probs[t, b]) + count += 1 + return loss / count + """ + student_crops, B, K = student_logits.shape + teacher_crops, _, _ = teacher_probs.shape + student_logits = F.log_softmax(student_logits.float() / self.student_temp, dim=-1) + if not ignore_diagonal: + loss = -torch.einsum("s b k, t b k -> ", student_logits, teacher_probs) + return loss / (B * student_crops * teacher_crops) + else: + loss = -torch.einsum("s b k, t b k -> s t", student_logits, teacher_probs) + min_st = min(student_crops, teacher_crops) + loss = torch.diagonal_scatter(loss, loss.new_zeros(min_st)) + return loss.sum() / (B * student_crops * teacher_crops - B * min_st) + + @torch.no_grad() + def update_center(self, teacher_output): + self.reduce_center_update(teacher_output) + + @torch.no_grad() + def reduce_center_update(self, teacher_output): + self.updated = False + self.len_teacher_output = len(teacher_output) + self.async_batch_center = torch.sum(teacher_output, dim=0, keepdim=True) + if dist.is_initialized(): + self.reduce_handle = dist.all_reduce(self.async_batch_center, async_op=True, group=get_process_subgroup()) + + @torch.no_grad() + def apply_center_update(self): + if self.updated is False: + world_size = get_subgroup_size() if dist.is_initialized() else 1 + + if self.reduce_handle is not None: + self.reduce_handle.wait() + _t = self.async_batch_center / (self.len_teacher_output * world_size) + + self.center = self.center * self.center_momentum + _t * (1 - self.center_momentum) + + self.updated = True diff --git a/starVLA/dinov3/dinov3/loss/gram_loss.py b/starVLA/dinov3/dinov3/loss/gram_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..4c2f0ac8726a137b0e963aba2a0f6bb1d19c3e6b --- /dev/null +++ b/starVLA/dinov3/dinov3/loss/gram_loss.py @@ -0,0 +1,84 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class GramLoss(nn.Module): + """Implementation of the gram loss""" + + def __init__( + self, + apply_norm=True, + img_level=True, + remove_neg=True, + remove_only_teacher_neg=False, + ): + super().__init__() + + # Loss + self.mse_loss = torch.nn.MSELoss() + + # Parameters + self.apply_norm = apply_norm + self.remove_neg = remove_neg + self.remove_only_teacher_neg = remove_only_teacher_neg + + if self.remove_neg or self.remove_only_teacher_neg: + assert self.remove_neg != self.remove_only_teacher_neg + + def forward(self, output_feats, target_feats, img_level=True): + """Compute the MSE loss between the gram matrix of the input and target features. + + Args: + output_feats: Pytorch tensor (B, N, dim) or (B*N, dim) if img_level == False + target_feats: Pytorch tensor (B, N, dim) or (B*N, dim) if img_level == False + img_level: bool, if true gram computed at the image level only else over the entire batch + Returns: + loss: scalar + """ + + # Dimensions of the tensor should be (B, N, dim) + if img_level: + assert len(target_feats.shape) == 3 and len(output_feats.shape) == 3 + + # Float casting + output_feats = output_feats.float() + target_feats = target_feats.float() + + # SSL correlation + if self.apply_norm: + target_feats = F.normalize(target_feats, dim=-1) + + if not img_level and len(target_feats.shape) == 3: + # Flatten (B, N, D) into (B*N, D) + target_feats = target_feats.flatten(0, 1) + + # Compute similarities + target_sim = torch.matmul(target_feats, target_feats.transpose(-1, -2)) + + # Patch correlation + if self.apply_norm: + output_feats = F.normalize(output_feats, dim=-1) + + if not img_level and len(output_feats.shape) == 3: + # Flatten (B, N, D) into (B*N, D) + output_feats = output_feats.flatten(0, 1) + + # Compute similarities + student_sim = torch.matmul(output_feats, output_feats.transpose(-1, -2)) + + if self.remove_neg: + target_sim[target_sim < 0] = 0.0 + student_sim[student_sim < 0] = 0.0 + + elif self.remove_only_teacher_neg: + # Remove only the negative sim values of the teacher + target_sim[target_sim < 0] = 0.0 + student_sim[(student_sim < 0) & (target_sim < 0)] = 0.0 + + return self.mse_loss(student_sim, target_sim) diff --git a/starVLA/dinov3/dinov3/loss/ibot_patch_loss.py b/starVLA/dinov3/dinov3/loss/ibot_patch_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..5412f0abf1675cb2f4d945bb4ef9e30ba32061c2 --- /dev/null +++ b/starVLA/dinov3/dinov3/loss/ibot_patch_loss.py @@ -0,0 +1,142 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import math + +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import nn + +from dinov3.distributed import get_process_subgroup, get_subgroup_size + + +def lossfunc(t, s, temp): # noqa: F811 + return torch.sum(t.float() * F.log_softmax(s.float() / temp, dim=-1), dim=-1) + + +class SinkhornKnoppTeacher(nn.Module): + """ + NOTE: This is a module and not a function in the `iBOTPatchLoss` class + This is because we want to torch.compile it, and torch.compil-ing a single + function with the `@torch.compile` decorator is bad. + It's better to `module.compile()` it, as we can control when we enable or + disable compilation globally. + """ + + @torch.no_grad() + def forward(self, teacher_output, teacher_temp, n_masked_patches_tensor, n_iterations=3): + teacher_output = teacher_output.float() + # world_size = dist.get_world_size() if dist.is_initialized() else 1 + Q = torch.exp(teacher_output / teacher_temp).t() # Q is K-by-B for consistency with notations from our paper + # B = Q.shape[1] * world_size # number of samples to assign + B = n_masked_patches_tensor + dist.all_reduce(B, group=get_process_subgroup()) + K = Q.shape[0] # how many prototypes + + # make the matrix sums to 1 + sum_Q = torch.sum(Q) + if dist.is_initialized(): + dist.all_reduce(sum_Q, group=get_process_subgroup()) + Q /= sum_Q + + for _ in range(n_iterations): + # normalize each row: total weight per prototype must be 1/K + sum_of_rows = torch.sum(Q, dim=1, keepdim=True) + if dist.is_initialized(): + dist.all_reduce(sum_of_rows, group=get_process_subgroup()) + Q /= sum_of_rows + Q /= K + + # normalize each column: total weight per sample must be 1/B + Q /= torch.sum(Q, dim=0, keepdim=True) + Q /= B + + Q *= B # the colomns must sum to 1 so that Q is an assignment + return Q.t() + + +class iBOTPatchLoss(nn.Module): + def __init__(self, patch_out_dim, student_temp=0.1, center_momentum=0.9): + super().__init__() + self.student_temp = student_temp + self.center_momentum = center_momentum + self.register_buffer("center", torch.full((1, 1, patch_out_dim), math.nan)) + self.updated = True + self.reduce_handle = None + self.len_teacher_patch_tokens = None + self.async_batch_center = None + self.sinkhorn_knopp_teacher = SinkhornKnoppTeacher() + self.sinkhorn_knopp_teacher.compile() + + def init_weights(self) -> None: + self.center.zero_() + + @torch.no_grad() + def softmax_center_teacher(self, teacher_patch_tokens, teacher_temp, update_centers=True): + if update_centers: + self.apply_center_update() + return F.softmax((teacher_patch_tokens - self.center) / teacher_temp, dim=-1) + + def forward(self, student_patch_tokens, teacher_patch_tokens, student_masks_flat): + """ + Cross-entropy between softmax outputs of the teacher and student networks. + student_patch_tokens: (B, N, D) tensor + teacher_patch_tokens: (B, N, D) tensor + student_masks_flat: (B, N) tensor + """ + t = teacher_patch_tokens + s = student_patch_tokens + loss = lossfunc(t, s, self.student_temp) + loss = torch.sum(loss * student_masks_flat.float(), dim=-1) / student_masks_flat.sum(dim=-1).clamp(min=1.0) + return -loss.mean() + + def forward_masked( + self, + student_patch_tokens_masked, + teacher_patch_tokens_masked, + student_masks_flat, + n_masked_patches=None, + masks_weight=None, + ): + t = teacher_patch_tokens_masked + s = student_patch_tokens_masked + # loss = torch.sum(t * F.log_softmax(s / self.student_temp, dim=-1), dim=-1) + loss = lossfunc(t, s, self.student_temp) + if masks_weight is None: + masks_weight = ( + (1 / student_masks_flat.sum(-1).clamp(min=1.0)) + .unsqueeze(-1) + .expand_as(student_masks_flat)[student_masks_flat] + ) + if n_masked_patches is not None: + loss = loss[:n_masked_patches] + loss = loss * masks_weight + return -loss.sum() / student_masks_flat.shape[0] + + @torch.no_grad() + def update_center(self, teacher_patch_tokens): + self.reduce_center_update(teacher_patch_tokens) + + @torch.no_grad() + def reduce_center_update(self, teacher_patch_tokens): + self.updated = False + self.len_teacher_patch_tokens = len(teacher_patch_tokens) + self.async_batch_center = torch.sum(teacher_patch_tokens.mean(1), dim=0, keepdim=True) + if dist.is_initialized(): + self.reduce_handle = dist.all_reduce(self.async_batch_center, async_op=True, group=get_process_subgroup()) + + @torch.no_grad() + def apply_center_update(self): + if self.updated is False: + world_size = get_subgroup_size() if dist.is_initialized() else 1 + + if self.reduce_handle is not None: + self.reduce_handle.wait() + _t = self.async_batch_center / (self.len_teacher_patch_tokens * world_size) + + self.center = self.center * self.center_momentum + _t * (1 - self.center_momentum) + + self.updated = True diff --git a/starVLA/dinov3/dinov3/loss/koleo_loss.py b/starVLA/dinov3/dinov3/loss/koleo_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..dee9194dbb0533b01a2012af6841606b6186847f --- /dev/null +++ b/starVLA/dinov3/dinov3/loss/koleo_loss.py @@ -0,0 +1,113 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import torch +import torch.distributed as torch_dist +import torch.nn as nn +import torch.nn.functional as F + +import dinov3.distributed as dist + + +class KoLeoLoss(nn.Module): + """Kozachenko-Leonenko entropic loss regularizer from Sablayrolles et al. - 2018 - Spreading vectors for similarity search""" + + def __init__(self): + super().__init__() + self.pdist = nn.PairwiseDistance(2, eps=1e-8) + + def pairwise_NNs_inner(self, x): + """ + Pairwise nearest neighbors for L2-normalized vectors. + Uses Torch rather than Faiss to remain on GPU. + """ + # parwise dot products (= inverse distance) + dots = torch.mm(x, x.t()) + n = x.shape[0] + dots.view(-1)[:: (n + 1)].fill_(-1) # Trick to fill diagonal with -1 + _, indices = torch.max(dots, dim=1) # max inner prod -> min distance + return indices + + def forward(self, student_output, eps=1e-8): + """ + Args: + student_output (BxD): backbone output of student + """ + with torch.autocast("cuda", enabled=False): + student_output = F.normalize(student_output, eps=eps, p=2, dim=-1) + indices = self.pairwise_NNs_inner(student_output) + distances = self.pdist(student_output, student_output[indices]) # BxD, BxD -> B + loss = -torch.log(distances + eps).mean() + return loss + + +class KoLeoLossDistributed(nn.Module): + """Kozachenko-Leonenko entropic loss regularizer from Sablayrolles et al. - 2018 - Spreading vectors for similarity search""" + + def __init__(self, topk=1, loss_group_size: int | None = None): + super().__init__() + self.pdist = nn.PairwiseDistance(2, eps=1e-8) + self.topk = topk + self.loss_group_size = loss_group_size # Size of the nearest neighbor set. If None, uses global batch size. + + def pairwise_NNs_inner(self, x, all_x, rank): + """ + Pairwise nearest neighbors for L2-normalized vectors. + Uses Torch rather than Faiss to remain on GPU. + """ + # parwise dot products (= inverse distance) + dots = torch.mm(x, all_x.t()) # local_B x global_B + local_B, global_B = dots.shape + dots.view(-1)[rank * local_B :: (global_B + 1)].fill_(-1) # Trick to fill diagonal with -1 + _, indices = torch.topk(dots, dim=1, k=self.topk) # max inner prod -> min distance + return indices + + def forward(self, student_output, eps=1e-8): + """ + Args: + student_output (BxD): backbone output of student + """ + with torch.autocast("cuda", enabled=False): + student_output = F.normalize(student_output, eps=eps, p=2, dim=-1) # local_B x D + + if dist.is_enabled(): + all_student_outputs = torch.cat(torch_dist.nn.all_gather(student_output), dim=0) # global_B x D + world_size = dist.get_world_size() + rank = dist.get_rank() + else: + all_student_outputs = student_output + world_size = 1 + rank = 0 + + # Group the global batch into groups of size `loss_group_size` and use the features of the group + # the local rank falls into as the nearest neighbor set for the local rank + local_B = len(student_output) + global_B = len(all_student_outputs) + loss_group_size = self.loss_group_size if self.loss_group_size is not None else global_B + if loss_group_size % local_B != 0: + raise ValueError( + f"Loss group size size {loss_group_size} must be a multiple of local batch size {local_B}." + ) + if global_B % loss_group_size != 0: + raise ValueError( + f"Global batch size {global_B} must be divisible by loss group size {loss_group_size}." + ) + n_groups = global_B // loss_group_size + ranks_per_group = world_size // n_groups + rank_in_group = rank % ranks_per_group + group = rank // ranks_per_group + all_student_outputs = all_student_outputs.view(n_groups, loss_group_size, student_output.shape[1]) + all_student_outputs = all_student_outputs[group] # loss_group_size x D + + with torch.no_grad(): + indices = self.pairwise_NNs_inner(student_output, all_student_outputs, rank_in_group) # local_B x topk + + student_output_expanded = ( + student_output.unsqueeze(1).repeat(1, self.topk, 1).flatten(0, 1) + ) # (local_B * topk) x D + distances = self.pdist(student_output_expanded, all_student_outputs[indices].flatten(0, 1)) # BxD, BxD -> B + loss = -torch.log(distances.float() + eps).mean() + + return loss diff --git a/starVLA/dinov3/dinov3/models/__init__.py b/starVLA/dinov3/dinov3/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb785a079a9326a1447baff40d6cb3eedde2c9a --- /dev/null +++ b/starVLA/dinov3/dinov3/models/__init__.py @@ -0,0 +1,133 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +from pathlib import Path + +from typing import Union + +import torch +import torch.nn as nn + +from dinov3.layers.fp8_linear import convert_linears_to_fp8 + +from . import vision_transformer as vits +from . import convnext + +logger = logging.getLogger("dinov3") + + +def init_fp8(model: nn.Module, args) -> nn.Module: + if not args.fp8_enabled: + logger.info("fp8 matmuls: OFF (disabled in config)") + return model + logger.info("fp8 matmuls: ON") + # Multi-kernel makes Inductor auto-tune between a regular "streaming"-based + # reduction kernel and a "persistent" reduction kernel. Since fp8 has some + # multi-pass steps (e.g., first get amax, then scale), persistent kernels + # should perform better. + torch._inductor.config.triton.multi_kernel = 1 + return convert_linears_to_fp8(model, filter=args.fp8_filter) + + +def build_model(args, only_teacher=False, img_size=224, device=None): + if "vit" in args.arch: + vit_kwargs = dict( + img_size=img_size, + patch_size=args.patch_size, + pos_embed_rope_base=args.pos_embed_rope_base, + pos_embed_rope_min_period=args.pos_embed_rope_min_period, + pos_embed_rope_max_period=args.pos_embed_rope_max_period, + pos_embed_rope_normalize_coords=args.pos_embed_rope_normalize_coords, + pos_embed_rope_shift_coords=args.pos_embed_rope_shift_coords, + pos_embed_rope_jitter_coords=args.pos_embed_rope_jitter_coords, + pos_embed_rope_rescale_coords=args.pos_embed_rope_rescale_coords, + qkv_bias=args.qkv_bias, + layerscale_init=args.layerscale, + norm_layer=args.norm_layer, + ffn_layer=args.ffn_layer, + ffn_bias=args.ffn_bias, + proj_bias=args.proj_bias, + n_storage_tokens=args.n_storage_tokens, + mask_k_bias=args.mask_k_bias, + untie_cls_and_patch_norms=args.untie_cls_and_patch_norms, + untie_global_and_local_cls_norm=args.untie_global_and_local_cls_norm, + device=device, + ) + teacher = vits.__dict__[args.arch](**vit_kwargs) + teacher = init_fp8(teacher, args) + if only_teacher: + return teacher, teacher.embed_dim + student = vits.__dict__[args.arch]( + **vit_kwargs, + drop_path_rate=args.drop_path_rate, + ) + embed_dim = student.embed_dim + elif "convnext" in args.arch: + convnext_cls = convnext.get_convnext_arch(args.arch) + convnext_kwargs = dict(patch_size=args.patch_size) + teacher = convnext_cls(**convnext_kwargs) + if only_teacher: + return teacher, teacher.embed_dim + student = convnext_cls(**convnext_kwargs) + embed_dim = student.embed_dim + else: + raise NotImplementedError(f"Unrecognized architecture {args.arch}") + student = init_fp8(student, args) + return student, teacher, embed_dim + + +def build_model_from_cfg(cfg, only_teacher: bool = False): + outputs = build_model( + cfg.student, + only_teacher=only_teacher, + img_size=cfg.crops.global_crops_size + if isinstance(cfg.crops.global_crops_size, int) + else max(cfg.crops.global_crops_size), + device="meta", + ) + if only_teacher: + teacher, embed_dim = outputs + return teacher, embed_dim + else: + student, teacher, embed_dim = outputs + return student, teacher, embed_dim + + +def build_model_for_eval( + config, + pretrained_weights: Union[str, Path] | None, + shard_unsharded_model: bool = False, # If the model is not sharded, shard it. No effect if already sharded on disk +): + model, _ = build_model_from_cfg(config, only_teacher=True) + if pretrained_weights is None or pretrained_weights == "": + logger.info("No pretrained weights") + model.init_weights() + elif Path(pretrained_weights).is_dir(): + logger.info("PyTorch DCP checkpoint") + from dinov3.checkpointer import load_checkpoint + from dinov3.fsdp.ac_compile_parallelize import ac_compile_parallelize + + moduledict = nn.ModuleDict({"backbone": model}) + # Wrap with FSDP + ac_compile_parallelize(moduledict, inference_only_models=[], cfg=config) + # Move to CUDA + model.to_empty(device="cuda") + # Load checkpoint + load_checkpoint(pretrained_weights, model=moduledict, strict_loading=True) + shard_unsharded_model = False + else: + logger.info("PyTorch consolidated checkpoint") + from dinov3.checkpointer import init_model_from_checkpoint_for_evals + + # consolidated checkpoint codepath + model.to_empty(device="cuda") + init_model_from_checkpoint_for_evals(model, pretrained_weights, "teacher") + if shard_unsharded_model: + logger.info("Sharding model") + moduledict = nn.ModuleDict({"backbone": model}) + ac_compile_parallelize(moduledict, inference_only_models=[], cfg=config) + model.eval() + return model diff --git a/starVLA/dinov3/dinov3/models/convnext.py b/starVLA/dinov3/dinov3/models/convnext.py new file mode 100644 index 0000000000000000000000000000000000000000..6300de5a9af0b673e67ff7ae31258aa06c205080 --- /dev/null +++ b/starVLA/dinov3/dinov3/models/convnext.py @@ -0,0 +1,350 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +from functools import partial +from typing import Dict, List, Optional, Sequence, Union + +import numpy as np +import torch +import torch.nn.functional as F +import torch.nn.init +from torch import Tensor, nn + + +logger = logging.getLogger("dinov3") + + +def drop_path(x: Tensor, drop_prob: float = 0.0, training: bool = False) -> Tensor: + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device) + random_tensor.floor_() # binarize + output = x.div(keep_prob) * random_tensor + return output + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None) -> None: + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x: Tensor) -> Tensor: + return drop_path(x, self.drop_prob, self.training) + + +class Block(nn.Module): + r"""ConvNeXt Block. There are two equivalent implementations: + (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) + (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back + We use (2) as we find it slightly faster in PyTorch + + Args: + dim (int): Number of input channels. + drop_path (float): Stochastic depth rate. Default: 0.0 + layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. + + Source: https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py + """ + + def __init__(self, dim, drop_path=0.0, layer_scale_init_value=1e-6): + super().__init__() + self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv + self.norm = LayerNorm(dim, eps=1e-6) + self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.pwconv2 = nn.Linear(4 * dim, dim) + self.layer_scale_init_value = layer_scale_init_value + self.gamma = ( + nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True) + if layer_scale_init_value > 0 + else None + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x): + input = x + x = self.dwconv(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.norm(x) + x = self.pwconv1(x) + x = self.act(x) + x = self.pwconv2(x) + if self.gamma is not None: + x = self.gamma * x + x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + + x = input + self.drop_path(x) + return x + + +class LayerNorm(nn.Module): + r"""LayerNorm that supports two data formats: channels_last (default) or channels_first. + The ordering of the dimensions in the inputs. channels_last corresponds to inputs with + shape (batch_size, height, width, channels) while channels_first corresponds to inputs + with shape (batch_size, channels, height, width). + + Source: https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py + """ + + def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"): + super().__init__() + self.weight = nn.Parameter(torch.empty(normalized_shape)) + self.bias = nn.Parameter(torch.empty(normalized_shape)) + self.eps = eps + self.data_format = data_format + if self.data_format not in ["channels_last", "channels_first"]: + raise NotImplementedError + self.normalized_shape = (normalized_shape,) + + def init_weights(self): + nn.init.ones_(self.weight) + nn.init.zeros_(self.bias) + + def forward(self, x): + if self.data_format == "channels_last": + return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + elif self.data_format == "channels_first": + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +class ConvNeXt(nn.Module): + r""" + Code adapted from https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.pyConvNeXt + + A PyTorch impl of : `A ConvNet for the 2020s` - + https://arxiv.org/pdf/2201.03545.pdf + + Args: + in_chans (int): Number of input image channels. Default: 3 + num_classes (int): Number of classes for classification head. Default: 1000 + depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3] + dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768] + drop_path_rate (float): Stochastic depth rate. Default: 0. + layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. + patch_size (int | None): Pseudo patch size. Used to resize feature maps to those of a ViT with a given patch size. If None, no resizing is performed + """ + + def __init__( + self, + # original ConvNeXt arguments + in_chans: int = 3, + depths: List[int] = [3, 3, 9, 3], + dims: List[int] = [96, 192, 384, 768], + drop_path_rate: float = 0.0, + layer_scale_init_value: float = 1e-6, + # DINO arguments + patch_size: int | None = None, + **ignored_kwargs, + ): + super().__init__() + if len(ignored_kwargs) > 0: + logger.warning(f"Ignored kwargs: {ignored_kwargs}") + del ignored_kwargs + + # ==== ConvNeXt's original init ===== + self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers + stem = nn.Sequential( + nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4), + LayerNorm(dims[0], eps=1e-6, data_format="channels_first"), + ) + self.downsample_layers.append(stem) + for i in range(3): + downsample_layer = nn.Sequential( + LayerNorm(dims[i], eps=1e-6, data_format="channels_first"), + nn.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2), + ) + self.downsample_layers.append(downsample_layer) + + self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks + dp_rates = [x for x in np.linspace(0, drop_path_rate, sum(depths))] + cur = 0 + for i in range(4): + stage = nn.Sequential( + *[ + Block(dim=dims[i], drop_path=dp_rates[cur + j], layer_scale_init_value=layer_scale_init_value) + for j in range(depths[i]) + ] + ) + self.stages.append(stage) + cur += depths[i] + + self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer + # ==== End of ConvNeXt's original init ===== + + # ==== DINO adaptation ==== + self.head = nn.Identity() # remove classification head + self.embed_dim = dims[-1] + self.embed_dims = dims # per layer dimensions + self.n_blocks = len(self.downsample_layers) # 4 + self.chunked_blocks = False + self.n_storage_tokens = 0 # no registers + + self.norms = nn.ModuleList([nn.Identity() for i in range(3)]) + self.norms.append(self.norm) + + self.patch_size = patch_size + self.input_pad_size = 4 # first convolution with kernel_size = 4, stride = 4 + + def init_weights(self): + self.apply(self._init_weights) + for stage_id, stage in enumerate(self.stages): + for block_id, block in enumerate(stage): + if block.gamma is not None: + nn.init.constant_(self.stages[stage_id][block_id].gamma, block.layer_scale_init_value) + + def _init_weights(self, module): + if isinstance(module, nn.LayerNorm): + module.reset_parameters() + if isinstance(module, LayerNorm): + nn.init.ones_(module.weight) + nn.init.zeros_(module.bias) + if isinstance(module, (nn.Conv2d, nn.Linear)): + nn.init.trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + + def forward_features(self, x: Tensor | List[Tensor], masks: Optional[Tensor] = None) -> List[Dict[str, Tensor]]: + if isinstance(x, torch.Tensor): + return self.forward_features_list([x], [masks])[0] + else: + return self.forward_features_list(x, masks) + + def forward_features_list(self, x_list: List[Tensor], masks_list: List[Tensor]) -> List[Dict[str, Tensor]]: + output = [] + for x, masks in zip(x_list, masks_list): + h, w = x.shape[-2:] + for i in range(4): + x = self.downsample_layers[i](x) + x = self.stages[i](x) + x_pool = x.mean([-2, -1]) # global average pooling, (N, C, H, W) -> (N, C) + x = torch.flatten(x, 2).transpose(1, 2) + + # concat [CLS] and patch tokens as (N, HW + 1, C), then normalize + x_norm = self.norm(torch.cat([x_pool.unsqueeze(1), x], dim=1)) + output.append( + { + "x_norm_clstoken": x_norm[:, 0], + "x_storage_tokens": x_norm[:, 1 : self.n_storage_tokens + 1], + "x_norm_patchtokens": x_norm[:, self.n_storage_tokens + 1 :], + "x_prenorm": x, + "masks": masks, + } + ) + + return output + + def forward(self, *args, is_training=False, **kwargs): + ret = self.forward_features(*args, **kwargs) + if is_training: + return ret + else: + return self.head(ret["x_norm_clstoken"]) + + def _get_intermediate_layers(self, x, n=1): + h, w = x.shape[-2:] + output, total_block_len = [], len(self.downsample_layers) + blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n + for i in range(total_block_len): + x = self.downsample_layers[i](x) + x = self.stages[i](x) + if i in blocks_to_take: + x_pool = x.mean([-2, -1]) + x_patches = x + if self.patch_size is not None: + # Resize output feature maps to that of a ViT with given patch_size + x_patches = nn.functional.interpolate( + x, + size=(h // self.patch_size, w // self.patch_size), + mode="bilinear", + antialias=True, + ) + output.append( + [ + x_pool, # CLS (B x C) + x_patches, # B x C x H x W + ] + ) + assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" + return output + + def get_intermediate_layers( + self, + x, + n: Union[int, Sequence] = 1, # Layers or n last layers to take, + reshape: bool = False, + return_class_token: bool = False, + norm: bool = True, + ): + outputs = self._get_intermediate_layers(x, n) + + if norm: + nchw_shapes = [out[-1].shape for out in outputs] + if isinstance(n, int): + norms = self.norms[-n:] + else: + norms = [self.norms[i] for i in n] + outputs = [ + ( + norm(cls_token), # N x C + norm(patches.flatten(-2, -1).permute(0, 2, 1)), # N x HW x C + ) + for (cls_token, patches), norm in zip(outputs, norms) + ] + if reshape: + outputs = [ + (cls_token, patches.permute(0, 2, 1).reshape(*nchw).contiguous()) + for (cls_token, patches), nchw in zip(outputs, nchw_shapes) + ] + elif not reshape: + # force B x N x C format for patch tokens + outputs = [(cls_token, patches.flatten(-2, -1).permute(0, 2, 1)) for (cls_token, patches) in outputs] + class_tokens = [out[0] for out in outputs] + outputs = [out[1] for out in outputs] + if return_class_token: + return tuple(zip(outputs, class_tokens)) + return tuple(outputs) + + +convnext_sizes = { + "tiny": dict( + depths=[3, 3, 9, 3], + dims=[96, 192, 384, 768], + ), + "small": dict( + depths=[3, 3, 27, 3], + dims=[96, 192, 384, 768], + ), + "base": dict( + depths=[3, 3, 27, 3], + dims=[128, 256, 512, 1024], + ), + "large": dict( + depths=[3, 3, 27, 3], + dims=[192, 384, 768, 1536], + ), +} + + +def get_convnext_arch(arch_name): + size_dict = None + query_sizename = arch_name.split("_")[1] + try: + size_dict = convnext_sizes[query_sizename] + except KeyError: + raise NotImplementedError("didn't recognize vit size string") + + return partial( + ConvNeXt, + **size_dict, + ) diff --git a/starVLA/dinov3/dinov3/models/vision_transformer.py b/starVLA/dinov3/dinov3/models/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..51316e518850cd607ffddc40c40bd39e8f2a03c2 --- /dev/null +++ b/starVLA/dinov3/dinov3/models/vision_transformer.py @@ -0,0 +1,416 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +from functools import partial +from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union + +import torch +import torch.nn.init +from torch import Tensor, nn + +from dinov3.layers import LayerScale, Mlp, PatchEmbed, RMSNorm, RopePositionEmbedding, SelfAttentionBlock, SwiGLUFFN +from dinov3.utils import named_apply + +logger = logging.getLogger("dinov3") + +ffn_layer_dict = { + "mlp": Mlp, + "swiglu": SwiGLUFFN, + "swiglu32": partial(SwiGLUFFN, align_to=32), + "swiglu64": partial(SwiGLUFFN, align_to=64), + "swiglu128": partial(SwiGLUFFN, align_to=128), +} + +norm_layer_dict = { + "layernorm": partial(nn.LayerNorm, eps=1e-6), + "layernormbf16": partial(nn.LayerNorm, eps=1e-5), + "rmsnorm": RMSNorm, +} + +dtype_dict = { + "fp32": torch.float32, + "fp16": torch.float16, + "bf16": torch.bfloat16, +} + + +def init_weights_vit(module: nn.Module, name: str = ""): + if isinstance(module, nn.Linear): + torch.nn.init.trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + if hasattr(module, "bias_mask") and module.bias_mask is not None: + o = module.out_features + module.bias_mask.fill_(1) + module.bias_mask[o // 3 : 2 * o // 3].fill_(0) + if isinstance(module, nn.LayerNorm): + module.reset_parameters() + if isinstance(module, LayerScale): + module.reset_parameters() + if isinstance(module, PatchEmbed): + module.reset_parameters() + if isinstance(module, RMSNorm): + module.reset_parameters() + + +class DinoVisionTransformer(nn.Module): + def __init__( + self, + *, + img_size: int = 224, + patch_size: int = 16, + in_chans: int = 3, + pos_embed_rope_base: float = 100.0, + pos_embed_rope_min_period: float | None = None, + pos_embed_rope_max_period: float | None = None, + pos_embed_rope_normalize_coords: Literal["min", "max", "separate"] = "separate", + pos_embed_rope_shift_coords: float | None = None, + pos_embed_rope_jitter_coords: float | None = None, + pos_embed_rope_rescale_coords: float | None = None, + pos_embed_rope_dtype: str = "bf16", + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + ffn_ratio: float = 4.0, + qkv_bias: bool = True, + drop_path_rate: float = 0.0, + layerscale_init: float | None = None, + norm_layer: str = "layernorm", + ffn_layer: str = "mlp", + ffn_bias: bool = True, + proj_bias: bool = True, + n_storage_tokens: int = 0, + mask_k_bias: bool = False, + untie_cls_and_patch_norms: bool = False, + untie_global_and_local_cls_norm: bool = False, + device: Any | None = None, + **ignored_kwargs, + ): + super().__init__() + if len(ignored_kwargs) > 0: + logger.warning(f"Ignored kwargs: {ignored_kwargs}") + del ignored_kwargs + + norm_layer_cls = norm_layer_dict[norm_layer] + + self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models + self.n_blocks = depth + self.num_heads = num_heads + self.patch_size = patch_size + + self.patch_embed = PatchEmbed( + img_size=img_size, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + flatten_embedding=False, + ) + + self.cls_token = nn.Parameter(torch.empty(1, 1, embed_dim, device=device)) + self.n_storage_tokens = n_storage_tokens + if self.n_storage_tokens > 0: + self.storage_tokens = nn.Parameter(torch.empty(1, n_storage_tokens, embed_dim, device=device)) + logger.info(f"using base={pos_embed_rope_base} for rope new") + logger.info(f"using min_period={pos_embed_rope_min_period} for rope new") + logger.info(f"using max_period={pos_embed_rope_max_period} for rope new") + logger.info(f"using normalize_coords={pos_embed_rope_normalize_coords} for rope new") + logger.info(f"using shift_coords={pos_embed_rope_shift_coords} for rope new") + logger.info(f"using rescale_coords={pos_embed_rope_rescale_coords} for rope new") + logger.info(f"using jitter_coords={pos_embed_rope_jitter_coords} for rope new") + logger.info(f"using dtype={pos_embed_rope_dtype} for rope new") + self.rope_embed = RopePositionEmbedding( + embed_dim=embed_dim, + num_heads=num_heads, + base=pos_embed_rope_base, + min_period=pos_embed_rope_min_period, + max_period=pos_embed_rope_max_period, + normalize_coords=pos_embed_rope_normalize_coords, + shift_coords=pos_embed_rope_shift_coords, + jitter_coords=pos_embed_rope_jitter_coords, + rescale_coords=pos_embed_rope_rescale_coords, + dtype=dtype_dict[pos_embed_rope_dtype], + device=device, + ) + logger.info(f"using {ffn_layer} layer as FFN") + ffn_layer_cls = ffn_layer_dict[ffn_layer] + ffn_ratio_sequence = [ffn_ratio] * depth + blocks_list = [ + SelfAttentionBlock( + dim=embed_dim, + num_heads=num_heads, + ffn_ratio=ffn_ratio_sequence[i], + qkv_bias=qkv_bias, + proj_bias=proj_bias, + ffn_bias=ffn_bias, + drop_path=drop_path_rate, + norm_layer=norm_layer_cls, + act_layer=nn.GELU, + ffn_layer=ffn_layer_cls, + init_values=layerscale_init, + mask_k_bias=mask_k_bias, + device=device, + ) + for i in range(depth) + ] + + self.chunked_blocks = False + self.blocks = nn.ModuleList(blocks_list) + + # This norm is applied to everything, or when untying, to patch and mask tokens. + self.norm = norm_layer_cls(embed_dim) + + self.untie_cls_and_patch_norms = untie_cls_and_patch_norms + if untie_cls_and_patch_norms: + # When untying, this norm is applied to CLS tokens and registers. + self.cls_norm = norm_layer_cls(embed_dim) + else: + self.cls_norm = None + + self.untie_global_and_local_cls_norm = untie_global_and_local_cls_norm + if untie_global_and_local_cls_norm: + # When untying, this norm is applied to local CLS tokens and registers. + # This norm is never used during eval. + self.local_cls_norm = norm_layer_cls(embed_dim) + else: + self.local_cls_norm = None + self.head = nn.Identity() + self.mask_token = nn.Parameter(torch.empty(1, embed_dim, device=device)) + + def init_weights(self): + self.rope_embed._init_weights() + nn.init.normal_(self.cls_token, std=0.02) + if self.n_storage_tokens > 0: + nn.init.normal_(self.storage_tokens, std=0.02) + nn.init.zeros_(self.mask_token) + named_apply(init_weights_vit, self) + + def prepare_tokens_with_masks(self, x: Tensor, masks=None) -> Tuple[Tensor, Tuple[int]]: + x = self.patch_embed(x) + B, H, W, _ = x.shape + x = x.flatten(1, 2) + + if masks is not None: + x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x) + cls_token = self.cls_token + else: + cls_token = self.cls_token + 0 * self.mask_token + if self.n_storage_tokens > 0: + storage_tokens = self.storage_tokens + else: + storage_tokens = torch.empty( + 1, + 0, + cls_token.shape[-1], + dtype=cls_token.dtype, + device=cls_token.device, + ) + + x = torch.cat( + [ + cls_token.expand(B, -1, -1), + storage_tokens.expand(B, -1, -1), + x, + ], + dim=1, + ) + + return x, (H, W) + + def forward_features_list(self, x_list: List[Tensor], masks_list: List[Tensor]) -> List[Dict[str, Tensor]]: + x = [] + rope = [] + for t_x, t_masks in zip(x_list, masks_list): + t2_x, hw_tuple = self.prepare_tokens_with_masks(t_x, t_masks) + x.append(t2_x) + rope.append(hw_tuple) + for _, blk in enumerate(self.blocks): + if self.rope_embed is not None: + rope_sincos = [self.rope_embed(H=H, W=W) for H, W in rope] + else: + rope_sincos = [None for r in rope] + x = blk(x, rope_sincos) + all_x = x + output = [] + for idx, (x, masks) in enumerate(zip(all_x, masks_list)): + if self.untie_cls_and_patch_norms or self.untie_global_and_local_cls_norm: + if self.untie_global_and_local_cls_norm and self.training and idx == 1: + # Assume second entry of list corresponds to local crops. + # We only ever apply this during training. + x_norm_cls_reg = self.local_cls_norm(x[:, : self.n_storage_tokens + 1]) + elif self.untie_cls_and_patch_norms: + x_norm_cls_reg = self.cls_norm(x[:, : self.n_storage_tokens + 1]) + else: + x_norm_cls_reg = self.norm(x[:, : self.n_storage_tokens + 1]) + x_norm_patch = self.norm(x[:, self.n_storage_tokens + 1 :]) + else: + x_norm = self.norm(x) + x_norm_cls_reg = x_norm[:, : self.n_storage_tokens + 1] + x_norm_patch = x_norm[:, self.n_storage_tokens + 1 :] + output.append( + { + "x_norm_clstoken": x_norm_cls_reg[:, 0], + "x_storage_tokens": x_norm_cls_reg[:, 1:], + "x_norm_patchtokens": x_norm_patch, + "x_prenorm": x, + "masks": masks, + } + ) + return output + + def forward_features(self, x: Tensor | List[Tensor], masks: Optional[Tensor] = None) -> List[Dict[str, Tensor]]: + if isinstance(x, torch.Tensor): + return self.forward_features_list([x], [masks])[0] + else: + return self.forward_features_list(x, masks) + + def _get_intermediate_layers_not_chunked(self, x: Tensor, n: int = 1) -> List[Tensor]: + x, (H, W) = self.prepare_tokens_with_masks(x) + # If n is an int, take the n last blocks. If it's a list, take them + output, total_block_len = [], len(self.blocks) + blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n + for i, blk in enumerate(self.blocks): + if self.rope_embed is not None: + rope_sincos = self.rope_embed(H=H, W=W) + else: + rope_sincos = None + x = blk(x, rope_sincos) + if i in blocks_to_take: + output.append(x) + assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" + return output + + def get_intermediate_layers( + self, + x: torch.Tensor, + *, + n: Union[int, Sequence] = 1, # Layers or n last layers to take + reshape: bool = False, + return_class_token: bool = False, + return_extra_tokens: bool = False, + norm: bool = True, + ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor, ...]]]: + outputs = self._get_intermediate_layers_not_chunked(x, n) + if norm: + outputs_normed = [] + for out in outputs: + if self.untie_cls_and_patch_norms: + x_norm_cls_reg = self.cls_norm(out[:, : self.n_storage_tokens + 1]) + x_norm_patch = self.norm(out[:, self.n_storage_tokens + 1 :]) + outputs_normed.append(torch.cat((x_norm_cls_reg, x_norm_patch), dim=1)) + else: + outputs_normed.append(self.norm(out)) + outputs = outputs_normed + class_tokens = [out[:, 0] for out in outputs] + extra_tokens = [out[:, 1 : self.n_storage_tokens + 1] for out in outputs] + outputs = [out[:, self.n_storage_tokens + 1 :] for out in outputs] + if reshape: + B, _, h, w = x.shape + outputs = [ + out.reshape(B, h // self.patch_size, w // self.patch_size, -1).permute(0, 3, 1, 2).contiguous() + for out in outputs + ] + if not return_class_token and not return_extra_tokens: + return tuple(outputs) + elif return_class_token and not return_extra_tokens: + return tuple(zip(outputs, class_tokens)) + elif not return_class_token and return_extra_tokens: + return tuple(zip(outputs, extra_tokens)) + elif return_class_token and return_extra_tokens: + return tuple(zip(outputs, class_tokens, extra_tokens)) + + def forward(self, *args, is_training: bool = False, **kwargs) -> List[Dict[str, Tensor]] | Tensor: + ret = self.forward_features(*args, **kwargs) + if is_training: + return ret + else: + return self.head(ret["x_norm_clstoken"]) + + +def vit_small(patch_size=16, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=12, + num_heads=6, + ffn_ratio=4, + **kwargs, + ) + return model + + +def vit_base(patch_size=16, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=12, + num_heads=12, + ffn_ratio=4, + **kwargs, + ) + return model + + +def vit_large(patch_size=16, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + ffn_ratio=4, + **kwargs, + ) + return model + + +def vit_so400m(patch_size=16, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1152, + depth=27, + num_heads=18, + ffn_ratio=3.777777778, + **kwargs, + ) + return model + + +def vit_huge2(patch_size=16, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1280, + depth=32, + num_heads=20, + ffn_ratio=4, + **kwargs, + ) + return model + + +def vit_giant2(patch_size=16, **kwargs): + """ + Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 + """ + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=1536, + depth=40, + num_heads=24, + ffn_ratio=4, + **kwargs, + ) + return model + + +def vit_7b(patch_size=16, **kwargs): + model = DinoVisionTransformer( + patch_size=patch_size, + embed_dim=4096, + depth=40, + num_heads=32, + ffn_ratio=3, + **kwargs, + ) + return model diff --git a/starVLA/dinov3/dinov3/run/__init__.py b/starVLA/dinov3/dinov3/run/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dinov3/dinov3/run/init.py b/starVLA/dinov3/dinov3/run/init.py new file mode 100644 index 0000000000000000000000000000000000000000..b3d96d718f5b3b63702cd0b40bbaefcab0dfecca --- /dev/null +++ b/starVLA/dinov3/dinov3/run/init.py @@ -0,0 +1,33 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import contextlib +from datetime import timedelta +from typing import Optional + +from dinov3.configs import exit_job, setup_job + + +@contextlib.contextmanager +def job_context( + output_dir: Optional[str] = None, + distributed_enabled: bool = True, + logging_enabled: bool = True, + seed: Optional[int] = 0, + restrict_print_to_main_process: bool = True, + distributed_timeout: timedelta | None = None, +): + setup_job( + output_dir=output_dir, + distributed_enabled=distributed_enabled, + logging_enabled=logging_enabled, + seed=seed, + restrict_print_to_main_process=restrict_print_to_main_process, + distributed_timeout=distributed_timeout, + ) + try: + yield + finally: + exit_job(distributed_enabled=distributed_enabled, logging_enabled=logging_enabled) diff --git a/starVLA/dinov3/dinov3/run/submit.py b/starVLA/dinov3/dinov3/run/submit.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad14edc26b02dd16e82bb636ac9cd43467082cd --- /dev/null +++ b/starVLA/dinov3/dinov3/run/submit.py @@ -0,0 +1,208 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import argparse +import logging +import os +from pathlib import Path + +from dinov3.logging import setup_logging +from dinov3.utils.cluster import ( + get_slurm_account, + get_slurm_executor_parameters, + get_slurm_partition, + get_slurm_qos, + get_user_checkpoint_path, +) +from dinov3.utils.custom_callable import load_custom_callable + +logger = logging.getLogger("dinov3") + + +def get_submitit_parser(): + slurm_partition = get_slurm_partition() + slurm_account = get_slurm_account() + slurm_qos = get_slurm_qos() + parser = argparse.ArgumentParser("Submitit arguments", add_help=False) + parser.add_argument( + "--ngpus", + default=8, + type=int, + help="Number of gpus to request on each node, default: %(default)s", + ) + parser.add_argument( + "--nodes", + default=1, + type=int, + help="Number of nodes to request, default: %(default)s", + ) + parser.add_argument( + "--timeout", + default=2800, + type=int, + help="Duration of the job, default: %(default)s", + ) + parser.add_argument( + "--slurm-partition", + default=slurm_partition, + type=str, + help="Partition where to submit, default: %(default)s", + ) + parser.add_argument( + "--slurm-qos", + default=slurm_qos, + metavar="SLURM_QOS", + type=str, + dest="slurm_qos", + help="slurm QoS to use for jobs in cluster environment, default: %(default)s", + ) + parser.add_argument( + "--slurm-array-parallelism", + default=256, + type=int, + help="Maximum number of jobs that will be executed in parallel, default: %(default)s", + ) + parser.add_argument( + "--slurm-nice", + default=0, + type=int, + help="Adjusted scheduling priority within Slurm, default: %(default)s", + ) + parser.add_argument( + "--slurm-account", + default=slurm_account, + type=str, + help="Slurm account name, default: %(default)s", + ) + parser.add_argument( + "--comment", + default="", + type=str, + help="Comment to pass to scheduler, e.g. priority message, default: '%(default)s'", + ) + parser.add_argument( + "--exclude", + default="", + type=str, + help="Nodes to exclude, default: '%(default)s'", + ) + parser.add_argument( + "--output-dir", + type=str, + help="output dir", + ) + return parser + + +def get_run_parser(): + parser = argparse.ArgumentParser("Launcher arguments", parents=[get_submitit_parser()]) + parser.add_argument( + "module_path", + type=str, + help="Full path to the program/script to be launched in parallel, " + "followed by all the arguments for the training script.", + ) + parser.add_argument( + "--callable-name", + type=str, + default="main", + help="Name of the callable to execute in the script", + ) + return parser + + +def get_shared_folder() -> Path: + user_checkpoint_path = get_user_checkpoint_path() + if user_checkpoint_path is None: + raise RuntimeError("Path to user checkpoint cannot be determined") + path = user_checkpoint_path / "experiments" + path.mkdir(exist_ok=True) + return path + + +class CheckpointableSubmitter: + def __init__(self, module_path, callable_name, args, output_dir): + self.args = args + self.callable_name = callable_name + self.module_path = os.path.realpath(module_path) + self.output_dir = os.path.realpath(output_dir) + + def __call__(self): + self._setup_args() + callable_ = load_custom_callable(self.module_path, self.callable_name) + callable_(self.args) + + def checkpoint(self): + import submitit + + logger.info(f"Requeuing {self.callable_name} from {self.module_path} with {self.args}") + empty_class = type(self)(self.module_path, self.callable_name, self.args, self.output_dir) + return submitit.helpers.DelayedSubmission(empty_class) + + def _setup_args(self): + import submitit + + job_env = submitit.JobEnvironment() + self.output_dir = str(self.output_dir).replace("%j", str(job_env.job_id)) + if "--output-dir" not in self.args: + self.args.insert(0, f"--output-dir={self.output_dir}") + + # Setup logging with exact same arguments as in fairvit/run/init.py + # to use lru_cache memoization and avoid setting up the logger twice + setup_logging(output=self.output_dir, level=logging.INFO) + logger.info(f"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}") + logger.info(f"Module Path: {self.module_path}") + logger.info(f"Callable Name: {self.callable_name}") + logger.info(f'Args: {" ".join(self.args)}') + + +def submit_jobs(class_to_submit, output_dir, submitit_args, name="fairvit"): + import submitit + + Path(output_dir).mkdir(parents=True, exist_ok=True) + executor = submitit.AutoExecutor(folder=output_dir, slurm_max_num_timeout=30) + + kwargs = {} + if submitit_args.comment: + kwargs["slurm_comment"] = submitit_args.comment + if submitit_args.exclude: + kwargs["slurm_exclude"] = submitit_args.exclude + + executor_params = get_slurm_executor_parameters( + nodes=submitit_args.nodes, + num_gpus_per_node=submitit_args.ngpus, + timeout_min=submitit_args.timeout, # max is 60 * 72 + slurm_signal_delay_s=120, + slurm_partition=submitit_args.slurm_partition, + slurm_qos=submitit_args.slurm_qos, + # slurm_account=submitit_args.slurm_account, + slurm_additional_parameters=dict(nice=submitit_args.slurm_nice), + **kwargs, + ) + executor.update_parameters(name=name, **executor_params) + job = executor.submit(class_to_submit) + + logger.info(f"Submitted job_id: {job.job_id}") + str_output_dir = os.path.abspath(output_dir).replace("%j", str(job.job_id)) + logger.info(f"Logs and checkpoints will be saved at: {str_output_dir}") + + +def main(): + setup_logging(level=logging.INFO) + args, script_args = get_run_parser().parse_known_args() + assert os.path.exists(args.module_path), "The module path does not exist" + + file_name = os.path.splitext(os.path.split(args.module_path)[1])[0] + name = f"{file_name}:{args.callable_name}" + + if args.output_dir is None: + args.output_dir = get_shared_folder() / "%j" + + class_to_submit = CheckpointableSubmitter(args.module_path, args.callable_name, script_args, args.output_dir) + submit_jobs(class_to_submit, args.output_dir, args, name=name) + + +if __name__ == "__main__": + main() diff --git a/starVLA/dinov3/dinov3/thirdparty/CLIP/__init__.py b/starVLA/dinov3/dinov3/thirdparty/CLIP/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dinov3/dinov3/thirdparty/CLIP/clip/__init__.py b/starVLA/dinov3/dinov3/thirdparty/CLIP/clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dinov3/dinov3/thirdparty/CLIP/clip/simple_tokenizer.py b/starVLA/dinov3/dinov3/thirdparty/CLIP/clip/simple_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e424249d57012833247c058e9e9f581e2b8097c9 --- /dev/null +++ b/starVLA/dinov3/dinov3/thirdparty/CLIP/clip/simple_tokenizer.py @@ -0,0 +1,143 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +# References: +# https://github.com/openai/CLIP/blob/main/clip/simple_tokenizer.py + +import gzip +import html +import os +from functools import lru_cache + +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] + 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: + new_word.extend(word[i:]) + 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/starVLA/dinov3/dinov3/thirdparty/__init__.py b/starVLA/dinov3/dinov3/thirdparty/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/dinov3/dinov3/train/__init__.py b/starVLA/dinov3/dinov3/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39e2108eb60628bb32958c7b373e76f68a10e891 --- /dev/null +++ b/starVLA/dinov3/dinov3/train/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from .multidist_meta_arch import MultiDistillationMetaArch +from .ssl_meta_arch import SSLMetaArch +from .train import get_args_parser, main diff --git a/starVLA/dinov3/dinov3/train/cosine_lr_scheduler.py b/starVLA/dinov3/dinov3/train/cosine_lr_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..2c61d7d01f573bca1e1111586244ef00587dd1f3 --- /dev/null +++ b/starVLA/dinov3/dinov3/train/cosine_lr_scheduler.py @@ -0,0 +1,85 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging + +import numpy as np + +logger = logging.getLogger("dinov3") + + +class CosineScheduler(object): + def __init__( + self, + base_value, + final_value, + total_iters, + warmup_iters=0, + start_warmup_value=0, + freeze_iters=0, + trunc_extra=0.0, + ): + super().__init__() + self.final_value = np.float64(final_value) + self.total_iters = total_iters + + freeze_schedule = np.zeros((freeze_iters)) + + warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) + + if trunc_extra == 0.0: + iters = np.arange(total_iters - warmup_iters - freeze_iters) + schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters))) + else: + cosine_steps = total_iters - warmup_iters - freeze_iters + iters = np.linspace(0, np.pi, int((1 + trunc_extra) * cosine_steps))[:cosine_steps] + schedule = np.cos(iters) + schedule = (schedule + 1) / 2 + schedule = (schedule - schedule[-1]) / (1 - schedule[-1]) + schedule = schedule * (base_value - final_value) + final_value + + self.schedule = np.concatenate((freeze_schedule, warmup_schedule, schedule), dtype=np.float64) + + assert len(self.schedule) == self.total_iters + + def __getitem__(self, it): + if it >= self.total_iters: + return self.final_value + else: + return self.schedule[it] + + +def linear_warmup_cosine_decay( + start: float, + peak: float, + end: float, + warmup_iterations: int, + total_iterations: int, + cosine_iterations: int | None = None, +) -> np.ndarray: + """ + Create a learning rate schedule with linear warmup, a cosine, and an optional constant part in the end. + + Args: + start (float): Initial learning rate. + peak (float): Learning rate after linear warmup. + end (float): Final learning rate after cosine. + warmup_iterations (int): Number of iterations for linear warmup. + total_iterations (int): Total number of iterations for the schedule. + cosine_iterations (int | None): Number of iterations for cosine. + If None, cosine part will be over remaining iterations after warmup. + Returns: + np.ndarray: Learning rate schedule as a numpy array. + """ + linear = np.linspace(start, peak, warmup_iterations, endpoint=False) + if cosine_iterations is None: + cosine_iterations = total_iterations - warmup_iterations + cosine = np.cos(np.linspace(0, np.pi, cosine_iterations)) + cosine = (cosine + 1) / 2 + cosine = (peak - end) * cosine + end + remaining_iterations = total_iterations - cosine_iterations - warmup_iterations + assert remaining_iterations >= 0 + constant = np.full((remaining_iterations,), fill_value=end) + return np.concatenate([linear, cosine, constant]) diff --git a/starVLA/dinov3/dinov3/train/multidist_meta_arch.py b/starVLA/dinov3/dinov3/train/multidist_meta_arch.py new file mode 100644 index 0000000000000000000000000000000000000000..1b8819357597c1183f8b50b63734f025053bc638 --- /dev/null +++ b/starVLA/dinov3/dinov3/train/multidist_meta_arch.py @@ -0,0 +1,165 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging + +import torch +from torch import Tensor + +from .ssl_meta_arch import SSLMetaArch + +logger = logging.getLogger("dinov3") + + +class MultiDistillationMetaArch(SSLMetaArch): + """ + Multidistillation version of SSLMetaArchCompilableGram: + - baked-in scales for DINO, KOLEO, and IBOT losses + - always global and local crops + - always separate heads for DINO and IBOT + - always sinkhorn-knopp centering for DINO and IBOT + - always per-GPU computation of KOLEO loss (non-distributed) + - DINO, IBOT, and KOLEO are always computed even if their weight is 0.0 + """ + + def forward_backward( + self, data, *, teacher_temp, iteration: int = 0, **ignored_kwargs + ) -> tuple[Tensor, dict[str, float | Tensor]]: + del ignored_kwargs + metrics_dict = {} + + # Shapes + n_global_crops = 2 + n_local_crops = self.n_local_crops # self.cfg.crops.local_crops_number + B_teacher = B = data["collated_local_crops"].shape[0] // n_local_crops + assert data["collated_global_crops"].shape[0] == n_global_crops * B + metrics_dict["batch_size"] = B + + global_crops = data["collated_global_crops"].cuda(non_blocking=True) + local_crops = data["collated_local_crops"].cuda(non_blocking=True) + masks = data["collated_masks"].cuda(non_blocking=True) + mask_indices_list = data["mask_indices_list"].cuda(non_blocking=True) + masks_weight = data["masks_weight"].cuda(non_blocking=True) + n_masked_patches_tensor = data["n_masked_patches"].cuda(non_blocking=True) + global_batch_size = data["global_batch_size"] + + # Multidistillation codepath: + + # Downsample teacher crops to match student resolution + downsampling_factor = getattr(self, "crops.teacher_to_student_resolution_scale", 1.0) + if downsampling_factor != 1.0: + global_crops = torch.nn.functional.interpolate( + global_crops, + scale_factor=1.0 / downsampling_factor, + mode="bilinear", + antialias=True, + ) + global_crops_subgroup = self.broadcast_to_subgroups( + global_crops.view(n_global_crops, -1, *global_crops.shape[1:]), + 1, + global_batch_size=global_batch_size, + ).view(-1, *global_crops.shape[1:]) + local_crops_subgroup = self.broadcast_to_subgroups( + local_crops.view(n_local_crops, -1, *local_crops.shape[1:]), + 1, + global_batch_size=global_batch_size, + ).view(-1, *local_crops.shape[1:]) + B = local_crops_subgroup.shape[0] // n_local_crops + + # Teacher output (will trigger an all-gather to unshard) + teacher_global = self.get_teacher_output( + global_crops.unflatten(0, (n_global_crops, B_teacher)), + teacher_temp=teacher_temp, + n_masked_patches_tensor=n_masked_patches_tensor, + mask_indices_list=mask_indices_list, + upperbound=data["upperbound"], + global_batch_size=global_batch_size, + ) + + # Student output (will trigger an all-gather to unshard) + student_global, student_local = self.get_student_output( + global_crops=global_crops_subgroup.unflatten(0, (n_global_crops, B)), + local_crops=local_crops_subgroup.unflatten(0, (n_local_crops, B)), + upperbound=data["upperbound"], + masks=masks, + mask_indices_list=mask_indices_list, + ) + # End of multidistillation codepath + + # Compute losses and backprop + loss_accumulator, loss_dict = self.compute_losses( + teacher_global=teacher_global, + student_global=student_global, + student_local=student_local, + masks=masks, + mask_indices_list=mask_indices_list, + masks_weight=masks_weight, + gram_global=None, + iteration=iteration, + ) + + self.backprop_loss(loss_accumulator) + + # Return total weighted loss and a dict of metrics to log + return loss_accumulator, metrics_dict | loss_dict + + @torch.no_grad() + def get_teacher_output( + self, + images, + *, + upperbound, + mask_indices_list, + teacher_temp, + n_masked_patches_tensor, + global_batch_size, + ): + n_crops, B_teacher, rgb, H, W = images.shape + + backbone_out = self.teacher.backbone(images.flatten(0, 1), is_training=True) + cls = backbone_out["x_norm_clstoken"] # [n_crops * B, D] + reg = backbone_out["x_storage_tokens"] # [n_crops * B, R, D] + ibot_patch = backbone_out["x_norm_patchtokens"] # [n_crops * B, P, D] + + R, D = reg.shape[-2:] + + # Multidistillation codepath: + # IBOT head only on patches that are masked for the student + n_tokens = ibot_patch.shape[1] + masked_patch_after_head = self.teacher.ibot_head(ibot_patch.flatten(0, 1), no_last_layer=True) + masked_patch_after_head = masked_patch_after_head.view(n_crops, -1, *masked_patch_after_head.shape[1:]) + masked_patch_after_head = self.broadcast_to_subgroups( + masked_patch_after_head, + over_dim=1, + global_batch_size=global_batch_size * n_tokens, + ) + buffer = torch.index_select(masked_patch_after_head.flatten(0, 1), dim=0, index=mask_indices_list) + masked_patch_after_head = self.teacher.ibot_head(buffer, only_last_layer=True) + + # DINO head on CLS tokens + cls_after_head = self.teacher.dino_head(cls, no_last_layer=True) # [n_crops * B, K] + cls_after_head = cls_after_head.view(n_crops, -1, *cls_after_head.shape[1:]) + cls_after_head = self.broadcast_to_subgroups(cls_after_head, over_dim=1, global_batch_size=global_batch_size) + B = cls_after_head.shape[1] + cls_after_head = cls_after_head.flatten(0, 1) + cls_after_head = self.teacher.dino_head(cls_after_head, only_last_layer=True) # [n_crops * B, K] + # End of multidistillation codepath + + # Center with sinkhorn-knopp + cls_centered = self.dino_loss.sinkhorn_knopp_teacher( + cls_after_head, teacher_temp=teacher_temp + ) # [n_crops * B, K] + cls_centered = cls_centered.unflatten(0, (n_crops, B)) # [n_crops, B, K] + masked_patch_centered = self.ibot_patch_loss.sinkhorn_knopp_teacher( + masked_patch_after_head, + teacher_temp=teacher_temp, + n_masked_patches_tensor=n_masked_patches_tensor, + ) # [n_masked_patches, K] + + return { + "cls_after_head": cls_after_head.unflatten(0, [n_crops, B]), # [n_crops, B, K] + "cls_centered": cls_centered, # [n_crops, B, K] + "masked_patch_centered": masked_patch_centered, # [n_masked_patches, K] + } diff --git a/starVLA/dinov3/dinov3/train/param_groups.py b/starVLA/dinov3/dinov3/train/param_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..d8712a82042db21ae1e21e24f4ed1968205a9d32 --- /dev/null +++ b/starVLA/dinov3/dinov3/train/param_groups.py @@ -0,0 +1,180 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +from collections import defaultdict + +logger = logging.getLogger("dinov3") + + +def get_vit_lr_decay_rate( + name, + lr_decay_rate=1.0, + num_layers=12, + force_is_backbone=False, + chunked_blocks=False, +): + """ + Calculate lr decay rate for different ViT blocks. + Args: + name (string): parameter name. + lr_decay_rate (float): base lr decay rate. + num_layers (int): number of ViT blocks. + Returns: + lr decay rate for the given parameter. + """ + layer_id = num_layers + 1 + if name.startswith("backbone") or force_is_backbone: + if ( + ".pos_embed" in name + or ".patch_embed" in name + or ".mask_token" in name + or ".cls_token" in name + or ".storage_tokens" in name + ): + layer_id = 0 + elif force_is_backbone and ( + "pos_embed" in name + or "patch_embed" in name + or "mask_token" in name + or "cls_token" in name + or "storage_tokens" in name + ): + layer_id = 0 + elif ".blocks." in name and ".residual." not in name: + layer_id = int(name[name.find(".blocks.") :].split(".")[2]) + 1 + elif chunked_blocks and "blocks." in name and "residual." not in name: + layer_id = int(name[name.find("blocks.") :].split(".")[2]) + 1 + elif "blocks." in name and "residual." not in name: + layer_id = int(name[name.find("blocks.") :].split(".")[1]) + 1 + + return lr_decay_rate ** (num_layers + 1 - layer_id) + + +def get_params_groups_with_decay(model, lr_decay_rate=1.0, patch_embed_lr_mult=1.0, dino_head_wd_multiplier=1.0): + chunked_blocks = False + if hasattr(model, "n_blocks"): + logger.info("chunked fsdp") + n_blocks = model.n_blocks + chunked_blocks = model.chunked_blocks + elif hasattr(model, "blocks"): + logger.info("first code branch") + n_blocks = len(model.blocks) + elif hasattr(model, "backbone"): + logger.info("second code branch") + n_blocks = len(model.backbone.blocks) + else: + logger.info("else code branch") + n_blocks = 0 + all_param_groups = [] + + for name, param in model.named_parameters(): + name = remove_fsdp_compile_names(name) + if not param.requires_grad: + continue + decay_rate = get_vit_lr_decay_rate( + name, + lr_decay_rate, + num_layers=n_blocks, + force_is_backbone=n_blocks > 0, + chunked_blocks=chunked_blocks, + ) + d = { + "name": name, + "params": param, + "is_last_layer": False, + "lr_multiplier": decay_rate, + "wd_multiplier": 1.0, + } + + if "dino_head" in name: + d["wd_multiplier"] = dino_head_wd_multiplier + + if "last_layer" in name: + d["is_last_layer"] = True + + # No weight-decay on biases, norm parameters, layer scale gamma, learned tokens and embeddings + if name.endswith("bias") or "norm" in name or "gamma" in name or "fourier_w" in name: + d["wd_multiplier"] = 0.0 + + if "patch_embed" in name: + d["lr_multiplier"] *= patch_embed_lr_mult + + all_param_groups.append(d) + logger.info(f"{name}: lr_multiplier: {d['lr_multiplier']}, wd_multiplier: {d['wd_multiplier']}") + + return all_param_groups + + +def fuse_params_groups(all_params_groups, keys=("lr_multiplier", "wd_multiplier", "is_last_layer")): + fused_params_groups = defaultdict(lambda: {"params": []}) + for d in all_params_groups: + identifier = "" + for k in keys: + identifier += k + str(d[k]) + "_" + + for k in keys: + fused_params_groups[identifier][k] = d[k] + fused_params_groups[identifier]["params"].append(d["params"]) + + return fused_params_groups.values() + + +def get_params_groups_with_decay_fsdp(model, lr_decay_rate=1.0, patch_embed_lr_mult=1.0, dino_head_wd_multiplier=1.0): + if hasattr(model, "module"): # SimpleFSDP + is_backbone = hasattr(model.module, "blocks") + n_blocks = len(model.module.blocks) if is_backbone else 0 + else: # FSDP2 + is_backbone = hasattr(model, "blocks") + n_blocks = len(model.blocks) if is_backbone else 0 + + all_param_groups = [] + + for name, param in model.named_parameters(): + name = remove_fsdp_compile_names(name) + if not param.requires_grad: + continue + decay_rate = get_vit_lr_decay_rate( + name, + lr_decay_rate, + num_layers=n_blocks, + force_is_backbone=n_blocks > 0, + chunked_blocks=False, + ) + d = { + "name": name, + "params": param, + "is_last_layer": False, + "lr_multiplier": decay_rate, + "wd_multiplier": 1.0, + } + + if "dino_head" in name: + d["wd_multiplier"] = dino_head_wd_multiplier + + if "last_layer" in name: + d["is_last_layer"] = True + + # No weight-decay on biases, norm parameters, layer scale gamma, learned tokens and embeddings + if name.endswith("bias") or "norm" in name or "gamma" in name or "fourier_w" in name: + d["wd_multiplier"] = 0.0 + + if "patch_embed" in name: + d["lr_multiplier"] *= patch_embed_lr_mult + + all_param_groups.append(d) + logger.info(f"{name}: lr_multiplier: {d['lr_multiplier']}, wd_multiplier: {d['wd_multiplier']}") + + return all_param_groups + + +def remove_fsdp_compile_names(name: str): + name = name.replace("_fsdp_wrapped_module.", "") # Added by FSDP + name = name.replace("_checkpoint_wrapped_module.", "") # Added by activation checkpointing for xFSDP + name = name.replace("parametrizations.", "") # Added by xFSDP + name = name.removesuffix(".original") # Added by xFSDP + name = name.replace("module.", "") # Added by xFSDP + name = name.replace("_orig_mod.", "") # Added by torch.compile + return name diff --git a/starVLA/dinov3/dinov3/train/ssl_meta_arch.py b/starVLA/dinov3/dinov3/train/ssl_meta_arch.py new file mode 100644 index 0000000000000000000000000000000000000000..f42bed1c284cc392ed88da4ee5aa1c9d47f140c9 --- /dev/null +++ b/starVLA/dinov3/dinov3/train/ssl_meta_arch.py @@ -0,0 +1,820 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import gc +import logging +from functools import partial + +import torch +from omegaconf import OmegaConf +from torch import Tensor, nn + +import dinov3.distributed as distributed +from dinov3.checkpointer import init_fsdp_model_from_checkpoint +from dinov3.configs import get_default_config +from dinov3.data import DataAugmentationDINO +from dinov3.fsdp.ac_compile_parallelize import ac_compile_parallelize +from dinov3.layers.dino_head import DINOHead +from dinov3.loss import DINOLoss, GramLoss, KoLeoLoss, KoLeoLossDistributed, iBOTPatchLoss +from dinov3.models import build_model_from_cfg +from dinov3.train.cosine_lr_scheduler import linear_warmup_cosine_decay +from dinov3.train.param_groups import fuse_params_groups, get_params_groups_with_decay_fsdp +from dinov3.utils import count_parameters + +logger = logging.getLogger("dinov3") + + +class SSLMetaArch(nn.Module): + """ + Modified version of SSLMetaArchCompilable including gram loss: + - Gram loss is used only if gram.use_loss is set to true + """ + + def __init__(self, cfg): + super().__init__() + + # assert cfg.multidistillation.enabled is False + assert cfg.crops.local_crops_number > 0 + assert cfg.ibot.separate_head is True + assert cfg.train.centering == "sinkhorn_knopp" + + # For some reason FULL_SHARD doesn't work + assert cfg.compute_precision.sharding_strategy == "SHARD_GRAD_OP" + + self.cfg = cfg + + student_model_dict = dict() + teacher_model_dict = dict() + gram_model_dict = dict() + + student_backbone, teacher_backbone, embed_dim = build_model_from_cfg(cfg) + torch.cuda.empty_cache() + gc.collect() + gram_backbone, _ = build_model_from_cfg(cfg, only_teacher=True) + logger.info(f"Number of parameters: {count_parameters(student_backbone)}") + student_model_dict["backbone"] = student_backbone + teacher_model_dict["backbone"] = teacher_backbone + gram_model_dict["backbone"] = gram_backbone + logger.info(f"OPTIONS -- architecture : embed_dim: {embed_dim}") + + self.embed_dim = embed_dim # D + self.dino_out_dim = cfg.dino.head_n_prototypes # K + + logger.info("OPTIONS -- DINO") + logger.info(f"OPTIONS -- DINO -- loss_weight: {cfg.dino.loss_weight}") + logger.info(f"OPTIONS -- DINO -- global_ignore_diagonal: {cfg.dino.global_ignore_diagonal}") + logger.info(f"OPTIONS -- DINO -- head_n_prototypes: {cfg.dino.head_n_prototypes}") + logger.info(f"OPTIONS -- DINO -- head_bottleneck_dim: {cfg.dino.head_bottleneck_dim}") + logger.info(f"OPTIONS -- DINO -- head_hidden_dim: {cfg.dino.head_hidden_dim}") + logger.info(f"OPTIONS -- DINO -- head_norm_last_layer: {cfg.dino.head_norm_last_layer}") + dino_head_class = partial( + DINOHead, + in_dim=embed_dim, + out_dim=cfg.dino.head_n_prototypes, + hidden_dim=cfg.dino.head_hidden_dim, + bottleneck_dim=cfg.dino.head_bottleneck_dim, + nlayers=cfg.dino.head_nlayers, + ) + student_model_dict["dino_head"] = dino_head_class() + teacher_model_dict["dino_head"] = dino_head_class() + self.dino_loss = DINOLoss(self.dino_out_dim) + + logger.info("OPTIONS -- KOLEO") + logger.info(f"OPTIONS -- KOLEO -- loss_weight: {cfg.dino.koleo_loss_weight}") + logger.info(f"OPTIONS -- KOLEO -- distributed: {cfg.dino.koleo_loss_distributed}") + if cfg.dino.koleo_loss_distributed: + logger.info(f"OPTIONS -- KOLEO -- topk: {cfg.dino.koleo_topk}") + logger.info( + f"OPTIONS -- KOLEO -- distributed_loss_group_size: {cfg.dino.koleo_distributed_loss_group_size}" + ) + assert cfg.dino.koleo_distributed_replicas == 0, ( + "Option `dino.koleo_distributed_replicas` is no longer supported" + ) + self.koleo_loss = KoLeoLossDistributed( + topk=cfg.dino.koleo_topk, + loss_group_size=cfg.dino.koleo_distributed_loss_group_size, + ) + else: + assert cfg.dino.koleo_topk == 1, "Non-distributed KoLeo loss only supports `dino.koleo_topk=1`" + self.koleo_loss = KoLeoLoss() + + logger.info("OPTIONS -- IBOT") + logger.info(f"OPTIONS -- IBOT -- loss_weight: {cfg.ibot.loss_weight}") + logger.info(f"OPTIONS -- IBOT masking -- ibot_mask_ratio_tuple: {cfg.ibot.mask_ratio_min_max}") + logger.info(f"OPTIONS -- IBOT masking -- ibot_mask_sample_probability: {cfg.ibot.mask_sample_probability}") + + assert 0 <= cfg.ibot.mask_ratio_min_max[0] < cfg.ibot.mask_ratio_min_max[1] <= 1, ( + "provide a valid cfg.ibot.mask_ratio_min_max" + ) + assert 0 <= cfg.ibot.mask_sample_probability <= 1, "provide a positive mask probability for ibot" + logger.info(f"OPTIONS -- IBOT -- head_n_prototypes: {cfg.ibot.head_n_prototypes}") + logger.info(f"OPTIONS -- IBOT -- head_bottleneck_dim: {cfg.ibot.head_bottleneck_dim}") + logger.info(f"OPTIONS -- IBOT -- head_hidden_dim: {cfg.ibot.head_hidden_dim}") + logger.info(f"OPTIONS -- IBOT -- head_norm_last_layer: {cfg.ibot.head_norm_last_layer}") + ibot_head_class = partial( + DINOHead, + in_dim=embed_dim, + out_dim=cfg.ibot.head_n_prototypes, + hidden_dim=cfg.ibot.head_hidden_dim, + bottleneck_dim=cfg.ibot.head_bottleneck_dim, + nlayers=cfg.ibot.head_nlayers, + ) + student_model_dict["ibot_head"] = ibot_head_class() + teacher_model_dict["ibot_head"] = ibot_head_class() + self.ibot_patch_loss = iBOTPatchLoss(cfg.ibot.head_n_prototypes) + + # Build student and teacher models + self.student = nn.ModuleDict(student_model_dict) + self.teacher = nn.ModuleDict(teacher_model_dict) + self.model_ema = self.teacher # this may be overwritten for distillation + logger.info(f"Student and Teacher are built: they are both {cfg.student.arch} network.") + + if cfg.distillation.enabled: + self._setup_distillation() + # No grad is needed for these two + self.teacher.requires_grad_(False) + self.model_ema.requires_grad_(False) + self.ema_params_lists = None + + # getting config params fixed: + self.n_local_crops = self.cfg.crops.local_crops_number + self.is_distillation_enabled = self.cfg.distillation.enabled + self.dino_global_ignore_diagonal = self.cfg.dino.global_ignore_diagonal + self.dino_loss_weight = self.cfg.dino.loss_weight + self.dino_koleo_loss_weight = self.cfg.dino.koleo_loss_weight + self.ibot_loss_weight = self.cfg.ibot.loss_weight + + # Local loss reweighting + if self.cfg.dino.reweight_dino_local_loss: + iter_per_epoch = cfg.train.OFFICIAL_EPOCH_LENGTH + total_iterations = iter_per_epoch * cfg.optim.epochs + schedule_cfg = cfg.dino.local_loss_weight_schedule + self.dino_local_loss_schedule = linear_warmup_cosine_decay( + start=schedule_cfg.start, + peak=schedule_cfg.peak, + end=schedule_cfg.end, + warmup_iterations=iter_per_epoch * schedule_cfg.warmup_epochs, + total_iterations=total_iterations, + cosine_iterations=( + iter_per_epoch * schedule_cfg.cosine_epochs if "cosine_epochs" in schedule_cfg else None + ), + ) + + # Gram + self.gram_use_loss = self.cfg.gram.use_loss + self.gram_ema_teacher = False + self.has_gram_teacher = False + self.gram_teacher_initialized = False + if self.gram_use_loss: + # Gram regularization + self.gram_loss = GramLoss( + apply_norm=self.cfg.gram.normalized, + remove_only_teacher_neg=self.cfg.gram.remove_only_teacher_neg, + remove_neg=self.cfg.gram.remove_neg, + ) + # Construct gram teacher + self.has_gram_teacher = True if not cfg.gram.ema_teacher else False + if self.has_gram_teacher: + self.gram_teacher = nn.ModuleDict(gram_model_dict) + self.gram_teacher.requires_grad_(False) + logger.info(f"Gram teacher parameter at init: {next(self.gram_teacher.named_parameters())}") + else: + self.gram_teacher = None + + self.gram_loss_weight = self.cfg.gram.loss_weight + if self.cfg.gram.get("loss_weight_schedule"): + iter_per_epoch = cfg.train.OFFICIAL_EPOCH_LENGTH + total_iterations = iter_per_epoch * cfg.optim.epochs + schedule_cfg = self.cfg.gram.loss_weight_schedule + self.gram_loss_schedule = linear_warmup_cosine_decay( + start=schedule_cfg.start, + peak=schedule_cfg.peak, + end=schedule_cfg.end, + warmup_iterations=iter_per_epoch * schedule_cfg.warmup_epochs, + total_iterations=total_iterations, + cosine_iterations=( + iter_per_epoch * schedule_cfg.cosine_epochs if "cosine_epochs" in schedule_cfg else None + ), + ) + logger.info(f"Applying gram loss weight schedule instead of `cfg.gram.loss_weight`: {schedule_cfg}") + else: + self.gram_loss_schedule = None + self.gram_ema_teacher = self.cfg.gram.ema_teacher # If true use the EMA_teacher as gram_teacher + self.gram_ckpt = self.cfg.gram.ckpt # Checkpoint to the first gram teacher model + self.gram_img_level = self.cfg.gram.img_level # Apply the loss on the image, if false on the batch + self.gram_tokens_used = self.cfg.gram.tokens_used # Any value in ["all", "masked", "unmasked"] + # Update the teacher frequently + self.gram_rep_update = self.cfg.gram.rep_update # bool, if yes the gram teacher will be updated at the freq + self.gram_update_frequency = self.cfg.gram.update_frequency # defined by this var update_frequency + self.gram_it_first_update = self.cfg.gram.it_first_update # after iteration it_first_update is passed. + self.gram_it_load_ema_teacher = ( + self.cfg.gram.it_load_ema_teacher + ) # after iteration it_load_ema the ema teacher is loaded into the gram teacher + self.gram_compute_stats = self.cfg.gram.compute_stats # whether to compute auxiliary stats + self.gram_params_lists = None + + if self.gram_ema_teacher and self.gram_ckpt is not None: + raise ValueError( + "Cannot use both `gram.ema_teacher` and `gram.ckpt` at the same time. Please set one of them to False." + ) + if self.gram_ckpt is None and self.gram_it_load_ema_teacher < 0: + raise ValueError( + "If no gram checkpoint is provided, `gram.it_load_ema_teacher` must be set to a non-negative value." + ) + + assert not (self.gram_ema_teacher and self.gram_rep_update) + assert self.gram_tokens_used in ["all", "masked", "unmasked"] + # Currently using masked/unmasked not handle at the image-level + if self.gram_tokens_used in ["masked", "unmasked"]: + assert self.gram_img_level is False + + logger.info("OPTIONS -- GRAM") + logger.info(f"OPTIONS -- GRAM -- loss_weight: {cfg.gram.loss_weight}") + logger.info(f"OPTIONS -- GRAM -- ema teacher: {cfg.gram.ema_teacher}") + logger.info(f"OPTIONS -- GRAM -- ckpt: {cfg.gram.ckpt}") + if self.cfg.gram.rep_update: + logger.info(f"OPTIONS -- GRAM -- repeated update: {cfg.gram.rep_update}") + logger.info(f"OPTIONS -- GRAM -- update freq: {cfg.gram.update_frequency}") + logger.info(f"OPTIONS -- GRAM -- iteration first update: {cfg.gram.it_first_update}") + + logger.info(f"OPTIONS -- GRAM -- tokens_used: {cfg.gram.tokens_used}") + logger.info(f"OPTIONS -- GRAM -- apply normalization: {cfg.gram.normalized}") + logger.info(f"OPTIONS -- GRAM -- img_level: {cfg.gram.img_level}") + logger.info(f"OPTIONS -- GRAM -- remove_neg: {cfg.gram.remove_neg}") + logger.info(f"OPTIONS -- GRAM -- remove_only_teacher_neg: {cfg.gram.remove_only_teacher_neg}") + + if cfg.crops.gram_teacher_crops_size is None and self.has_gram_teacher: + raise ValueError("cfg.crops.gram_teacher_crops_size must be set to use gram loss") + if cfg.crops.gram_teacher_crops_size is not None and self.gram_ema_teacher: + raise ValueError("cfg.crops.gram_teacher_crops_size shoud be None when gram.ema_teacher=True") + + self.student_crop_size = cfg.crops.global_crops_size + self.gram_global_teacher_resize_method = cfg.gram.global_teacher_resize_method + self.gram_global_teacher_resize_antialias = cfg.gram.global_teacher_resize_antialias + logger.info(f"OPTIONS -- global crops student/teacher size: {self.student_crop_size}") + logger.info(f"OPTIONS -- global crops GRAM teacher size: {cfg.crops.gram_teacher_crops_size}") + logger.info(f"OPTIONS -- global crops GRAM teacher resize method: {cfg.gram.global_teacher_resize_method}") + logger.info( + f"OPTIONS -- global crops GRAM teacher resize antialias: {cfg.gram.global_teacher_resize_antialias}" + ) + + def _setup_distillation(self): + logger.info(f"Performing distillation from {self.cfg.distillation.full_cfg_path}") + + default_cfg = get_default_config() + distillation_cfg = OmegaConf.load(self.cfg.distillation.full_cfg_path) + distillation_cfg = OmegaConf.merge(default_cfg, distillation_cfg) + + assert distillation_cfg.ibot.separate_head is True + assert distillation_cfg.ibot.head_n_prototypes == self.cfg.ibot.head_n_prototypes, ( + f"{distillation_cfg.ibot.head_n_prototypes} != {self.cfg.ibot.head_n_prototypes}" + ) + assert distillation_cfg.dino.head_n_prototypes == self.cfg.dino.head_n_prototypes, ( + f"{distillation_cfg.dino.head_n_prototypes} != {self.cfg.dino.head_n_prototypes}" + ) + assert distillation_cfg.student.patch_size == self.cfg.student.patch_size + + teacher_model_dict = dict() + + backbone, embed_dim = build_model_from_cfg(distillation_cfg, only_teacher=True) + teacher_model_dict["backbone"] = backbone + + teacher_model_dict["dino_head"] = DINOHead( + in_dim=embed_dim, + out_dim=distillation_cfg.dino.head_n_prototypes, + hidden_dim=distillation_cfg.dino.head_hidden_dim, + bottleneck_dim=distillation_cfg.dino.head_bottleneck_dim, + nlayers=distillation_cfg.dino.head_nlayers, + ) + teacher_model_dict["ibot_head"] = DINOHead( + in_dim=embed_dim, + out_dim=distillation_cfg.ibot.head_n_prototypes, + hidden_dim=distillation_cfg.ibot.head_hidden_dim, + bottleneck_dim=distillation_cfg.ibot.head_bottleneck_dim, + nlayers=distillation_cfg.ibot.head_nlayers, + ) + self.teacher = nn.ModuleDict(teacher_model_dict) + + def init_weights(self) -> None: + # All weights are set to `nan` to ensure we initialize everything explicitly + self.student.backbone.init_weights() + self.student.dino_head.init_weights() + self.student.ibot_head.init_weights() + self.dino_loss.init_weights() + self.ibot_patch_loss.init_weights() + self.model_ema.load_state_dict(self.student.state_dict()) + if self.has_gram_teacher: + if self.gram_ckpt is not None: + logger.info(f"Loading pretrained weights from {self.gram_ckpt}") + init_fsdp_model_from_checkpoint( + self.gram_teacher, + self.gram_ckpt, + skip_load_keys=[ + "dino_head", + "ibot_head", + "dino_loss.center", + "ibot_patch_loss.center", + ], + keys_not_sharded=["backbone.rope_embed.periods", "qkv.bias_mask"], + process_group=distributed.get_default_process_group(), + ) + self.gram_teacher_initialized = True + else: + raise ValueError(f"Provide a correct path to {self.gram_ckpt}") + self.gram_teacher.requires_grad_(False) + self.gram_teacher.eval() + if self.cfg.student.resume_from_teacher_chkpt: + logger.info(f"Loading pretrained weights from {self.cfg.student.resume_from_teacher_chkpt}") + init_fsdp_model_from_checkpoint( + self.student, + self.cfg.student.resume_from_teacher_chkpt, + skip_load_keys=["dino_loss.center", "ibot_patch_loss.center"], + keys_not_sharded=["backbone.rope_embed.periods", "qkv.bias_mask"], + process_group=distributed.get_process_subgroup(), + ) + self.model_ema.load_state_dict(self.student.state_dict()) + if self.cfg.distillation.enabled: + if self.cfg.distillation.checkpoint_path != "ignore": + logger.info(f"Loading teacher to distil from : {self.cfg.distillation.checkpoint_path}") + init_fsdp_model_from_checkpoint( + self.teacher, + self.cfg.distillation.checkpoint_path, + skip_load_keys=["dino_loss.center", "ibot_patch_loss.center"], + keys_not_sharded=["backbone.rope_embed.periods", "qkv.bias_mask"], + process_group=distributed.get_default_process_group(), + ) + else: + logger.info("Init teacher to distil from, used for testing purpose only") + self.teacher.backbone.init_weights() + self.teacher.dino_head.init_weights() + self.teacher.ibot_head.init_weights() + logger.info(f"Performing distillation from: {self.teacher}") + + def forward_backward( + self, data, *, teacher_temp, iteration=0, **ignored_kwargs + ) -> tuple[Tensor, dict[str, float | Tensor]]: + del ignored_kwargs + metrics_dict = {} + + # Shapes + n_global_crops = 2 + n_local_crops = self.n_local_crops # self.cfg.crops.local_crops_number + B = data["collated_local_crops"].shape[0] // n_local_crops + assert data["collated_global_crops"].shape[0] == n_global_crops * B + metrics_dict["local_batch_size"] = B + metrics_dict["global_batch_size"] = data["global_batch_size"] + + global_crops = data["collated_global_crops"].cuda(non_blocking=True) + local_crops = data["collated_local_crops"].cuda(non_blocking=True) + masks = data["collated_masks"].cuda(non_blocking=True) + mask_indices_list = data["mask_indices_list"].cuda(non_blocking=True) + masks_weight = data["masks_weight"].cuda(non_blocking=True) + n_masked_patches_tensor = data["n_masked_patches"].cuda(non_blocking=True) + + if self.has_gram_teacher: + assert "collated_gram_teacher_crops" in data, ( + "no gram teacher crops in the data, have you set cfg.crops.gram_teacher_crops_size?" + ) + gram_teacher_crops = data["collated_gram_teacher_crops"].cuda(non_blocking=True) + else: + gram_teacher_crops = None + + # Teacher output (will trigger an all-gather to unshard) + teacher_global = self.get_teacher_output( + global_crops.unflatten(0, (n_global_crops, B)), + teacher_temp=teacher_temp, + n_masked_patches_tensor=n_masked_patches_tensor, + mask_indices_list=mask_indices_list, + upperbound=data["upperbound"], + ) + + # Student output (will trigger an all-gather to unshard) + student_global, student_local = self.get_student_output( + global_crops=global_crops.unflatten(0, (n_global_crops, B)), + local_crops=local_crops.unflatten(0, (n_local_crops, B)), + upperbound=data["upperbound"], + masks=masks, + mask_indices_list=mask_indices_list, + ) + + # Gram output + if self.gram_use_loss: + gram_global = self.get_gram_teacher_output( + gram_teacher_crops.unflatten(0, (n_global_crops, B)) if gram_teacher_crops is not None else None, + masks=masks, + teacher_global=teacher_global, + student_global=student_global, + student_global_crops_size=global_crops.shape[-1], + ) + else: + gram_global = {} + + # Compute losses and backprop + loss_accumulator, loss_dict = self.compute_losses( + teacher_global=teacher_global, + student_global=student_global, + student_local=student_local, + gram_global=gram_global, + masks=masks, + mask_indices_list=mask_indices_list, + masks_weight=masks_weight, + iteration=iteration, + ) + + self.backprop_loss(loss_accumulator) + + # Return total weighted loss and a dict of metrics to log + return loss_accumulator, metrics_dict | loss_dict + + @torch.no_grad() + def get_teacher_output( + self, + images, + *, + upperbound, + mask_indices_list, + teacher_temp, + n_masked_patches_tensor, + ): + n_crops, B, rgb, H, W = images.shape + images = images.flatten(0, 1) + + backbone_out = self.teacher.backbone(images, is_training=True) + cls = backbone_out["x_norm_clstoken"] # [n_crops * B, D] + reg = backbone_out["x_storage_tokens"] # [n_crops * B, R, D] + ibot_patch = backbone_out["x_norm_patchtokens"] # [n_crops * B, P, D] + + # IBOT head only on patches that are masked for the student + buffer = torch.index_select(ibot_patch.flatten(0, 1), dim=0, index=mask_indices_list) + masked_patch_after_head = self.teacher.ibot_head(buffer) + + # DINO head on CLS tokens + cls_after_head = self.teacher.dino_head(cls) # [n_crops * B, K] + + # Center with sinkhorn-knopp + cls_centered = self.dino_loss.sinkhorn_knopp_teacher( + cls_after_head, teacher_temp=teacher_temp + ) # [n_crops * B, K] + cls_centered = cls_centered.unflatten(0, (n_crops, B)) # [n_crops, B, K] + masked_patch_centered = self.ibot_patch_loss.sinkhorn_knopp_teacher( + masked_patch_after_head, + teacher_temp=teacher_temp, + n_masked_patches_tensor=n_masked_patches_tensor, + ) # [n_masked_patches, K] + + return { + "cls_pre_head": cls.unflatten(0, [n_crops, B]), # [n_crops, B, D] + "reg_pre_head": reg.unflatten(0, [n_crops, B]), # [n_crops, B, R, D] + "patch_pre_head": ibot_patch.unflatten(0, [n_crops, B]), # [n_crops, B, P, D] + "cls_after_head": cls_after_head.unflatten(0, [n_crops, B]), # [n_crops, B, K] + "cls_centered": cls_centered, # [n_crops, B, K] + "masked_patch_centered": masked_patch_centered, # [n_masked_patches, K] + } + + def get_gram_teacher_output(self, images, *, masks, teacher_global, student_global, student_global_crops_size): + # Get student patch features + student_patches = student_global["patch_pre_head"].flatten(0, 1) # [n_crops * B, P, D] + + # Get gram targets + if self.gram_ema_teacher: + teacher_patches = teacher_global["patch_pre_head"].flatten(0, 1) # [n_crops * B, P, D] + else: + if not self.gram_teacher_initialized: + raise ValueError("Gram teacher has not been initialized. Load a checkpoint or from the EMA teacher.") + n_crops, B, rgb, H, W = images.shape + images = images.flatten(0, 1) # [n_crops * B, rgb, H, W] + + with torch.no_grad(): + backbone_out = self.gram_teacher.backbone(images, is_training=True) + teacher_patches = backbone_out["x_norm_patchtokens"] # [n_crops * B, P_T, D] + + # Downsample Gram teacher features if needed + if teacher_patches.shape[1] != student_patches.shape[1]: + N = H // self.cfg.student.patch_size + assert teacher_patches.shape[1] == N**2 + N_student = student_global_crops_size // self.cfg.student.patch_size + assert student_patches.shape[1] == N_student**2 + patches_hw = teacher_patches.transpose(-2, -1).unflatten(-1, (N, N)) # [n_crops * B, D, N, N] + patches_hw = torch.nn.functional.interpolate( + patches_hw, + size=(N_student, N_student), + mode=self.gram_global_teacher_resize_method, + align_corners=False, + antialias=self.gram_global_teacher_resize_antialias, + ) + teacher_patches = patches_hw.flatten(-2, -1).transpose( + -2, -1 + ) # [n_crops * B, N_student * N_student, D] + assert teacher_patches.shape == student_patches.shape + + # Select the patches to be considered in the loss + orig_student_patches = student_patches + orig_teacher_patches = teacher_patches + if self.gram_tokens_used == "masked": + student_patches = student_patches[masks] + teacher_patches = teacher_patches[masks] + elif self.gram_tokens_used == "unmasked": + student_patches = student_patches[~masks] + teacher_patches = teacher_patches[~masks] + + return { + "student_patches": student_patches, # [n_crops * B, P, D] or [n_selected_patches, D] + "teacher_patches": teacher_patches, # [n_crops * B, P, D] or [n_selected_patches, D] + # Unmasked patches, for computing statistics + "orig_student_patches": orig_student_patches, # [n_crops * B, P, D] + "orig_teacher_patches": orig_teacher_patches, # [n_crops * B, P, D] + } + + def get_student_output(self, *, global_crops, local_crops, upperbound, masks, mask_indices_list): + n_global_crops, B, rgb, H, W = global_crops.shape + n_local_crops, B, rgb, H, W = local_crops.shape + + global_crops = global_crops.flatten(0, 1) + + # Forward global and local crops through the student backbone jointly + global_out, local_out = self.student.backbone( + [global_crops, local_crops.flatten(0, 1)], + masks=[masks if not self.is_distillation_enabled else None, None], + is_training=True, + ) + g_cls, g_reg, g_patch = ( + global_out["x_norm_clstoken"], + global_out["x_storage_tokens"], + global_out["x_norm_patchtokens"], + ) + l_cls, l_reg, l_patch = ( + local_out["x_norm_clstoken"], + local_out["x_storage_tokens"], + local_out["x_norm_patchtokens"], + ) + + # IBOT head only on masked patches + masked_patches_pre_head = torch.index_select(g_patch.flatten(0, 1), dim=0, index=mask_indices_list) + global_masked_patch_after_head = self.student.ibot_head(masked_patches_pre_head) + + # DINO head on CLS tokens (all in one pass) + buffer = [ + g_cls, # [n_global_crops * B, D] + l_cls, # [n_local_crops * B, D] + ] + sizes = [x.shape[0] for x in buffer] + buffer = torch.cat(buffer, dim=0) # [n_global_crops * B + n_local_crops * B, D] + buffer = self.student.dino_head(buffer) # [n_global_crops * B + n_local_crops * B, K] + buffer = torch.split_with_sizes(buffer, sizes, dim=0) + + global_out = { + "cls_pre_head": g_cls.unflatten(0, [n_global_crops, B]), # [n_global_crops, B, D] + "reg_pre_head": g_reg.unflatten(0, [n_global_crops, B]), # [n_global_crops, B, R, D] + "patch_pre_head": g_patch.unflatten(0, [n_global_crops, B]), # [n_global_crops, B, P, D] + "cls_after_head": buffer[0].unflatten(0, [n_global_crops, B]), # [n_global_crops, B, K], + "masked_patch_after_head": global_masked_patch_after_head, # [n_masked_patches, K] + "masked_patch_pre_head": masked_patches_pre_head, # [n_masked_patches, D] + } + local_out = { + "cls_pre_head": l_cls.unflatten(0, [n_local_crops, B]), # [n_local_crops, B, D] + "reg_pre_head": l_reg.unflatten(0, [n_local_crops, B]), # [n_local_crops, B, R, D] + "patch_pre_head": l_patch.unflatten(0, [n_local_crops, B]), # [n_local_crops, B, P, D] + "cls_after_head": buffer[1].unflatten(0, [n_local_crops, B]), # [n_local_crops, B, K], + } + + return global_out, local_out + + def compute_losses( + self, + *, + teacher_global, + student_global, + student_local, + gram_global, + masks, + mask_indices_list, + masks_weight, + iteration, + ): + n_global_crops = student_global["cls_after_head"].shape[0] + n_local_crops = student_local["cls_after_head"].shape[0] + loss_dict = {} + loss_accumulator = 0.0 + + # Loss scales like in DINOv2, these are multiplied with the loss weights from the config + dino_global_terms = ( + n_global_crops * (n_global_crops - 1) if self.dino_global_ignore_diagonal else n_global_crops**2 + ) + dino_local_terms = n_global_crops * n_local_crops + dino_global_scale = dino_global_terms / (dino_global_terms + dino_local_terms) + dino_local_scale = dino_local_terms / (dino_global_terms + dino_local_terms) + koleo_scale = n_global_crops + + # DINO local loss: compare post-head CLS tokens: student(local crops) vs. teacher(global crops) + dino_local_crops_loss = self.dino_loss( + student_logits=student_local["cls_after_head"], + teacher_probs=teacher_global["cls_centered"], + ) + loss_dict["dino_local_crops_loss"] = dino_local_crops_loss + + # Reweighting of DINO loss + if self.cfg.dino.reweight_dino_local_loss: + local_weight = self.dino_local_loss_schedule[iteration] + else: + local_weight = 1.0 + + loss_dict["dino_local_loss_weight"] = local_weight + loss_accumulator += self.dino_loss_weight * dino_local_scale * local_weight * dino_local_crops_loss + + # DINO global loss: compare post-head CLS tokens: student(global crops) vs. teacher(global crops) + dino_global_crops_loss = self.dino_loss( + student_logits=student_global["cls_after_head"], + teacher_probs=teacher_global["cls_centered"], + ignore_diagonal=self.dino_global_ignore_diagonal, + ) + loss_dict["dino_global_crops_loss"] = dino_global_crops_loss + loss_accumulator += self.dino_loss_weight * dino_global_scale * dino_global_crops_loss + + # Koleo: regularize pre-head CLS tokens of student(global crops) + koleo_loss = sum(self.koleo_loss(x) for x in student_global["cls_pre_head"]) / n_global_crops + loss_dict["koleo_loss"] = koleo_loss + loss_accumulator += self.dino_koleo_loss_weight * koleo_scale * koleo_loss + + # IBOT loss + ibot_patch_loss = self.ibot_patch_loss.forward_masked( + student_global["masked_patch_after_head"], + teacher_global["masked_patch_centered"], + student_masks_flat=masks, + n_masked_patches=mask_indices_list.shape[0], + masks_weight=masks_weight, + ) + loss_dict["ibot_loss"] = ibot_patch_loss + loss_accumulator += self.ibot_loss_weight * ibot_patch_loss + + # Gram loss + if self.gram_use_loss: + gram_loss = self.gram_loss( + gram_global["student_patches"], + gram_global["teacher_patches"], + img_level=self.gram_img_level, + ) + + if self.gram_loss_schedule is not None: + gram_loss_weight = self.gram_loss_schedule[iteration] + else: + gram_loss_weight = self.gram_loss_weight + + loss_dict["gram_loss_weight"] = gram_loss_weight + loss_accumulator += gram_loss * gram_loss_weight + loss_dict["gram_loss"] = gram_loss + + if self.gram_compute_stats: + with torch.no_grad(): + # Save stats over masked / unmasked tokens + gram_loss_masked = self.gram_loss( + gram_global["orig_student_patches"][masks].detach(), + gram_global["orig_teacher_patches"][masks], + img_level=False, + ) + loss_dict["stats_only/masked_gram_loss"] = gram_loss_masked + gram_loss_unmasked = self.gram_loss( + gram_global["orig_student_patches"][~masks].detach(), + gram_global["orig_teacher_patches"][~masks], + img_level=False, + ) + loss_dict["stats_only/unmasked_gram_loss"] = gram_loss_unmasked + + return loss_accumulator, loss_dict + + @torch.no_grad() + def gram_load_ema_teacher(self): + if self.has_gram_teacher: + skip_load_prefixes = ["dino_head.", "ibot_head."] + self.gram_teacher.load_state_dict( + { + k: v + for k, v in self.model_ema.state_dict().items() + if not any(k.startswith(prefix) for prefix in skip_load_prefixes) + } + ) + self.gram_teacher.requires_grad_(False) + self.gram_teacher.eval() + self.gram_teacher_initialized = True + + def train(self): + super().train() + self.teacher.eval() + if self.has_gram_teacher: + self.gram_teacher.eval() + + def forward(self, inputs): + raise NotImplementedError + + def backprop_loss(self, loss): + loss.backward() + + def update_ema(self, m): + if self.ema_params_lists is None: + student_param_list = [] + teacher_param_list = [] + for k in self.student.keys(): + for ms, mt in zip(self.student[k].parameters(), self.model_ema[k].parameters()): + student_param_list += [ms] + teacher_param_list += [mt] + self.ema_params_lists = (student_param_list, teacher_param_list) + else: + student_param_list, teacher_param_list = self.ema_params_lists + with torch.no_grad(): + torch._foreach_mul_(teacher_param_list, m) + torch._foreach_add_(teacher_param_list, student_param_list, alpha=1 - m) + + def update_gram(self, m=0): + if not self.has_gram_teacher: + return + logger.info("Updating gram teacher with teacher weights.") + if self.gram_params_lists is None: + teacher_param_list = [] + gramteacher_param_list = [] + for k in self.gram_teacher.keys(): + for mgt, mt in zip(self.gram_teacher[k].parameters(), self.teacher[k].parameters()): + gramteacher_param_list += [mgt] + teacher_param_list += [mt] + self.gram_params_lists = (gramteacher_param_list, teacher_param_list) + else: + gramteacher_param_list, teacher_param_list = self.gram_params_lists + + with torch.no_grad(): + torch._foreach_mul_(gramteacher_param_list, m) + torch._foreach_add_(gramteacher_param_list, teacher_param_list, alpha=1 - m) + + def build_data_augmentation_dino(self, cfg): + return DataAugmentationDINO( + cfg.crops.global_crops_scale, + cfg.crops.local_crops_scale, + cfg.crops.local_crops_number, + global_crops_size=cfg.crops.global_crops_size, + local_crops_size=cfg.crops.local_crops_size, + gram_teacher_crops_size=cfg.crops.gram_teacher_crops_size, + gram_teacher_no_distortions=cfg.crops.gram_teacher_no_distortions, + local_crops_subset_of_global_crops=cfg.crops.localcrops_subset_of_globalcrops, + share_color_jitter=cfg.crops.share_color_jitter, + horizontal_flips=cfg.crops.horizontal_flips, + mean=cfg.crops.rgb_mean, + std=cfg.crops.rgb_std, + ) + + def get_maybe_fused_params_for_submodel(self, m: nn.Module): + params_groups = get_params_groups_with_decay_fsdp( + model=m, + lr_decay_rate=self.cfg.optim.layerwise_decay, + patch_embed_lr_mult=self.cfg.optim.patch_embed_lr_mult, + dino_head_wd_multiplier=self.cfg.optim.dino_head_wd_multiplier, + ) + if self.cfg.optim.multi_tensor_optim: + fused_params_groups = fuse_params_groups(params_groups) + logger.info("fusing param groups") + + for g in fused_params_groups: + g["foreach"] = True + g["fused"] = True + return fused_params_groups + else: + return params_groups + + def get_params_groups(self): + all_params_groups = [] + for name, m in self.student.items(): + logger.info(f"Getting paramer groups for {name}") + all_params_groups += self.get_maybe_fused_params_for_submodel(m) + return all_params_groups + + def prepare_for_distributed_training(self) -> None: + process_subgroup = distributed.get_process_subgroup() + default_process_group = distributed.get_default_process_group() + inference_only_models = [self.model_ema] + inference_only_models_process_groups = [process_subgroup] + if self.has_gram_teacher: + inference_only_models.append(self.gram_teacher) + inference_only_models_process_groups.append(default_process_group) + if self.cfg.distillation.enabled: + inference_only_models.append(self.teacher) + inference_only_models_process_groups.append(default_process_group) + ac_compile_parallelize( + trained_model=self.student, + inference_only_models=inference_only_models, + cfg=self.cfg, + trained_model_process_group=process_subgroup, + inference_only_models_process_groups=inference_only_models_process_groups, + ) + + def broadcast_to_subgroups(self, tensor, over_dim, global_batch_size=None): + """ + This is an operation that takes a tensor from the default process group, gathers it, stacks it, then scatters it within a smaller process subgroup + """ + world_size = distributed.get_world_size() + subgroup_size = distributed.get_subgroup_size() + gathered = [torch.zeros_like(tensor) for _ in range(world_size)] + + torch.distributed.all_gather(gathered, tensor) + catted = torch.cat(gathered, dim=over_dim) + if global_batch_size is not None: + catted = catted.narrow(dim=over_dim, start=0, length=global_batch_size) + + return catted.chunk(subgroup_size, dim=over_dim)[distributed.get_subgroup_rank()].clone() diff --git a/starVLA/dinov3/dinov3/train/train.py b/starVLA/dinov3/dinov3/train/train.py new file mode 100644 index 0000000000000000000000000000000000000000..95ab2e5af4f20c8407a6b0fc6648fbbd8f421f50 --- /dev/null +++ b/starVLA/dinov3/dinov3/train/train.py @@ -0,0 +1,637 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import argparse +import copy +import gc +import logging +import math +import os +import sys +from functools import partial +from pathlib import Path + +import torch +import torch.distributed +from torch.distributed._tensor import DTensor + +import dinov3.distributed as distributed +from dinov3.checkpointer import ( + find_latest_checkpoint, + keep_checkpoint_copy, + keep_last_n_checkpoints, + load_checkpoint, + register_dont_save_hooks, + save_checkpoint, +) +from dinov3.configs import setup_config, setup_job, setup_multidistillation +from dinov3.data import ( + MaskingGenerator, + SamplerType, + collate_data_and_cast, + make_data_loader, + make_dataset, + CombinedDataLoader, +) +from dinov3.logging import MetricLogger, setup_logging +from dinov3.train.cosine_lr_scheduler import CosineScheduler, linear_warmup_cosine_decay +from dinov3.train.multidist_meta_arch import MultiDistillationMetaArch +from dinov3.train.ssl_meta_arch import SSLMetaArch + +assert torch.__version__ >= (2, 1) +torch.backends.cuda.matmul.allow_tf32 = True # pytorch 1.12 sets this to false by default +torch.backends.cudnn.benchmark = False # True + +logger = logging.getLogger("dinov3") + + +def get_args_parser(add_help: bool = True): + parser = argparse.ArgumentParser("DINOv3 training", add_help=add_help) + parser.add_argument("--config-file", default="", metavar="FILE", help="path to config file") + parser.add_argument( + "--no-resume", + action="store_true", + help="Whether to not attempt to resume from the checkpoint directory. ", + ) + parser.add_argument("--eval-only", action="store_true", help="perform evaluation only") + parser.add_argument("--eval", type=str, default="", help="Eval type to perform") + parser.add_argument( + "--eval_pretrained_weights", + type=str, + default="", + help="Path to pretrained weights", + ) + parser.add_argument( + "opts", + help=""" +Modify config options at the end of the command. For Yacs configs, use +space-separated "PATH.KEY VALUE" pairs. +For python-based LazyConfig, use "path.key=value". + """.strip(), + default=None, + nargs=argparse.REMAINDER, + ) + parser.add_argument( + "--output-dir", + default="./local_dino", + type=str, + help="Path to save logs and checkpoints.", + ) + parser.add_argument("--seed", default=0, type=int, help="RNG seed") + parser.add_argument( + "--benchmark-codebase", + action="store_true", + help="test the codebase for a few iters", + ) + parser.add_argument("--test-ibot", action="store_true", help="test ibot") + parser.add_argument("--profiling", action="store_true", help="do profiling") + parser.add_argument("--dump-fsdp-weights", action="store_true", help="dump fsdp weights") + parser.add_argument("--record_ref_losses", action="store_true", help="record reference losses") + parser.add_argument("--ref_losses_path", default="", type=str) + parser.add_argument("--multi-distillation", action="store_true", help="run multi-distillation") + + return parser + + +def build_optimizer(cfg, params_groups): + return torch.optim.AdamW(params_groups, betas=(cfg.optim.adamw_beta1, cfg.optim.adamw_beta2)) + + +def build_schedulers(cfg): + if "schedules" in cfg: + logger.info("Using schedules v2") + return build_schedulers_v2(cfg) + + OFFICIAL_EPOCH_LENGTH = cfg.train.OFFICIAL_EPOCH_LENGTH + lr = dict( + base_value=cfg.optim["lr"], + final_value=cfg.optim["min_lr"], + total_iters=cfg.optim["epochs"] * OFFICIAL_EPOCH_LENGTH, + warmup_iters=cfg.optim["warmup_epochs"] * OFFICIAL_EPOCH_LENGTH, + start_warmup_value=0, + trunc_extra=cfg.optim["schedule_trunc_extra"], + ) + wd = dict( + base_value=cfg.optim["weight_decay"], + final_value=cfg.optim["weight_decay_end"], + total_iters=cfg.optim["epochs"] * OFFICIAL_EPOCH_LENGTH, + trunc_extra=cfg.optim["schedule_trunc_extra"], + ) + momentum = dict( + base_value=cfg.teacher["momentum_teacher"], + final_value=cfg.teacher["final_momentum_teacher"], + total_iters=cfg.optim["epochs"] * OFFICIAL_EPOCH_LENGTH, + trunc_extra=cfg.optim["schedule_trunc_extra"], + ) + teacher_temp = dict( + base_value=cfg.teacher["teacher_temp"], + final_value=cfg.teacher["teacher_temp"], + total_iters=cfg.teacher["warmup_teacher_temp_epochs"] * OFFICIAL_EPOCH_LENGTH, + warmup_iters=cfg.teacher["warmup_teacher_temp_epochs"] * OFFICIAL_EPOCH_LENGTH, + start_warmup_value=cfg.teacher["warmup_teacher_temp"], + ) + + lr_schedule = CosineScheduler(**lr) + wd_schedule = CosineScheduler(**wd) + momentum_schedule = CosineScheduler(**momentum) + teacher_temp_schedule = CosineScheduler(**teacher_temp) + last_layer_lr_schedule = CosineScheduler(**lr) + + last_layer_lr_schedule.schedule[: cfg.optim["freeze_last_layer_epochs"] * OFFICIAL_EPOCH_LENGTH] = ( + 0 # mimicking the original schedules + ) + logger.info("Schedulers ready.") + return ( + lr_schedule, + wd_schedule, + momentum_schedule, + teacher_temp_schedule, + last_layer_lr_schedule, + ) + + +def build_schedulers_v2(cfg): + iter_per_epoch = cfg.train.OFFICIAL_EPOCH_LENGTH + total_iterations = cfg.train.OFFICIAL_EPOCH_LENGTH * cfg.optim.epochs + logger.info(f"Total training iterations {total_iterations}") + + # LR scaling rules + lr_peak = cfg.schedules.lr.peak + lr_end = cfg.schedules.lr.end + if cfg.optim.scaling_rule == "linear_wrt_256": + lr_peak *= cfg.train.batch_size_per_gpu * distributed.get_world_size() / 256.0 + lr_end *= cfg.train.batch_size_per_gpu * distributed.get_world_size() / 256.0 + logger.info( + f"Scaling rule {cfg.optim.scaling_rule}, LR peak {cfg.schedules.lr.peak} -> {lr_peak}, LR end {cfg.schedules.lr.end} -> {lr_end}" + ) + elif cfg.optim.scaling_rule == "sqrt_wrt_1024": + lr_peak *= 4 * math.sqrt(cfg.train.batch_size_per_gpu * distributed.get_world_size() / 1024.0) + lr_end *= 4 * math.sqrt(cfg.train.batch_size_per_gpu * distributed.get_world_size() / 1024.0) + logger.info( + f"Scaling rule {cfg.optim.scaling_rule}, LR peak {cfg.schedules.lr.peak} -> {lr_peak}, LR end {cfg.schedules.lr.end} -> {lr_end}" + ) + else: + logger.info(f"No scaling rule for {cfg.optim.scaling_rule=}") + + lr = linear_warmup_cosine_decay( + start=cfg.schedules.lr.start, + peak=lr_peak, + end=lr_end, + warmup_iterations=iter_per_epoch * cfg.schedules.lr.warmup_epochs, + total_iterations=total_iterations, + cosine_iterations=( + iter_per_epoch * cfg.schedules.lr.cosine_epochs if "cosine_epochs" in cfg.schedules.lr else None + ), + ) + last_layer_lr = lr.copy() + last_layer_lr[: iter_per_epoch * cfg.schedules.lr.freeze_last_layer_epochs] = 0 + weight_decay = linear_warmup_cosine_decay( + start=cfg.schedules.weight_decay.start, + peak=cfg.schedules.weight_decay.peak, + end=cfg.schedules.weight_decay.end, + warmup_iterations=iter_per_epoch * cfg.schedules.weight_decay.warmup_epochs, + total_iterations=total_iterations, + cosine_iterations=( + iter_per_epoch * cfg.schedules.weight_decay.cosine_epochs + if "cosine_epochs" in cfg.schedules.weight_decay + else None + ), + ) + momentum = linear_warmup_cosine_decay( + start=cfg.schedules.momentum.start, + peak=cfg.schedules.momentum.peak, + end=cfg.schedules.momentum.end, + warmup_iterations=iter_per_epoch * cfg.schedules.momentum.warmup_epochs, + total_iterations=total_iterations, + cosine_iterations=( + iter_per_epoch * cfg.schedules.momentum.cosine_epochs if "cosine_epochs" in cfg.schedules.momentum else None + ), + ) + teacher_temp = linear_warmup_cosine_decay( + start=cfg.schedules.teacher_temp.start, + peak=cfg.schedules.teacher_temp.peak, + end=cfg.schedules.teacher_temp.end, + warmup_iterations=iter_per_epoch * cfg.schedules.teacher_temp.warmup_epochs, + total_iterations=total_iterations, + cosine_iterations=( + iter_per_epoch * cfg.schedules.teacher_temp.cosine_epochs + if "cosine_epochs" in cfg.schedules.teacher_temp + else None + ), + ) + return lr, weight_decay, momentum, teacher_temp, last_layer_lr + + +def apply_optim_scheduler(optimizer, lr, wd, last_layer_lr): + for param_group in optimizer.param_groups: + is_last_layer = param_group["is_last_layer"] + lr_multiplier = param_group["lr_multiplier"] + wd_multiplier = param_group["wd_multiplier"] + param_group["weight_decay"] = wd * wd_multiplier + if is_last_layer: + param_group["lr"] = last_layer_lr * lr_multiplier + else: + param_group["lr"] = lr * lr_multiplier + + +def do_test(cfg, model, iteration, process_group, do_low_freq=False): + # dump a sharded checkpoint + eval_dir = Path(cfg.train.output_dir) / "eval" / str(iteration) + if distributed.is_subgroup_main_process(): + eval_dir.mkdir(parents=True, exist_ok=True) + if cfg.train.sharded_eval_checkpoint: + ckpt_path = eval_dir / "sharded_teacher_checkpoint" + if distributed.is_subgroup_main_process(): + ckpt_path.mkdir(parents=True, exist_ok=True) + torch.distributed.barrier() + teacher_backbone = model.model_ema + save_checkpoint( + ckpt_dir=ckpt_path, iteration=iteration, model=teacher_backbone, overwrite=True, process_group=process_group + ) + if not distributed.is_subgroup_main_process(): + return + else: + new_state_dict = model.model_ema.state_dict() + for k, tensor in list(new_state_dict.items()): + if isinstance(tensor, DTensor): + new_state_dict[k] = tensor.full_tensor() + if not distributed.is_subgroup_main_process(): + return + # save teacher checkpoint + ckpt_path = eval_dir / "teacher_checkpoint.pth" + torch.save({"teacher": new_state_dict}, ckpt_path) + logger.info("Saved eval checkpoint: %s", ckpt_path) + + +def build_data_loader_from_cfg( + cfg, + model, + start_iter, +): + # Collate function + img_size = cfg.crops.global_crops_size + patch_size = int(cfg.student.patch_size * cfg.crops.teacher_to_student_resolution_scale) + n_tokens = (img_size // patch_size) ** 2 + mask_generator = MaskingGenerator( + input_size=(img_size // patch_size, img_size // patch_size), + max_num_patches=0.5 * img_size // patch_size * img_size // patch_size, + ) + + if cfg.multidistillation.enabled: + assert cfg.multidistillation.global_batch_size % distributed.get_subgroup_size() == 0 + local_batch_size = cfg.multidistillation.global_batch_size // distributed.get_subgroup_size() + dataloader_batch_size_per_gpu = ( + cfg.multidistillation.global_batch_size + (distributed.get_world_size() - 1) + ) // distributed.get_world_size() + else: + local_batch_size = None # will default to the standard local batch size matching the data batch size + dataloader_batch_size_per_gpu = cfg.train.batch_size_per_gpu + + collate_fn = partial( + collate_data_and_cast, + mask_ratio_tuple=cfg.ibot.mask_ratio_min_max, + mask_probability=cfg.ibot.mask_sample_probability, + dtype={ + "fp32": torch.float32, + "fp16": torch.float16, + "bf16": torch.bfloat16, + }[cfg.compute_precision.param_dtype], + n_tokens=n_tokens, + mask_generator=mask_generator, + random_circular_shift=cfg.ibot.mask_random_circular_shift, + local_batch_size=local_batch_size, + ) + batch_size = dataloader_batch_size_per_gpu + num_workers = cfg.train.num_workers + dataset_path = cfg.train.dataset_path + dataset = make_dataset( + dataset_str=dataset_path, + transform=model.build_data_augmentation_dino(cfg), + target_transform=lambda _: (), + ) + + if isinstance(dataset, torch.utils.data.IterableDataset): + sampler_type = SamplerType.INFINITE + else: + sampler_type = SamplerType.SHARDED_INFINITE if cfg.train.cache_dataset else SamplerType.INFINITE + + data_loader = make_data_loader( + dataset=dataset, + batch_size=batch_size, + num_workers=num_workers, + shuffle=True, + seed=cfg.train.seed + start_iter + 1, + sampler_type=sampler_type, + sampler_advance=start_iter * dataloader_batch_size_per_gpu, + drop_last=True, + collate_fn=collate_fn, + ) + return data_loader + + +def build_multi_resolution_data_loader_from_cfg( + cfg, + model, + start_iter, + seed=65537, +): + global_crops_sizes = ( + [cfg.crops.global_crops_size] if isinstance(cfg.crops.global_crops_size, int) else cfg.crops.global_crops_size + ) + local_crops_sizes = ( + [cfg.crops.local_crops_size] if isinstance(cfg.crops.local_crops_size, int) else cfg.crops.local_crops_size + ) + gram_teacher_crops_sizes = ( + [cfg.crops.gram_teacher_crops_size] + if cfg.crops.gram_teacher_crops_size is None or isinstance(cfg.crops.gram_teacher_crops_size, int) + else cfg.crops.gram_teacher_crops_size + ) + loader_ratios = ( + [cfg.crops.global_local_crop_pairs_ratios] + if type(cfg.crops.global_local_crop_pairs_ratios) in [int, float] + else cfg.crops.global_local_crop_pairs_ratios + ) + assert len(global_crops_sizes) == len(local_crops_sizes) == len(gram_teacher_crops_sizes) == len(loader_ratios) + + loaders = [] + for increment, (global_crops_size_i, local_crops_size_i, gram_teacher_crops_size_i) in enumerate( + zip(global_crops_sizes, local_crops_sizes, gram_teacher_crops_sizes) + ): + cfg_i = copy.deepcopy(cfg) + cfg_i.crops.global_crops_size = global_crops_size_i + cfg_i.crops.local_crops_size = local_crops_size_i + cfg_i.crops.gram_teacher_crops_size = gram_teacher_crops_size_i + cfg_i.train.seed = cfg.train.seed + increment + 1 + loaders.append(build_data_loader_from_cfg(cfg=cfg_i, model=model, start_iter=start_iter)) + + if len(loaders) == 1: + data_loader = loaders[0] + else: + data_loader = CombinedDataLoader( + loaders_with_ratios=zip(loaders, loader_ratios), + batch_size=cfg.train.batch_size_per_gpu, + combining_mode=0, + seed=seed, + name="MultiResDL", + ) + return data_loader + + +def do_train(cfg, model, resume=False): + process_subgroup = distributed.get_process_subgroup() + ckpt_dir = Path(cfg.train.output_dir, "ckpt").expanduser() + ckpt_dir.mkdir(parents=True, exist_ok=True) + + model.train() + # Optimizer + optimizer = build_optimizer(cfg, model.get_params_groups()) + ( + lr_schedule, + wd_schedule, + momentum_schedule, + teacher_temp_schedule, + last_layer_lr_schedule, + ) = build_schedulers(cfg) + if cfg.multidistillation.enabled: + register_dont_save_hooks( + model, + dont_save=[k for k, _ in model.state_dict().items() if k.startswith("teacher")], + ) + model.init_weights() + start_iter = 0 + if resume and (last_checkpoint_dir := find_latest_checkpoint(ckpt_dir)): + logger.info(f"Checkpoint found {last_checkpoint_dir}") + start_iter = ( + load_checkpoint( + last_checkpoint_dir, + model=model, + optimizer=optimizer, + strict_loading=False, + process_group=process_subgroup, + ) + + 1 + ) + OFFICIAL_EPOCH_LENGTH = cfg.train.OFFICIAL_EPOCH_LENGTH + max_iter = cfg.optim.epochs * OFFICIAL_EPOCH_LENGTH + if cfg.multidistillation.enabled: + global_batch_size = cfg.multidistillation.global_batch_size + else: + global_batch_size = cfg.train.batch_size_per_gpu * distributed.get_world_size() + + # Build data loader + data_loader = build_multi_resolution_data_loader_from_cfg( + cfg=cfg, + model=model, + start_iter=start_iter, + ) + + # Metric logging + logger.info("Starting training from iteration %d", start_iter) + metrics_file = os.path.join(cfg.train.output_dir, "training_metrics.json") + metric_logger = MetricLogger(delimiter=" ", output_file=metrics_file) + # Manual garbage collection + gc.disable() + gc.collect() + + # Training loop + student = model.student + iteration = start_iter + num_gram_updates = 0 + if ( + cfg.gram.use_loss + and model.has_gram_teacher + and cfg.gram.rep_update + and start_iter > 0 + and start_iter >= cfg.gram.it_first_update + ): + # If `start_iter == it_first_update`, we have performed one gram teacher update after + # iteration `start_iter - 1`, except if we are starting training from scratch and `start_iter == 0`. + num_gram_updates = math.ceil((start_iter + 1 - cfg.gram.it_first_update) / cfg.gram.update_frequency) + logger.info(f"Gram was updated {num_gram_updates} times before iteration {start_iter}") + consecutive_nan_count = 0 + for data in metric_logger.log_every( + data_loader, + print_freq=10, + header="Training", + n_iterations=max_iter, + start_iteration=start_iter, + ): + it = iteration + data["global_batch_size"] = global_batch_size + if iteration > max_iter: + return + + # Garbage collection (trigger manually so it happens on all ranks at the same time) + if (iteration + 1) % 150 == 0: + logger.info("Garbage collection") + gc.collect() + + if cfg.gram.use_loss and model.gram_it_load_ema_teacher == it: + logger.info(f"Loading EMA teacher into Gram teacher before iteration {it}") + model.gram_load_ema_teacher() + + # Learning rates and other schedules + lr = lr_schedule[it] + wd = wd_schedule[it] + mom = momentum_schedule[it] + teacher_temp = teacher_temp_schedule[it] + last_layer_lr = last_layer_lr_schedule[it] + apply_optim_scheduler(optimizer, lr, wd, last_layer_lr) + + # Forward backward + optimizer.zero_grad(set_to_none=True) + total_loss, metrics_dict = model.forward_backward(data, teacher_temp=teacher_temp, iteration=it) + + # Gradient clipping + if cfg.optim.clip_grad: + for k, v in student.items(): + grad_norm = torch.nn.utils.clip_grad_norm_( + v.parameters(), + max_norm=cfg.optim.clip_grad, + ) + metrics_dict[f"{k}_grad_norm"] = ( + grad_norm.full_tensor().item() + if isinstance(grad_norm, torch.distributed.tensor.DTensor) + else grad_norm.item() + ) + + # Reduce total_loss to check for NaNs, reduce metrics for logging + total_loss_all_ranks = total_loss.new_empty(distributed.get_subgroup_size()) + torch.distributed.all_gather_into_tensor( + total_loss_all_ranks, + total_loss.detach(), + group=distributed.get_process_subgroup(), + ) + total_loss = total_loss_all_ranks.mean() + metrics_values = torch.stack( + [torch.as_tensor(v, dtype=torch.float32, device=total_loss.device).detach() for v in metrics_dict.values()] + ) + torch.distributed.all_reduce( + metrics_values, + op=torch.distributed.ReduceOp.AVG, + group=distributed.get_process_subgroup(), + ) + metrics_dict = dict(zip(metrics_dict.keys(), metrics_values)) + if total_loss_all_ranks.isnan().any(): + consecutive_nan_count += 1 + which_ranks = total_loss_all_ranks.isnan().nonzero().flatten().tolist() + logger.warning("NaN loss detected on ranks: %s", which_ranks) + logger.warning("Consecutive NaNs: %d", consecutive_nan_count) + metrics_dict_str = "\n".join([f"{k}: {v}" for k, v in metrics_dict.items()]) + logger.warning("All-reduced metrics:\n%s", metrics_dict_str) + if consecutive_nan_count > 2 and not cfg.multidistillation.enabled: + msg = "Too many consecutive nans detected in loss, aborting..." + logger.error(msg) + raise RuntimeError(msg) + else: + consecutive_nan_count = 0 + # Step optimizer + optimizer.step() + model.update_ema(mom) + + # [GRAM] Update gram teacher when using gram teacher and frequent updates + if ( + cfg.gram.use_loss + and model.gram_rep_update + and (it + 1) >= model.gram_it_first_update + and (it + 1) % model.gram_update_frequency == 0 + and (cfg.gram.max_updates is None or num_gram_updates < cfg.gram.max_updates) + ): + logger.info(f"Updating Gram teacher from EMA teacher after iteration {it}") + model.update_gram() + num_gram_updates += 1 + + # Log metrics + metric_logger.update(lr=lr) + metric_logger.update(wd=wd) + metric_logger.update(mom=mom) + metric_logger.update(last_layer_lr=last_layer_lr) + metric_logger.update(total_loss=total_loss, **metrics_dict) + + # Submit evaluation jobs + if ( + cfg.evaluation.eval_period_iterations > 0 and (iteration + 1) % cfg.evaluation.eval_period_iterations == 0 + # and iteration != max_iter - 1 + ): + do_test(cfg, model, f"training_{iteration}", process_group=process_subgroup) + torch.cuda.synchronize() + + # Checkpointing + if (iteration + 1) % cfg.checkpointing.period == 0: + torch.cuda.synchronize() + save_checkpoint( + ckpt_dir / str(iteration), + iteration=iteration, + model=model, + optimizer=optimizer, + overwrite=True, + process_group=process_subgroup, + ) + if distributed.is_subgroup_main_process(): + keep_last_n_checkpoints(ckpt_dir, cfg.checkpointing.max_to_keep) + if "keep_every" in cfg.checkpointing and (iteration + 1) % cfg.checkpointing.keep_every == 0: + keep_checkpoint_copy(ckpt_dir / str(iteration)) + + iteration = iteration + 1 + metric_logger.synchronize_between_processes() + + return {k: meter.global_avg for k, meter in metric_logger.meters.items()} + + +def main(argv=None): + if argv is None: + args = get_args_parser().parse_args() + else: + args = get_args_parser().parse_args(argv[1:]) + args.output_dir = sys.argv[1] + if args.multi_distillation: + print("performing multidistillation run") + cfg = setup_multidistillation(args) + torch.distributed.barrier() + logger.info("setup_multidistillation done") + assert cfg.MODEL.META_ARCHITECTURE == "MultiDistillationMetaArch" + else: + setup_job(output_dir=args.output_dir, seed=args.seed) + cfg = setup_config(args, strict_cfg=False) + logger.info(cfg) + setup_logging( + output=os.path.join(os.path.abspath(args.output_dir), "nan_logs"), + name="nan_logger", + ) + meta_arch = { + "SSLMetaArch": SSLMetaArch, + "MultiDistillationMetaArch": MultiDistillationMetaArch, + }.get(cfg.MODEL.META_ARCHITECTURE, None) + if meta_arch is None: + raise ValueError(f"Unknown MODEL.META_ARCHITECTURE {cfg.MODEL.META_ARCHITECTURE}") + logger.info(f"Making meta arch {meta_arch.__name__}") + with torch.device("meta"): + model = meta_arch(cfg) + model.prepare_for_distributed_training() + # Fill all values with `nans` so that we identify + # non-initialized values + model._apply( + lambda t: torch.full_like( + t, + fill_value=math.nan if t.dtype.is_floating_point else (2 ** (t.dtype.itemsize * 8 - 1)), + device="cuda", + ), + recurse=True, + ) + logger.info(f"Model after distributed:\n{model}") + if args.eval_only: + model.init_weights() + iteration = ( + model.get_checkpointer_class()(model, save_dir=cfg.train.output_dir) + .resume_or_load(cfg.MODEL.WEIGHTS, resume=not args.no_resume) + .get("iteration", -1) + + 1 + ) + return do_test(cfg, model, f"manual_{iteration}") + do_train(cfg, model, resume=not args.no_resume) + + +if __name__ == "__main__": + main() diff --git a/starVLA/dinov3/dinov3/utils/__init__.py b/starVLA/dinov3/dinov3/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2794ac284e9bba24c6cee6a3eb5ecf7722f8734c --- /dev/null +++ b/starVLA/dinov3/dinov3/utils/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from .dtype import as_torch_dtype +from .utils import ( + cat_keep_shapes, + count_parameters, + fix_random_seeds, + get_conda_env, + get_sha, + named_apply, + named_replace, + uncat_with_shapes, +) diff --git a/starVLA/dinov3/dinov3/utils/cluster.py b/starVLA/dinov3/dinov3/utils/cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..25df3bc556241b1efc22908c7c832d5f3751682f --- /dev/null +++ b/starVLA/dinov3/dinov3/utils/cluster.py @@ -0,0 +1,103 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import os +from enum import Enum +from pathlib import Path +from typing import Any, Dict, Optional + + +class ClusterType(Enum): + CW = "cw" + + +def _guess_cluster_type() -> ClusterType: + return ClusterType.CW + + +def get_cluster_type( + cluster_type: Optional[ClusterType] = None, +) -> Optional[ClusterType]: + if cluster_type is None: + return _guess_cluster_type() + + return cluster_type + + +def get_slurm_account(cluster_type: Optional[ClusterType] = None) -> Optional[str]: + cluster_type = get_cluster_type(cluster_type) + if cluster_type is None: + return None + return { + ClusterType.CW: "fair_amaia_cw_explore", + }[cluster_type] + + +def get_checkpoint_path(cluster_type: Optional[ClusterType] = None) -> Optional[Path]: + cluster_type = get_cluster_type(cluster_type) + if cluster_type is None: + return None + + CHECKPOINT_DIRNAMES = { + ClusterType.CW: "", + } + return Path("/") / CHECKPOINT_DIRNAMES[cluster_type] + + +def get_user_checkpoint_path( + cluster_type: Optional[ClusterType] = None, +) -> Optional[Path]: + checkpoint_path = get_checkpoint_path(cluster_type) + if checkpoint_path is None: + return None + + username = os.environ.get("USER") + assert username is not None + return checkpoint_path / username + + +def get_slurm_qos(cluster_type: Optional[ClusterType] = None) -> Optional[str]: + cluster_type = get_cluster_type(cluster_type) + if cluster_type is None: + return None + + return { + ClusterType.CW: "explore", + }.get(cluster_type) + + +def get_slurm_partition(cluster_type: Optional[ClusterType] = None) -> Optional[str]: + cluster_type = get_cluster_type(cluster_type) + if cluster_type is None: + return None + + SLURM_PARTITIONS = { + ClusterType.CW: "learn", + } + return SLURM_PARTITIONS[cluster_type] + + +def get_slurm_executor_parameters( + nodes: int, + num_gpus_per_node: int, + cluster_type: Optional[ClusterType] = None, + **kwargs, +) -> Dict[str, Any]: + # create default parameters + params = { + "mem_gb": 0, # Requests all memory on a node, see https://slurm.schedmd.com/sbatch.html + "gpus_per_node": num_gpus_per_node, + "tasks_per_node": num_gpus_per_node, # one task per GPU + "cpus_per_task": 10, + "nodes": nodes, + "slurm_partition": get_slurm_partition(cluster_type), + } + # apply cluster-specific adjustments + cluster_type = get_cluster_type(cluster_type) + if cluster_type == ClusterType.CW: + params["cpus_per_task"] = 16 + # set additional parameters / apply overrides + params.update(kwargs) + return params diff --git a/starVLA/dinov3/dinov3/utils/custom_callable.py b/starVLA/dinov3/dinov3/utils/custom_callable.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7c2f762835a6027f94006fad3360cf19ca4be3 --- /dev/null +++ b/starVLA/dinov3/dinov3/utils/custom_callable.py @@ -0,0 +1,47 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import contextlib +import importlib +import inspect +import os +import sys +from pathlib import Path + + +@contextlib.contextmanager +def _load_modules_from_dir(dir_: str): + sys.path.insert(0, dir_) + yield + sys.path.pop(0) + + +def load_custom_callable(module_path: str | Path, callable_name: str): + module_full_path = os.path.realpath(module_path) + assert os.path.exists(module_full_path), f"module {module_full_path} does not exist" + module_dir, module_filename = os.path.split(module_full_path) + module_name, _ = os.path.splitext(module_filename) + + with _load_modules_from_dir(module_dir): + module = importlib.import_module(module_name) + if inspect.getfile(module) != module_full_path: + importlib.reload(module) + callable_ = getattr(module, callable_name) + + return callable_ + + +@contextlib.contextmanager +def change_working_dir_and_pythonpath(new_dir): + old_dir = Path.cwd() + new_dir = Path(new_dir).expanduser().resolve().as_posix() + old_pythonpath = sys.path.copy() + sys.path.insert(0, new_dir) + os.chdir(new_dir) + try: + yield + finally: + os.chdir(old_dir) + sys.path = old_pythonpath diff --git a/starVLA/dinov3/dinov3/utils/dtype.py b/starVLA/dinov3/dinov3/utils/dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..b2795ed42b512ce51890c8592db5c364b18a5f4c --- /dev/null +++ b/starVLA/dinov3/dinov3/utils/dtype.py @@ -0,0 +1,35 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from typing import Dict, Union + +import numpy as np +import torch + +TypeSpec = Union[str, np.dtype, torch.dtype] + + +_NUMPY_TO_TORCH_DTYPE: Dict[np.dtype, torch.dtype] = { + np.dtype("bool"): torch.bool, + np.dtype("uint8"): torch.uint8, + np.dtype("int8"): torch.int8, + np.dtype("int16"): torch.int16, + np.dtype("int32"): torch.int32, + np.dtype("int64"): torch.int64, + np.dtype("float16"): torch.float16, + np.dtype("float32"): torch.float32, + np.dtype("float64"): torch.float64, + np.dtype("complex64"): torch.complex64, + np.dtype("complex128"): torch.complex128, +} + + +def as_torch_dtype(dtype: TypeSpec) -> torch.dtype: + if isinstance(dtype, torch.dtype): + return dtype + if isinstance(dtype, str): + dtype = np.dtype(dtype) + assert isinstance(dtype, np.dtype), f"Expected an instance of nunpy dtype, got {type(dtype)}" + return _NUMPY_TO_TORCH_DTYPE[dtype] diff --git a/starVLA/dinov3/dinov3/utils/utils.py b/starVLA/dinov3/dinov3/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7b267033f49dfa0819406f48152f490b7c17ac94 --- /dev/null +++ b/starVLA/dinov3/dinov3/utils/utils.py @@ -0,0 +1,130 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +import logging +import os +import random +import subprocess +from typing import Callable, List, Optional, Tuple + +import numpy as np +import torch +from torch import Tensor, nn + +logger = logging.getLogger("dinov3") + + +def cat_keep_shapes(x_list: List[Tensor]) -> Tuple[Tensor, List[Tuple[int]], List[int]]: + shapes = [x.shape for x in x_list] + num_tokens = [x.select(dim=-1, index=0).numel() for x in x_list] + flattened = torch.cat([x.flatten(0, -2) for x in x_list]) + return flattened, shapes, num_tokens + + +def uncat_with_shapes(flattened: Tensor, shapes: List[Tuple[int]], num_tokens: List[int]) -> List[Tensor]: + outputs_splitted = torch.split_with_sizes(flattened, num_tokens, dim=0) + shapes_adjusted = [shape[:-1] + torch.Size([flattened.shape[-1]]) for shape in shapes] + outputs_reshaped = [o.reshape(shape) for o, shape in zip(outputs_splitted, shapes_adjusted)] + return outputs_reshaped + + +def named_replace( + fn: Callable, + module: nn.Module, + name: str = "", + depth_first: bool = True, + include_root: bool = False, +) -> nn.Module: + if not depth_first and include_root: + module = fn(module=module, name=name) + for child_name_o, child_module in list(module.named_children()): + child_name = ".".join((name, child_name_o)) if name else child_name_o + new_child = named_replace( + fn=fn, + module=child_module, + name=child_name, + depth_first=depth_first, + include_root=True, + ) + setattr(module, child_name_o, new_child) + + if depth_first and include_root: + module = fn(module=module, name=name) + return module + + +def named_apply( + fn: Callable, + module: nn.Module, + name: str = "", + depth_first: bool = True, + include_root: bool = False, +) -> nn.Module: + if not depth_first and include_root: + fn(module=module, name=name) + for child_name, child_module in module.named_children(): + child_name = ".".join((name, child_name)) if name else child_name + named_apply( + fn=fn, + module=child_module, + name=child_name, + depth_first=depth_first, + include_root=True, + ) + if depth_first and include_root: + fn(module=module, name=name) + return module + + +def fix_random_seeds(seed: int = 31): + """ + Fix random seeds. + """ + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + np.random.seed(seed) + random.seed(seed) + + +def get_sha() -> str: + cwd = os.path.dirname(os.path.abspath(__file__)) + + def _run(command): + return subprocess.check_output(command, cwd=cwd).decode("ascii").strip() + + sha = "N/A" + diff = "clean" + branch = "N/A" + try: + sha = _run(["git", "rev-parse", "HEAD"]) + subprocess.check_output(["git", "diff"], cwd=cwd) + diff = _run(["git", "diff-index", "HEAD"]) + diff = "has uncommited changes" if diff else "clean" + branch = _run(["git", "rev-parse", "--abbrev-ref", "HEAD"]) + except Exception: + pass + message = f"sha: {sha}, status: {diff}, branch: {branch}" + return message + + +def get_conda_env() -> Tuple[Optional[str], Optional[str]]: + conda_env_name = os.environ.get("CONDA_DEFAULT_ENV") + conda_env_path = os.environ.get("CONDA_PREFIX") + return conda_env_name, conda_env_path + + +def count_parameters(module: nn.Module) -> int: + c = 0 + for m in module.parameters(): + c += m.nelement() + return c + + +def has_batchnorms(model: nn.Module) -> bool: + bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm) + for _, module in model.named_modules(): + if isinstance(module, bn_types): + return True + return False diff --git a/starVLA/dinov3/hubconf.py b/starVLA/dinov3/hubconf.py new file mode 100644 index 0000000000000000000000000000000000000000..0f1c7e6f34ddd08c3da0708661e383c5d05a3987 --- /dev/null +++ b/starVLA/dinov3/hubconf.py @@ -0,0 +1,25 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from dinov3.hub.backbones import ( + dinov3_convnext_base, + dinov3_convnext_large, + dinov3_convnext_small, + dinov3_convnext_tiny, + dinov3_vit7b16, + dinov3_vitb16, + dinov3_vith16plus, + dinov3_vitl16, + dinov3_vitl16plus, + dinov3_vits16, + dinov3_vits16plus, +) +from dinov3.hub.classifiers import dinov3_vit7b16_lc +from dinov3.hub.depthers import dinov3_vit7b16_dd, dinov3_vitl16_chmv2 +from dinov3.hub.detectors import dinov3_vit7b16_de +from dinov3.hub.dinotxt import dinov3_vitl16_dinotxt_tet1280d20h24l +from dinov3.hub.segmentors import dinov3_vit7b16_ms + +dependencies = ["torch", "numpy"] diff --git a/starVLA/dinov3/pyproject.toml b/starVLA/dinov3/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..ede1516806550631618dcccdc74d10b4c0035984 --- /dev/null +++ b/starVLA/dinov3/pyproject.toml @@ -0,0 +1,45 @@ +[tool.mypy] +python_version = "3.11" +ignore_missing_imports = true +files = "dinov3" +exclude = '''(?x)( + ^dinov3/tests/([^/]+/)*test_.*\.py$ # Unit tests +)''' + +[tool.pylint.master] +persistent = false +score = false + +[tool.pylint.messages_control] +disable = "all" +enable = [ + "miscellaneous", + "similarities", +] + +[tool.pylint.similarities] +ignore-comments = true +ignore-docstrings = true +ignore-imports = true +min-similarity-lines = 8 + +[tool.pylint.reports] +reports = false + +[tool.pylint.miscellaneous] +notes = [ + "FIXME", + "XXX", + "TODO", +] + +[tool.ruff] +line-length = 120 +target-version = "py311" + +[tool.ruff.lint] +ignore = ["E203", "E501"] + +[tool.ruff.lint.per-file-ignores] +"__init__.py" = ["F401"] +"hubconf.py" = ["F401"] diff --git a/starVLA/dinov3/requirements-dev.txt b/starVLA/dinov3/requirements-dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..44cb0c6c6fd22ddb04add6a91dc4baa253b425e1 --- /dev/null +++ b/starVLA/dinov3/requirements-dev.txt @@ -0,0 +1,4 @@ +docstr-coverage==2.3.2 +mypy[reports]==1.17 +pylint==3.3.8 +ruff==0.12.8 diff --git a/starVLA/dinov3/requirements.txt b/starVLA/dinov3/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..c14d0fac8a9b2294fd2e9b5b3189f3c74b7a719e --- /dev/null +++ b/starVLA/dinov3/requirements.txt @@ -0,0 +1,9 @@ +ftfy +omegaconf +regex +scikit-learn +submitit +termcolor +torch +torchmetrics +torchvision diff --git a/starVLA/dinov3/setup.py b/starVLA/dinov3/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..9302c1249c4c57680aa7b8a6c33582932fa22364 --- /dev/null +++ b/starVLA/dinov3/setup.py @@ -0,0 +1,86 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This software may be used and distributed in accordance with +# the terms of the DINOv3 License Agreement. + +from pathlib import Path +import re +from typing import List, Tuple + +from setuptools import setup, find_packages + + +NAME = "dinov3" +DESCRIPTION = "" + +URL = "https://github.com/facebookresearch/dinov3" +AUTHOR = "Meta AI" +REQUIRES_PYTHON = ">=3.11" +HERE = Path(__file__).parent + + +try: + with open(HERE / "README.md", encoding="utf-8") as f: + long_description = "\n" + f.read() +except FileNotFoundError: + long_description = DESCRIPTION + + +def get_requirements(path: str = HERE / "requirements.txt") -> Tuple[List[str], List[str]]: + requirements = [] + extra_indices = [] + with open(path) as f: + for line in f.readlines(): + line = line.rstrip("\r\n") + if line.startswith("--extra-index-url "): + extra_indices.append(line[18:]) + continue + requirements.append(line) + return requirements, extra_indices + + +def get_package_version() -> str: + with open(HERE / "dinov3/__init__.py") as f: + result = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M) + if result: + return result.group(1) + raise RuntimeError("Can't get package version") + + +requirements, extra_indices = get_requirements() +version = get_package_version() +dev_requirements, _ = get_requirements(HERE / "requirements-dev.txt") + + +setup( + name=NAME, + version=version, + description=DESCRIPTION, + long_description=long_description, + long_description_content_type="text/markdown", + author=AUTHOR, + python_requires=REQUIRES_PYTHON, + url=URL, + packages=find_packages(), + package_data={ + "": ["*.yaml"], + }, + install_requires=requirements, + dependency_links=extra_indices, + extras_require={ + "dev": dev_requirements, + }, + install_package_data=True, + license="DINOv3 LIcense", + license_files=("LICENSE.md",), + classifiers=[ + # Trove classifiers: https://github.com/pypa/trove-classifiers/blob/main/src/trove_classifiers/__init__.py + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: Other/Proprietary License", + "Programming Language :: Python :: 3.11", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Software Development :: Libraries :: Python Modules", + ], +) diff --git a/starVLA/facebookresearch_vjepa2_main/.github/workflows/base_tests.yaml b/starVLA/facebookresearch_vjepa2_main/.github/workflows/base_tests.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3468aab3bc94f246ffc6e8cc50adb4326fae5b05 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/.github/workflows/base_tests.yaml @@ -0,0 +1,29 @@ +name: UnitTests + +on: [push] + +jobs: + unittests: + runs-on: ubuntu-latest + strategy: + max-parallel: 4 + + steps: + - uses: actions/checkout@v4 + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Add conda to system path + run: | + # $CONDA is an environment variable pointing to the root of the miniconda directory + echo $CONDA/bin >> $GITHUB_PATH + - name: Install dependencies + run: | + conda create --name test-env python=3.12 + conda install pytest + echo "Starting setup from $PWD" + pip install -e . + - name: Test with pytest + run: | + pytest tests diff --git a/starVLA/facebookresearch_vjepa2_main/.github/workflows/linters.yaml b/starVLA/facebookresearch_vjepa2_main/.github/workflows/linters.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c5f5fef89e91b2b220a61a188c73385dd4584d2e --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/.github/workflows/linters.yaml @@ -0,0 +1,48 @@ +name: Lint (Common Code) + +on: + push: + branches: + - master + paths: + - 'app/' + - 'evals/*.py' + - 'src/' + - 'tests/' + pull_request: + branches: + - master + - 'gh/**' + paths: + - 'app/' + - 'evals/*.py' + - 'src/' + - 'tests/' + +jobs: + run-linters: + name: Run linters + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install Python lint dependencies + run: | + pip install -r requirements-test.txt + - name: Set lint paths + run: echo "lint_paths=app evals/*.py src tests" >> "$GITHUB_ENV" + - name: Run isort + run: | + python -m isort $lint_paths --check + - name: Run flake8 + if: always() + run: | + python -m flake8 --config .flake8 --show-source --statistics $lint_paths + - name: Run black + if: always() + run: | + python -m black --check $lint_paths diff --git a/starVLA/facebookresearch_vjepa2_main/.gitignore b/starVLA/facebookresearch_vjepa2_main/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cb5a1240f8ca09808eb36bc390a56e36e916bd1f --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/.gitignore @@ -0,0 +1,32 @@ +*.pyc +.vscode/ +.*.swp + +run_vjepa_aws.py +run.py +main_distributed_video.py +main_video.py + +app/vjepa/configs/temp_aws +app/main_dev.py +app/main_distributed_dev.py +evals/ava/alphaction/data + +run_evals.py +run_evals_v2.py +run_pretrain.py + +*.egg-info/ +*.ipynb_checkpoints/ + +traces/ +third_party/* + +evals/simu_env_planning/local/ +evals/simu_env_planning/docker2/ +evals/simu_env_planning/docker/ +app/vjepa_droid/local/ +app/vjepa_droid_v2/local/ +app/vjepa_droid_v3/local/ +app/vjepa_droid_v4/local/ +configs/local \ No newline at end of file diff --git a/starVLA/facebookresearch_vjepa2_main/CHANGELOG.md b/starVLA/facebookresearch_vjepa2_main/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b0350a95b276ca537bd1fcf4c31daa09c8abeccd --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + + +## [0.0.2] - 2025-03-16 + +Release of V-JEPA 2.1 + + +## [0.0.1] - 2025-06-05 + +Initial release of V-JEPA 2 codebase diff --git a/starVLA/facebookresearch_vjepa2_main/CODE_OF_CONDUCT.md b/starVLA/facebookresearch_vjepa2_main/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..83f431e8feeb7e80d571f39c9f6c1b96857b5f85 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/CODE_OF_CONDUCT.md @@ -0,0 +1,80 @@ +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to make participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic +address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, and it also applies when +an individual is representing the project or its community in public spaces. +Examples of representing a project or community include using an official +project e-mail address, posting via an official social media account, or acting +as an appointed representative at an online or offline event. Representation of +a project may be further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when there is a +reasonable belief that an individual's behavior may have a negative impact on +the project or its community. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at . All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/starVLA/facebookresearch_vjepa2_main/CONTRIBUTING.md b/starVLA/facebookresearch_vjepa2_main/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..0d5dc72243ef7a20abe3c9de9e060d045b6558e9 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/CONTRIBUTING.md @@ -0,0 +1,39 @@ +# Contributing to V-JEPA 2 +We want to make contributing to this project as easy and transparent as +possible. + +## Pull Requests +We welcome your pull requests. + +1. Fork the repo and create your branch from `main`. +2. If you've added code that should be tested, add tests. +3. If you've changed APIs, update the documentation. +4. Ensure the test suite passes. +5. Make sure your code is consistent with style guidance (below) and lints. +6. If you haven't already, complete the Contributor License Agreement ("CLA"). +7. Add reviewer(s) for approval. + +## Contributor License Agreement ("CLA") +In order to accept your pull request, we need you to submit a CLA. You only need +to do this once to work on any of Facebook's open source projects. + +Complete your CLA here: + +## Issues +We use GitHub issues to track public bugs. Please ensure your description is +clear and has sufficient instructions to be able to reproduce the issue. + +Meta has a [bounty program](https://bugbounty.meta.com/) for the safe +disclosure of security bugs. In those cases, please go through the process +outlined on that page and do not file a public issue. + +## Coding Style +* 4 spaces for indentation rather than tabs +* 119 character line length +* PEP8 formatting + +We recommend using `black`, `isort`, and `flake8` to format your code changes. + +## License +By contributing to this repository, you agree that your contributions will be licensed +under the LICENSE file in the root directory of this source tree. diff --git a/starVLA/facebookresearch_vjepa2_main/LICENSE b/starVLA/facebookresearch_vjepa2_main/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a45a376fb0fcd4a3de06b6c096e62028929a2dcb --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Meta Platforms, Inc. and affiliates. + +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. \ No newline at end of file diff --git a/starVLA/facebookresearch_vjepa2_main/README.md b/starVLA/facebookresearch_vjepa2_main/README.md new file mode 100644 index 0000000000000000000000000000000000000000..29e7c35164facdcfc34b938473701ae3bb1862da --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/README.md @@ -0,0 +1,551 @@ + +🆕 **[2026-03-16]:** :fire: V-JEPA 2.1 is released :fire: A new familly of models trained with a novel recipe that learns high quality and temporolly consistent dense features !!! + +**[2025-06-25]:** V-JEPA 2 is released. [[`Blog`](https://ai.meta.com/blog/v-jepa-2-world-model-benchmarks)] + + +# V-JEPA 2: Self-Supervised Video Models Enable Understanding, Prediction and Planning + +### [Meta FAIR](https://ai.meta.com/research/) + +Mahmoud Assran∗, Adrien Bardes∗, David Fan∗, Quentin Garrido∗, Russell Howes∗, Mojtaba +Komeili∗, Matthew Muckley∗, Ammar Rizvi∗, Claire Roberts∗, Koustuv Sinha∗, Artem Zholus*, +Sergio Arnaud*, Abha Gejji*, Ada Martin*, Francois Robert Hogan*, Daniel Dugas*, Piotr +Bojanowski, Vasil Khalidov, Patrick Labatut, Francisco Massa, Marc Szafraniec, Kapil +Krishnakumar, Yong Li, Xiaodong Ma, Sarath Chandar, Franziska Meier*, Yann LeCun*, Michael +Rabbat*, Nicolas Ballas* + +*Core Team + +[[`Paper`](https://arxiv.org/abs/2506.09985)] [[`Blog`](https://ai.meta.com/blog/v-jepa-2-world-model-benchmarks)] [[`BibTex`](#Citation)] + +Official Pytorch codebase for V-JEPA 2, V-JEPA 2-AC, V-JEPA 2.1. + +V-JEPA 2 is a self-supervised approach to training video encoders, using internet-scale video data, that attains state-of-the-art performance on motion understanding and human action anticipation tasks. V-JEPA 2-AC is a latent action-conditioned world model post-trained from V-JEPA 2 (using a small amount of robot trajectory interaction data) that solves robot manipulation tasks without environment-specific data collection or task-specific training or calibration. + +

+ +

+ + + +## V-JEPA 2.1 Pre-training + +Lorenzo Mur-Labadia, Matthew Muckley, Amir Bar, Mahmoud Assran, Koustuv Sinha, Michael +Rabbat, Yann LeCun, Nicolas Ballas, Adrien Bardes + +[[`Paper`](https://arxiv.org/abs/TODO)] [[`BibTex`](#Citation)] + +V-JEPA 2.1 improves the training recipe to focus on learning high-quality and temporally consistent dense features, as higlighted by PCA visualizations: + +

+ +

+ +The V-JEPA 2.1 approach leverages: (1) **Dense Predictive Loss**, a masking-based +self-supervision objective where all tokens (both visible/context and masked tokens) contribute to the +self-supervised training loss; (2) **Deep Self-Supervision**, which applies the self-supervised loss at multiple +intermediate representations of the encoder models; (3) **Multi-Modal Tokenizers** for images and videos; +and we show that our approach benefit from (4) **Model and data scaling**. + +

+ +

+ +V-JEPA 2.1 performance across dense and global prediction tasks: + +

+ +

+ + +## V-JEPA 2 Pre-training + +**(Top)** The encoder and predictor are pre-trained through self-supervised learning from video using a masked latent feature prediction objective, leveraging abundant natural videos to bootstrap physical world understanding and prediction. **(Bottom)** Performance of V-JEPA 2 on downstream understanding and prediction tasks. + +  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BenchmarkV-JEPA 2Previous Best
EK10039.7%27.6% (PlausiVL)
SSv2 (Probe)77.3%69.7% (InternVideo2-1B)
Diving48 (Probe)90.2%86.4% (InternVideo2-1B)
MVP (Video QA)44.5%39.9% (InternVL-2.5)
TempCompass (Video QA)76.9%75.3% (Tarsier 2)
+ +## V-JEPA 2-AC Post-training + +**(Top)** After post-training with a small amount of robot data, we can deploy the model on a robot arm in new environments, and tackle foundational tasks like reaching, grasping, and pick-and-place by planning from image goals. **(Bottom)** Performance on robot manipulation tasks using a Franka arm, with input provided through a monocular RGB camera. + +  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
GraspPick-and-Place
MethodReachCupBoxCupBox
Octo100%10%0%10%10%
Cosmos80%0%20%0%0%
VJEPA 2-AC100%60%20%80%50%
+ + + + + +## Models + +### V-JEPA 2 and V-JEPA 2.1 + +#### HuggingFace + +See our HuggingFace [collection](https://huggingface.co/collections/facebook/v-jepa-2-6841bad8413014e185b497a6) for V-JEPA 2. + +#### V-JEPA 2 Pretrained Checkpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model#ParametersResolutionDownload LinkPretraining Config
ViT-L/16300M256checkpointconfigs
ViT-H/16600M256checkpointconfigs
ViT-g/161B256checkpointconfigs
ViT-g/163841B384checkpointconfigs
+ +#### V-JEPA 2.1 Pretrained Checkpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model#ParametersResolutionDownload LinkPretraining Config
ViT-B/1680M384checkpointconfigs
ViT-L/16300M384checkpointconfigs
ViT-g/161B384checkpointconfigs
ViT-G/162B384checkpointconfigs
+ + +#### Pretrained backbones (via PyTorch Hub) + +Please install [Pytorch](https://pytorch.org/get-started/locally/), [timm](https://pypi.org/project/timm/) and [einops](https://pypi.org/project/einops/) locally, then run the following to load each model. Installing Pytorch with CUDA support is strongly recommended. + +```python +import torch + +# preprocessor +processor = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_preprocessor') +# models +# V-JEPA 2 +vjepa2_vit_large = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_vit_large') +vjepa2_vit_huge = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_vit_huge') +vjepa2_vit_giant = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_vit_giant') +vjepa2_vit_giant_384 = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_vit_giant_384') +# V-JEPA 2.1 +vjepa2_1_vit_base_384 = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_1_vit_base_384') +vjepa2_1_vit_large_384 = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_1_vit_large_384') +vjepa2_1_vit_giant_384 = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_1_vit_giant_384') +vjepa2_1_vit_gigantic_384 = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_1_vit_gigantic_384') + +``` + +#### Pretrained checkpoints on Huggingface + +You can also use our pretrained checkpoints on [Huggingface for V-JEPA 2](https://huggingface.co/collections/facebook/v-jepa-2-6841bad8413014e185b497a6). + +```python +from transformers import AutoVideoProcessor, AutoModel + +hf_repo = "facebook/vjepa2-vitg-fpc64-256" +# facebook/vjepa2-vitl-fpc64-256 +# facebook/vjepa2-vith-fpc64-256 +# facebook/vjepa2-vitg-fpc64-256 +# facebook/vjepa2-vitg-fpc64-384 + +model = AutoModel.from_pretrained(hf_repo) +processor = AutoVideoProcessor.from_pretrained(hf_repo) +``` + +#### Evaluation Attentive Probes + +We share the trained attentive probes for two of our visual understanding evals (Something-Something v2 and Diving48) and the action anticipation eval EPIC-KITCHENS-100. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelSSv2Diving48EK100
CheckpointTraining ConfigInference ConfigResultCheckpointTraining ConfigInference ConfigResultCheckpointTraining ConfigInference ConfigResult
ViT-L/16checkpointconfigconfig73.7%checkpointconfigconfig89.0%checkpointconfigconfig32.7 R@5
ViT-g/16384checkpointconfigconfig77.3%checkpointconfigconfig90.2%checkpointconfigconfig39.7 R@5
+ +### V-JEPA 2-AC + +Our action-conditioned checkpoint was trained from the ViT-g encoder. + + + + + + + + + + + +
ModelDownload LinkTraining Config
ViT-g/16checkpointconfig
+ +#### Pretrained action-conditioned backbone (via PyTorch Hub) + +Please install [Pytorch](https://pytorch.org/get-started/locally/), [timm](https://pypi.org/project/timm/) and [einops](https://pypi.org/project/einops/) locally, then run the following to load each model. Installing Pytorch with CUDA support is strongly recommended. + +```python +import torch + +vjepa2_encoder, vjepa2_ac_predictor = torch.hub.load('facebookresearch/vjepa2', 'vjepa2_ac_vit_giant') +``` + + +See [energy_landscape_example.ipynb](notebooks/energy_landscape_example.ipynb) for an example notebook computing the energy landscape of the pretrained action-conditioned backbone using a robot trajectory collected from our lab. +To run this notebook, you'll need to additionally install [Jupyter](https://jupyter.org/install) and [Scipy](https://scipy.org/install/) in your conda environment. + + + +## Getting Started + +### Setup + +``` +conda create -n vjepa2-312 python=3.12 +conda activate vjepa2-312 +pip install . # or `pip install -e .` for development mode +``` + +**Note to macOS users:** V-JEPA 2 relies on [`decord`](https://github.com/dmlc/decord), which does not support macOS (and, unfortunately, is also no longer under development). In order to run the V-JEPA 2 code on macOS, you will need a different `decord` implementation. We do not make specific recommendations, although some users have reported the use of [`eva-decord`](https://github.com/georgia-tech-db/eva-decord) (see [PR 1](https://github.com/facebookresearch/vjepa2/pull/1)) or [`decord2`](https://github.com/johnnynunez/decord2) (see [PR 31](https://github.com/facebookresearch/vjepa2/pull/31)). We leave the selection of the `decord` package up to the user's discretion. + +### Usage Demo + +See [vjepa2_demo.ipynb](notebooks/vjepa2_demo.ipynb) [(Colab Link)](https://colab.research.google.com/github/facebookresearch/vjepa2/blob/main/notebooks/vjepa2_demo.ipynb) or [vjepa2_demo.py](notebooks/vjepa2_demo.py) for an example of how to load both the HuggingFace and PyTorch V-JEPA 2 models and run inference on a sample video to get a sample classification result. + +The script assumes the presence of downloaded model checkpoints so you will need to download the model weights and update the corresponding paths in the script. E.g.: +``` +wget https://dl.fbaipublicfiles.com/vjepa2/vitg-384.pt -P YOUR_DIR +wget https://dl.fbaipublicfiles.com/vjepa2/evals/ssv2-vitg-384-64x2x3.pt -P YOUR_DIR + +# Then update your model paths in vjepa2_demo.py. +pt_model_path = YOUR_DIR/vitg-384.pt +classifier_model_path = YOUR_DIR/ssv2-vitg-384-64x2x3.pt + +# Then run the script (assumes your machine has a GPU) +python -m notebooks.vjepa2_demo +``` + +### Probe-based evaluation + +Probe-based evaluation consists in training an attentive probe on top of frozen V-JEPA 2 features. We provide training scripts for training your own probes, and checkpoints to run inference directly. + +#### Training probes + +Evaluations can be run either locally, or distributed via SLURM. (Running locally is useful for debugging and validation). +These sample commands launch Something-Something v2 video classification; other evals are launched by specifying the corresponding config. +Use provided training configs under "Evaluation Attentive Probes". These configs allow to train multiple probes in parallel with various optimization parameters. +Change filepaths as needed (e.g. `folder`, `checkpoint`, `dataset_train`, `dataset_val`) to match locations of data and downloaded checkpoints on your local filesystem. +Change \# nodes and local batch size as needed to not exceed available GPU memory. + +##### Local + +To run locally, specify the GPUs to use on +``` +python -m evals.main --fname configs/eval/vitl16/ssv2.yaml \ + --devices cuda:0 cuda:1 +``` + +##### Distributed + +``` +python -m evals.main_distributed \ + --fname configs/eval/vitl/ssv2.yaml \ + --time 8600 \ + --account my_account --qos=my_qos +``` + +#### Inference from existing probes + +Use provided inference configs under [Evaluation Attentive Probes](#evaluation-attentive-probes). +Download the corresponding checkpoint, rename it to 'latest.pt', and create a folder with the checkpoint inside, with the format matching the variables in the config: +``` +[folder]/[eval_name]/[tag]/latest.pt +``` +Then run inference, locally or distributed, using the same evaluation commands as above, but with configs from `configs/inference`. + +### Pretraining + +Likewise, training can also be run locally or distributed. Pretraining and cooldown training phases are +run with the same command using different configs. +These sample commands launch initial training of a ViT-L model. Configs for cooldown (or action-conditioned) training +can be found in the same directory as the config for initial training. + +#### Local + +``` +python -m app.main --fname configs/train/vitl16/pretrain-256px-16f.yaml \ + --devices cuda:0 +``` + +#### Distributed + +``` +python -m app.main_distributed \ + --fname configs/train/vitl16/pretrain-256px-16f.yaml + --time 6000 + --account my_account --qos=my_qos +``` + +### Postraining + +Post-training of the action-conditioned model, starting from the pretrained VJEPA 2 backbone, also follows a similar interface, and can be run locally or distributed using [this config](configs/train/vitg16/droid-256px-8f.yaml). +We post-train the model starting from the ViT-g/16 backbone. + +#### Local + +``` +python -m app.main --fname configs/train/vitg16/droid-256px-8f.yaml \ + --devices cuda:0 +``` + +#### Distributed + +``` +python -m app.main_distributed \ + --fname configs/train/vitg16/droid-256px-8f.yaml + --time 6000 + --account my_account --qos=my_qos +``` + + +## Code Structure + +``` +. +├── app # training loops +│ ├── vjepa # V-JEPA 2 pre-training +│ ├── vjepa_2_1 # V-JEPA 2.1 pre-training +│ ├── vjepa_droid # training the action-conditioned model +│ ├── main_distributed.py # entrypoint for launch app on slurm cluster +│ └── main.py # entrypoint for launch app locally on your machine +├── configs # config files with experiment params for training and evaluation +│ ├── train # pretraining with V-JEPA 2 (phase 1), cooldown (phase 2), and action-conditioned training +│ ├── train_2_1 # pretraining with V-JEPA 2.1 (phase 1), cooldown (phase 2) +│ └── eval # frozen evaluations +│ └── inference # inference only frozen evaluations +├── evals # evaluation loops training an attentive probe with frozen backbone... +│ ├── action_anticipation_frozen # action anticipation +│ ├── image_classification_frozen # image understanding +│ ├── video_classification_frozen # video understanding +│ ├── main_distributed.py # entrypoint for distributed evaluations +│ └── main.py # entrypoint for locally-run evaluations +├── src # the package +│ ├── datasets # datasets, data loaders, ... +│ ├── models # model definitions +│ ├── masks # mask collators, masking utilities, ... +│ └── utils # shared utilities +├── tests # unit tests for some modules in `src` + +``` + +## License + +The majority of V-JEPA 2 is licensed under MIT, however portions of the project are available under separate license terms: + +[src/datasets/utils/video/randaugment.py](src/datasets/utils/video/randaugment.py)
+[src/datasets/utils/video/randerase.py](src/datasets/utils/video/randerase.py)
+[src/datasets/utils/worker_init_fn.py](src/datasets/utils/worker_init_fn.py)
+ +are licensed under the Apache 2.0 license. + + +## Citation +If you find this repository useful in your research, please consider giving a star :star: and cite the papers: + +```bibtex +@article{assran2025vjepa2, + title={V-JEPA~2: Self-Supervised Video Models Enable Understanding, Prediction and Planning}, + author={Assran, Mahmoud and Bardes, Adrien and Fan, David and Garrido, Quentin and Howes, Russell and +Komeili, Mojtaba and Muckley, Matthew and Rizvi, Ammar and Roberts, Claire and Sinha, Koustuv and Zholus, Artem and +Arnaud, Sergio and Gejji, Abha and Martin, Ada and Robert Hogan, Francois and Dugas, Daniel and +Bojanowski, Piotr and Khalidov, Vasil and Labatut, Patrick and Massa, Francisco and Szafraniec, Marc and +Krishnakumar, Kapil and Li, Yong and Ma, Xiaodong and Chandar, Sarath and Meier, Franziska and LeCun, Yann and +Rabbat, Michael and Ballas, Nicolas}, + journal={arXiv preprint arXiv:2506.09985}, + year={2025} +} +``` + +```bibtex +@article{murlabadia2026vjepa2_1, + title={V-JEPA 2.1: Unlocking Dense Features in Video Self-Supervised Learning}, + author={Mur-Labadia, Lorenzo and Muckley, Matthew and Bar, Amir and Assran, Mahmoud and +Sinha, Koustuv and Rabbat, Michael and LeCun, Yann and Ballas, Nicolas and Bardes, Adrien}, + journal={arXiv preprint arXiv:2603.14482}, + year={2026} +} +``` diff --git a/starVLA/facebookresearch_vjepa2_main/__init__.py b/starVLA/facebookresearch_vjepa2_main/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/facebookresearch_vjepa2_main/app/main.py b/starVLA/facebookresearch_vjepa2_main/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..32cd18319c972772d9bfa6d152139379079d8b80 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/main.py @@ -0,0 +1,84 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import argparse +import multiprocessing as mp +import pprint +from pathlib import Path + +import yaml + +from app.scaffold import main as app_main +from src.utils.distributed import init_distributed + +parser = argparse.ArgumentParser() +parser.add_argument("--fname", type=str, help="name of config file to load", default="configs.yaml") +parser.add_argument( + "--devices", + type=str, + nargs="+", + default=["cuda:0", "cuda:1", "cuda:2", "cuda:3", "cuda:4", "cuda:5", "cuda:6", "cuda:7"], + help="which devices to use on local machine", +) +parser.add_argument( + "--debugmode", + type=bool, + default=False, + help="Setting this to true will not spin up new processes. " + "The main code runs the main process, which makes it easier to \ + debug with checkpointing.", +) + + +def process_main(rank, fname, world_size, devices): + import os + + os.environ["CUDA_VISIBLE_DEVICES"] = str(devices[rank].split(":")[-1]) + + import logging + + from src.utils.logging import get_logger + + logger = get_logger(force=True) + if rank == 0: + logger.setLevel(logging.INFO) + else: + logger.setLevel(logging.ERROR) + + logger.info(f"called-params {fname}") + + # Load config + params = None + with open(fname, "r") as y_file: + params = yaml.load(y_file, Loader=yaml.FullLoader) + logger.info("loaded params...") + + # Log config + if rank == 0: + pprint.PrettyPrinter(indent=4).pprint(params) + folder = params["folder"] + params_path = os.path.join(folder, "params-pretrain.yaml") + folder = Path(folder) + folder.mkdir(parents=True, exist_ok=True) + with open(params_path, "w") as f: + yaml.dump(params, f) + + # Init distributed (access to comm between GPUS on same machine) + world_size, rank = init_distributed(rank_and_world_size=(rank, world_size)) + logger.info(f"Running... (rank: {rank}/{world_size})") + + # Launch the app with loaded config + app_main(params["app"], args=params) + + +if __name__ == "__main__": + args = parser.parse_args() + if args.debugmode: + process_main(rank=0, fname=args.fname, world_size=1, devices=["cuda:0"]) + else: + num_gpus = len(args.devices) + mp.set_start_method("spawn") + for rank in range(num_gpus): + mp.Process(target=process_main, args=(rank, args.fname, num_gpus, args.devices)).start() diff --git a/starVLA/facebookresearch_vjepa2_main/app/main_distributed.py b/starVLA/facebookresearch_vjepa2_main/app/main_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..353d5dc1c337de6e5ebbcead32ddcc742fa985d6 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/main_distributed.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import argparse +import copy +import datetime +import os +import pprint +import shutil +from pathlib import Path + +import submitit +import yaml + +from app.scaffold import main as app_main +from src.utils.logging import get_logger, git_information + +logger = get_logger(force=True) + + +parser = argparse.ArgumentParser() +parser.add_argument( + "--fname", + type=str, + help="yaml file containing config file names to launch", + default="configs.yaml", +) +parser.add_argument("--exclude", type=str, help="nodes to exclude from training", default=None) +parser.add_argument( + "--batch-launch", + action="store_true", + help="whether fname points to a file to batch-launch several config files", +) +parser.add_argument( + "--use_fname_as_folder", + action="store_true", + help="whether to append fname filename to folder", +) +parser.add_argument( + "--folder", + type=str, + default=None, + help="if specified, override 'folder' field in the .yaml with this", +) +parser.add_argument( + "--account", + type=str, + default="jepa", + help="Cluster account to use when submitting jobs", +) +parser.add_argument( + "--partition", + type=str, + default="learn", + help="Cluster partition to use when submitting jobs", +) +parser.add_argument( + "--qos", + type=str, + default=None, + help="If specified, cluster partition to use when submitting jobs", +) +parser.add_argument("--time", type=int, default=4300, help="time in minutes to run job") + + +class Trainer: + def __init__(self, args_pretrain, load_model=None): + self.app = args_pretrain["app"] + self.args_pretrain = args_pretrain + self.load_model = load_model + + def __call__(self): + app = self.app + params = self.args_pretrain + load_model = self.load_model + + logger.info("loaded pretrain params...") + pp = pprint.PrettyPrinter(indent=4) + pp.pprint(params) + + # Launch app with loaded config + resume_preempt = False if load_model is None else load_model + app_main(app, args=params, resume_preempt=resume_preempt) + + def checkpoint(self): + fb_trainer = Trainer(self.args_pretrain, True) + return submitit.helpers.DelayedSubmission( + fb_trainer, + ) + + +def copy_code_folder(code_folder, ignore_patterns, ignore_paths): + path_to_node_folder = {} + + for path in ignore_paths: + split_path = path.split("/") + base_path = "/".join(split_path[:-1]) + node_folder = split_path[-1] + path_to_node_folder[base_path] = node_folder + + def ignore_func(path, names): + ignore_list = ignore_patterns + if path in path_to_node_folder.keys(): + ignore_list.append(path_to_node_folder[path]) + return ignore_list + + if not os.path.exists(code_folder): + shutil.copytree(".", code_folder, ignore=ignore_func) + + +def update_folder_with_timestamp(args_list): + new_args_list = copy.deepcopy(args_list) + for i, args in enumerate(args_list): + folder = args["folder"] + load_checkpoint = args["meta"].get("load_checkpoint", False) if "meta" in args else False + if not load_checkpoint and Path(folder).exists(): + timestamp = datetime.datetime.now().strftime("%y_%m_%d_%H_%M_%S") + folder = folder.rstrip("/") + f"_{timestamp}" + logger.info(f"Folder already exists but `load_checkpoint` is False. Logging to new folder {folder}...") + new_args_list[i]["folder"] = folder + return new_args_list + + +def launch_app_with_parsed_args( + args_for_pretrain, + account, + partition, + qos, + mem_per_gpu="210G", + timeout=4300, + nodes=1, + tasks_per_node=1, + cpus_per_task=12, + exclude_nodes=None, +): + args_for_pretrain = update_folder_with_timestamp(args_for_pretrain) + for ap in args_for_pretrain: + folder = ap["folder"] + Path(folder).mkdir(parents=True, exist_ok=True) + folder = args_for_pretrain[0]["folder"] + + # -------------- Copy code -------------- + code_folder = os.path.join(folder, "code") + ignore_patterns = [ + "__pycache__", + ".vscode", + ".git", + "core", + ] + ignore_paths = [ + "./evals/ava/alphaction/data", + "./demos", + "./traces", + ] + copy_code_folder(code_folder, ignore_patterns, ignore_paths) + os.chdir(code_folder) + # --------------------------------------- + + # -------------- Save config file -------------- + params_path = os.path.join(folder, "params-pretrain.yaml") + if not os.path.exists(params_path): + with open(params_path, "w") as f: + yaml.dump(args_for_pretrain, f) + # ---------------------------------------------- + + # -------------- Save git info file -------------- + git_info_fpath = os.path.join(folder, "git-info.txt") + with open(git_info_fpath, "w") as f: + f.write(git_information()) + # ---------------------------------------------- + + # -------------- SET JOB NAME -------------- + folder_ = folder + if folder[-1] == "/": + folder_ = folder[:-1] + job_name = folder_.split("/")[-1] + # ------------------------------------------ + + executor = submitit.AutoExecutor(folder=os.path.join(folder, "job_%j"), slurm_max_num_timeout=20) + executor.update_parameters( + name=job_name, + slurm_partition=partition, + slurm_account=account, + slurm_qos=qos, + slurm_mem_per_gpu=mem_per_gpu, + timeout_min=timeout, + nodes=nodes, + tasks_per_node=tasks_per_node, + cpus_per_task=cpus_per_task, + gpus_per_node=tasks_per_node, + ) + + if exclude_nodes is not None: + executor.update_parameters(slurm_exclude=exclude_nodes) + + jobs, trainers = [], [] + with executor.batch(): + for ap in args_for_pretrain: + # TODO Create sub folder and ap['folder']=subfolder + fb_trainer = Trainer(ap) + job = executor.submit( + fb_trainer, + ) + trainers.append(fb_trainer) + jobs.append(job) + + for job in jobs: + print(job.job_id) + + +def launch(): + # ---------------------------------------------------------------------- # + # 1. Put config file names in a list + # ---------------------------------------------------------------------- # + config_fnames = [args.fname] + + # -- If batch-launch is True, then the args.fname yaml file is not a + # -- config, but actually specifies a list of other config files + # -- to run in a slurm job array + if args.batch_launch: + with open(args.fname, "r") as y_file: + config_fnames = yaml.load(y_file, Loader=yaml.FullLoader) + # ---------------------------------------------------------------------- # + + # ---------------------------------------------------------------------- # + # 2. Parse each yaml config file as a dict and place in list + # ---------------------------------------------------------------------- # + nodes, tasks_per_node = None, None + configs = [] + for f in config_fnames: + with open(f, "r") as y_file: + _params = yaml.load(y_file, Loader=yaml.FullLoader) + if args.use_fname_as_folder: + assert not args.folder, "Don't specify --folder if adding fname to folder" + _params["folder"] = str(Path(_params["folder"]) / f.split("/")[-1].split(".yaml")[0]) + elif args.folder: + _params["folder"] = args.folder + nodes = int(_params.get("nodes")) + tasks_per_node = int(_params.get("tasks_per_node")) + cpus_per_task = int(_params.get("cpus_per_task", 32)) + mem_per_gpu = _params.get("mem_per_gpu", "210G") + configs += [_params] + logger.info(f"Loaded {len(configs)} config files") + logger.info(f"Running all jobs with {nodes=} / {tasks_per_node=}") + # ---------------------------------------------------------------------- # + + # ---------------------------------------------------------------------- # + # 3. Launch evals with parsed config files + # ---------------------------------------------------------------------- # + launch_app_with_parsed_args( + args_for_pretrain=configs, + account=args.account, + partition=args.partition, + qos=args.qos, + mem_per_gpu=mem_per_gpu, + cpus_per_task=cpus_per_task, + timeout=args.time, + nodes=nodes, + tasks_per_node=tasks_per_node, + exclude_nodes=args.exclude, + ) + # ---------------------------------------------------------------------- # + + +if __name__ == "__main__": + args = parser.parse_args() + launch() diff --git a/starVLA/facebookresearch_vjepa2_main/app/scaffold.py b/starVLA/facebookresearch_vjepa2_main/app/scaffold.py new file mode 100644 index 0000000000000000000000000000000000000000..60a41bc43b289c556cc8df9975c93a129d8ead94 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/scaffold.py @@ -0,0 +1,17 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import importlib +import logging +import sys + +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +logger = logging.getLogger() + + +def main(app, args, resume_preempt=False): + + logger.info(f"Running pre-training of app: {app}") + return importlib.import_module(f"app.{app}.train").main(args=args, resume_preempt=resume_preempt) diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa/train.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa/train.py new file mode 100644 index 0000000000000000000000000000000000000000..69a735db7049ca218dd913b53516c3976bdca42c --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa/train.py @@ -0,0 +1,536 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os + +# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESS +try: + # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE + # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE + # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE + # -- TO EACH PROCESS + os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"] +except Exception: + pass + +import copy +import gc +import random +import time + +import numpy as np +import torch +import torch.multiprocessing as mp +import torch.nn.functional as F +from torch.nn.parallel import DistributedDataParallel + +from app.vjepa.transforms import make_transforms +from app.vjepa.utils import init_opt, init_video_model, load_checkpoint +from src.datasets.data_manager import init_data +from src.masks.multiseq_multiblock3d import MaskCollator +from src.masks.utils import apply_masks +from src.utils.distributed import init_distributed +from src.utils.logging import AverageMeter, CSVLogger, get_logger, gpu_timer + +# -- +log_timings = True +log_freq = 10 +CHECKPOINT_FREQ = 1 +GARBAGE_COLLECT_ITR_FREQ = 50 +# -- + +_GLOBAL_SEED = 0 +random.seed(_GLOBAL_SEED) +np.random.seed(_GLOBAL_SEED) +torch.manual_seed(_GLOBAL_SEED) +torch.backends.cudnn.benchmark = True + + +logger = get_logger(__name__, force=True) + + +def main(args, resume_preempt=False): + # ----------------------------------------------------------------------- # + # PASSED IN PARAMS FROM CONFIG FILE + # ----------------------------------------------------------------------- # + + # -- META + folder = args.get("folder") + cfgs_meta = args.get("meta") + load_model = cfgs_meta.get("load_checkpoint") or resume_preempt + r_file = cfgs_meta.get("read_checkpoint", None) + seed = cfgs_meta.get("seed", _GLOBAL_SEED) + save_every_freq = cfgs_meta.get("save_every_freq", -1) + skip_batches = cfgs_meta.get("skip_batches", -1) + use_sdpa = cfgs_meta.get("use_sdpa", False) + sync_gc = cfgs_meta.get("sync_gc", False) + which_dtype = cfgs_meta.get("dtype") + logger.info(f"{which_dtype=}") + if which_dtype.lower() == "bfloat16": + dtype = torch.bfloat16 + mixed_precision = True + elif which_dtype.lower() == "float16": + dtype = torch.float16 + mixed_precision = True + else: + dtype = torch.float32 + mixed_precision = False + + # -- MASK + cfgs_mask = args.get("mask") + + # -- MODEL + cfgs_model = args.get("model") + compile_model = cfgs_model.get("compile_model", False) + use_activation_checkpointing = cfgs_model.get("use_activation_checkpointing", False) + model_name = cfgs_model.get("model_name") + pred_depth = cfgs_model.get("pred_depth") + pred_num_heads = cfgs_model.get("pred_num_heads", None) + pred_embed_dim = cfgs_model.get("pred_embed_dim") + uniform_power = cfgs_model.get("uniform_power", False) + use_mask_tokens = cfgs_model.get("use_mask_tokens", False) + zero_init_mask_tokens = cfgs_model.get("zero_init_mask_tokens", True) + use_rope = cfgs_model.get("use_rope", False) + use_silu = cfgs_model.get("use_silu", False) + use_pred_silu = cfgs_model.get("use_pred_silu", False) + wide_silu = cfgs_model.get("wide_silu", True) + + # -- DATA + cfgs_data = args.get("data") + dataset_type = cfgs_data.get("dataset_type", "videodataset") + dataset_paths = cfgs_data.get("datasets", []) + datasets_weights = cfgs_data.get("datasets_weights") + dataset_fpcs = cfgs_data.get("dataset_fpcs") + max_num_frames = max(dataset_fpcs) + if datasets_weights is not None: + assert len(datasets_weights) == len(dataset_paths), "Must have one sampling weight specified for each dataset" + batch_size = cfgs_data.get("batch_size") + tubelet_size = cfgs_data.get("tubelet_size") + fps = cfgs_data.get("fps") + crop_size = cfgs_data.get("crop_size", 224) + patch_size = cfgs_data.get("patch_size") + pin_mem = cfgs_data.get("pin_mem", False) + num_workers = cfgs_data.get("num_workers", 1) + persistent_workers = cfgs_data.get("persistent_workers", True) + + # -- DATA AUGS + cfgs_data_aug = args.get("data_aug") + ar_range = cfgs_data_aug.get("random_resize_aspect_ratio", [3 / 4, 4 / 3]) + rr_scale = cfgs_data_aug.get("random_resize_scale", [0.3, 1.0]) + motion_shift = cfgs_data_aug.get("motion_shift", False) + reprob = cfgs_data_aug.get("reprob", 0.0) + use_aa = cfgs_data_aug.get("auto_augment", False) + + # -- LOSS + cfgs_loss = args.get("loss") + loss_exp = cfgs_loss.get("loss_exp") + + # -- OPTIMIZATION + cfgs_opt = args.get("optimization") + is_anneal = cfgs_opt.get("is_anneal", False) + anneal_ckpt = cfgs_opt.get("anneal_ckpt", None) + if is_anneal and anneal_ckpt is None: + raise ValueError("Must specify anneal_ckpt if is_anneal is True") + resume_anneal = cfgs_opt.get("resume_anneal", False) or (is_anneal and resume_preempt) + ipe = cfgs_opt.get("ipe", None) + ipe_scale = cfgs_opt.get("ipe_scale", 1.0) + wd = float(cfgs_opt.get("weight_decay")) + final_wd = float(cfgs_opt.get("final_weight_decay")) + num_epochs = cfgs_opt.get("epochs") + warmup = cfgs_opt.get("warmup") + start_lr = cfgs_opt.get("start_lr") + lr = cfgs_opt.get("lr") + final_lr = cfgs_opt.get("final_lr") + ema = cfgs_opt.get("ema") + betas = cfgs_opt.get("betas", (0.9, 0.999)) + eps = cfgs_opt.get("eps", 1.0e-8) + # ----------------------------------------------------------------------- # + # ----------------------------------------------------------------------- # + + np.random.seed(seed) + torch.manual_seed(seed) + torch.backends.cudnn.benchmark = True + try: + mp.set_start_method("spawn") + except Exception: + pass + + # -- init torch distributed backend + world_size, rank = init_distributed() + logger.info(f"Initialized (rank/world-size) {rank}/{world_size}") + + # -- set device + if not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device("cuda:0") + torch.cuda.set_device(device) + + # -- log/checkpointing paths + log_file = os.path.join(folder, f"log_r{rank}.csv") + latest_file = "latest.pt" + latest_path = os.path.join(folder, latest_file) + load_path = None + if load_model: + if is_anneal: + if os.path.exists(latest_path) and resume_anneal: + load_path = latest_path + else: + load_path = anneal_ckpt + resume_anneal = False + else: + load_path = r_file if r_file is not None else latest_path + if not os.path.exists(load_path): + load_path = None + load_model = False + + # -- make csv_logger + csv_logger = CSVLogger( + log_file, + ("%d", "epoch"), + ("%d", "itr"), + ("%.5f", "loss"), + ("%d", "iter-time(ms)"), + ("%d", "gpu-time(ms)"), + ("%d", "dataload-time(ms)"), + ) + + # -- init model + encoder, predictor = init_video_model( + uniform_power=uniform_power, + use_mask_tokens=use_mask_tokens, + num_mask_tokens=int(len(cfgs_mask) * len(dataset_fpcs)), + zero_init_mask_tokens=zero_init_mask_tokens, + device=device, + patch_size=patch_size, + max_num_frames=max_num_frames, + tubelet_size=tubelet_size, + model_name=model_name, + crop_size=crop_size, + pred_depth=pred_depth, + pred_num_heads=pred_num_heads, + pred_embed_dim=pred_embed_dim, + use_sdpa=use_sdpa, + use_silu=use_silu, + use_pred_silu=use_pred_silu, + wide_silu=wide_silu, + use_rope=use_rope, + use_activation_checkpointing=use_activation_checkpointing, + ) + target_encoder = copy.deepcopy(encoder) + + if compile_model: + logger.info("Compiling encoder, target_encoder, and predictor.") + torch._dynamo.config.optimize_ddp = False + encoder.compile() + target_encoder.compile() + predictor.compile() + + mask_collator = MaskCollator( + cfgs_mask=cfgs_mask, + dataset_fpcs=dataset_fpcs, + crop_size=crop_size, + patch_size=patch_size, + tubelet_size=tubelet_size, + ) + transform = make_transforms( + random_horizontal_flip=True, + random_resize_aspect_ratio=ar_range, + random_resize_scale=rr_scale, + reprob=reprob, + auto_augment=use_aa, + motion_shift=motion_shift, + crop_size=crop_size, + ) + + # -- init data-loaders/samplers + (unsupervised_loader, unsupervised_sampler) = init_data( + data=dataset_type, + root_path=dataset_paths, + batch_size=batch_size, + training=True, + dataset_fpcs=dataset_fpcs, + fps=fps, + transform=transform, + rank=rank, + world_size=world_size, + datasets_weights=datasets_weights, + persistent_workers=persistent_workers, + collator=mask_collator, + num_workers=num_workers, + pin_mem=pin_mem, + log_dir=None, + ) + try: + _dlen = len(unsupervised_loader) + except Exception: # Different interface for webdataset + _dlen = unsupervised_loader.num_batches + if ipe is None: + ipe = _dlen + logger.info(f"iterations per epoch/dataset length: {ipe}/{_dlen}") + + # -- init optimizer and scheduler + optimizer, scaler, scheduler, wd_scheduler = init_opt( + is_anneal=is_anneal, + encoder=encoder, + predictor=predictor, + wd=wd, + final_wd=final_wd, + start_lr=start_lr, + ref_lr=lr, + final_lr=final_lr, + iterations_per_epoch=ipe, + warmup=warmup, + num_epochs=num_epochs, + ipe_scale=ipe_scale, + mixed_precision=mixed_precision, + betas=betas, + eps=eps, + ) + encoder = DistributedDataParallel(encoder, static_graph=True) + predictor = DistributedDataParallel(predictor, static_graph=False, find_unused_parameters=True) + target_encoder = DistributedDataParallel(target_encoder) + for p in target_encoder.parameters(): + p.requires_grad = False + + # -- momentum schedule + momentum_scheduler = ( + ema[0] + i * (ema[1] - ema[0]) / (ipe * num_epochs * ipe_scale) + for i in range(int(ipe * num_epochs * ipe_scale) + 1) + ) + + start_epoch = 0 + # -- load training checkpoint + if load_model or os.path.exists(latest_path): + ( + encoder, + predictor, + target_encoder, + optimizer, + scaler, + start_epoch, + ) = load_checkpoint( + r_path=load_path, + encoder=encoder, + predictor=predictor, + target_encoder=target_encoder, + opt=optimizer, + scaler=scaler, + is_anneal=is_anneal and not resume_anneal, + ) + if not is_anneal or resume_anneal: + for _ in range(start_epoch * ipe): + scheduler.step() + wd_scheduler.step() + next(momentum_scheduler) + mask_collator.step() + + def save_checkpoint(epoch, path): + if rank != 0: + return + save_dict = { + "encoder": encoder.state_dict(), + "predictor": predictor.state_dict(), + "opt": optimizer.state_dict(), + "scaler": None if scaler is None else scaler.state_dict(), + "target_encoder": target_encoder.state_dict(), + "epoch": epoch, + "loss": loss_meter.avg, + "batch_size": batch_size, + "world_size": world_size, + "lr": lr, + } + try: + torch.save(save_dict, path) + except Exception as e: + logger.info(f"Encountered exception when saving checkpoint: {e}") + + logger.info("Initializing loader...") + unsupervised_sampler.set_epoch(start_epoch) + loader = iter(unsupervised_loader) + + if skip_batches > 0: + logger.info(f"Skip {skip_batches} batches") + # -- update distributed-data-loader epoch + + for itr in range(skip_batches): + if itr % 10 == 0: + logger.info(f"Skip {itr}/{skip_batches} batches") + try: + _ = next(loader) + except Exception: + loader = iter(unsupervised_loader) + _ = next(loader) + + if sync_gc: + gc.disable() + gc.collect() + + # -- TRAINING LOOP + for epoch in range(start_epoch, num_epochs): + logger.info("Epoch %d" % (epoch + 1)) + + loss_meter = AverageMeter() + mask_meters = {fpc: AverageMeter() for fpc in dataset_fpcs} + iter_time_meter = AverageMeter() + gpu_time_meter = AverageMeter() + data_elapsed_time_meter = AverageMeter() + + for itr in range(ipe): + itr_start_time = time.time() + + iter_retries = 0 + iter_successful = False + while not iter_successful: + try: + sample = next(loader) + iter_successful = True + except StopIteration: + logger.info("Exhausted data loaders. Refreshing...") + unsupervised_sampler.set_epoch(epoch) + loader = iter(unsupervised_loader) + except Exception as e: + NUM_RETRIES = 5 + if iter_retries < NUM_RETRIES: + logger.warning(f"Encountered exception when loading data (num retries {iter_retries}):\n{e}") + iter_retries += 1 + time.sleep(5) + else: + logger.warning(f"Exceeded max retries ({NUM_RETRIES}) when loading data. Skipping batch.") + raise e + + for _fpc_sample in sample: + bs, fpc = _fpc_sample[0][-1][0].size() + mask_meters[fpc].update(bs / batch_size) + + def load_clips(): + all_clips, all_masks_enc, all_masks_pred = [], [], [] + for fpc_sample in sample: + udata, masks_enc, masks_pred = fpc_sample + all_clips += [udata[0][0].to(device, non_blocking=True)] + all_masks_enc += [[m.to(device, non_blocking=True) for m in masks_enc]] + all_masks_pred += [[m.to(device, non_blocking=True) for m in masks_pred]] + return all_clips, all_masks_enc, all_masks_pred + + clips, masks_enc, masks_pred = load_clips() + data_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 + + if sync_gc and (itr + 1) % GARBAGE_COLLECT_ITR_FREQ == 0: + logger.info("Running garbage collection...") + gc.collect() + + def train_step(): + _new_lr = scheduler.step() + _new_wd = wd_scheduler.step() + # -- + + def forward_target(c): + with torch.no_grad(): + h = target_encoder(c) + h = [F.layer_norm(hi, (hi.size(-1),)) for hi in h] + return h + + def forward_context(c): + z = encoder(c, masks_enc) + z = predictor(z, masks_enc, masks_pred) + return z + + def loss_fn(z, h): + # Assumption: predictor will have returned only masked tokens for z + h = [apply_masks(hi, mi, concat=False) for hi, mi in zip(h, masks_pred)] + + loss, n = 0, 0 + for zi, hi in zip(z, h): + for zij, hij in zip(zi, hi): + loss += torch.mean(torch.abs(zij - hij) ** loss_exp) / loss_exp + n += 1 + loss /= n + return loss + + # Step 1. Forward + with torch.cuda.amp.autocast(dtype=dtype, enabled=mixed_precision): + h = forward_target(clips) + z = forward_context(clips) + loss = loss_fn(z, h) # jepa prediction loss + + # Step 2. Backward & step + if mixed_precision: + scaler.scale(loss).backward() + scaler.unscale_(optimizer) + else: + loss.backward() + if mixed_precision: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + optimizer.zero_grad() + + # Step 3. momentum update of target encoder + m = next(momentum_scheduler) + with torch.no_grad(): + params_k = [] + params_q = [] + for param_q, param_k in zip(encoder.parameters(), target_encoder.parameters()): + params_k.append(param_k) + params_q.append(param_q) + torch._foreach_mul_(params_k, m) + torch._foreach_add_(params_k, params_q, alpha=1 - m) + + return ( + float(loss), + _new_lr, + _new_wd, + ) + + ( + loss, + _new_lr, + _new_wd, + ), gpu_etime_ms = gpu_timer(train_step) + iter_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 + loss_meter.update(loss) + iter_time_meter.update(iter_elapsed_time_ms) + gpu_time_meter.update(gpu_etime_ms) + data_elapsed_time_meter.update(data_elapsed_time_ms) + + # -- Logging + def log_stats(): + csv_logger.log(epoch + 1, itr, loss, iter_elapsed_time_ms, gpu_etime_ms, data_elapsed_time_ms) + if (itr % log_freq == 0) or (itr == ipe - 1) or np.isnan(loss) or np.isinf(loss): + logger.info( + "[%d, %5d] loss: %.3f " + "masks: %s " + "[wd: %.2e] [lr: %.2e] " + "[mem: %.2e] " + "[iter: %.1f ms] " + "[gpu: %.1f ms] " + "[data: %.1f ms]" + % ( + epoch + 1, + itr, + loss_meter.avg, + "[" + ", ".join([f"{k}: " + "%.1f" % mask_meters[k].avg for k in mask_meters]) + "]", + _new_wd, + _new_lr, + torch.cuda.max_memory_allocated() / 1024.0**2, + iter_time_meter.avg, + gpu_time_meter.avg, + data_elapsed_time_meter.avg, + ) + ) + + log_stats() + assert not np.isnan(loss), "loss is nan" + + # -- Save Checkpoint + logger.info("avg. loss %.3f" % loss_meter.avg) + # -- Save Last + if epoch % CHECKPOINT_FREQ == 0 or epoch == (num_epochs - 1): + save_checkpoint(epoch + 1, latest_path) + if save_every_freq > 0 and epoch % save_every_freq == 0: + save_every_file = f"e{epoch}.pt" + save_every_path = os.path.join(folder, save_every_file) + save_checkpoint(epoch + 1, save_every_path) diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa/transforms.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc7d62ce37e87c23c98ab06668de220f4eacf4c --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa/transforms.py @@ -0,0 +1,154 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torchvision.transforms as transforms + +import src.datasets.utils.video.transforms as video_transforms +from src.datasets.utils.video.randerase import RandomErasing + + +def make_transforms( + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), +): + + _frames_augmentation = VideoTransform( + random_horizontal_flip=random_horizontal_flip, + random_resize_aspect_ratio=random_resize_aspect_ratio, + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + crop_size=crop_size, + normalize=normalize, + ) + return _frames_augmentation + + +class VideoTransform(object): + + def __init__( + self, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + ): + + self.random_horizontal_flip = random_horizontal_flip + self.random_resize_aspect_ratio = random_resize_aspect_ratio + self.random_resize_scale = random_resize_scale + self.auto_augment = auto_augment + self.motion_shift = motion_shift + self.crop_size = crop_size + self.mean = torch.tensor(normalize[0], dtype=torch.float32) + self.std = torch.tensor(normalize[1], dtype=torch.float32) + if not self.auto_augment: + # Without auto-augment, PIL and tensor conversions simply scale uint8 space by 255. + self.mean *= 255.0 + self.std *= 255.0 + + self.autoaug_transform = video_transforms.create_random_augment( + input_size=(crop_size, crop_size), + # auto_augment="rand-m4-n4-w1-mstd0.5-inc1", + auto_augment="rand-m7-n4-mstd0.5-inc1", + interpolation="bicubic", + ) + + self.spatial_transform = ( + video_transforms.random_resized_crop_with_shift if motion_shift else video_transforms.random_resized_crop + ) + + self.reprob = reprob + self.erase_transform = RandomErasing( + reprob, + mode="pixel", + max_count=1, + num_splits=1, + device="cpu", + ) + + def __call__(self, buffer): + + if self.auto_augment: + buffer = [transforms.ToPILImage()(frame) for frame in buffer] + buffer = self.autoaug_transform(buffer) + buffer = [transforms.ToTensor()(img) for img in buffer] + buffer = torch.stack(buffer) # T C H W + buffer = buffer.permute(0, 2, 3, 1) # T H W C + elif torch.is_tensor(buffer): + # TODO: ensure input is always a tensor? + buffer = buffer.to(torch.float32) + else: + buffer = torch.tensor(buffer, dtype=torch.float32) + + buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W + + buffer = self.spatial_transform( + images=buffer, + target_height=self.crop_size, + target_width=self.crop_size, + scale=self.random_resize_scale, + ratio=self.random_resize_aspect_ratio, + ) + if self.random_horizontal_flip: + buffer, _ = video_transforms.horizontal_flip(0.5, buffer) + + buffer = _tensor_normalize_inplace(buffer, self.mean, self.std) + if self.reprob > 0: + buffer = buffer.permute(1, 0, 2, 3) + buffer = self.erase_transform(buffer) + buffer = buffer.permute(1, 0, 2, 3) + + return buffer + + +def tensor_normalize(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize. + mean (tensor or list): mean value to subtract. + std (tensor or list): std to divide. + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + tensor = tensor / 255.0 + if isinstance(mean, list): + mean = torch.tensor(mean) + if isinstance(std, list): + std = torch.tensor(std) + tensor = tensor - mean + tensor = tensor / std + return tensor + + +def _tensor_normalize_inplace(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize (with dimensions C, T, H, W). + mean (tensor): mean value to subtract (in 0 to 255 floats). + std (tensor): std to divide (in 0 to 255 floats). + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + + C, T, H, W = tensor.shape + tensor = tensor.view(C, -1).permute(1, 0) # Make C the last dimension + tensor.sub_(mean).div_(std) + tensor = tensor.permute(1, 0).view(C, T, H, W) # Put C back in front + return tensor diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa/utils.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..82e5473a93129873d9d9763f59615a153ebf6196 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa/utils.py @@ -0,0 +1,267 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import sys +import warnings + +import torch +import yaml + +import src.models.predictor as vit_pred +import src.models.vision_transformer as video_vit +from src.utils.checkpoint_loader import robust_checkpoint_loader +from src.utils.schedulers import CosineWDSchedule, LinearDecaySchedule, WarmupCosineSchedule +from src.utils.wrappers import MultiSeqWrapper, PredictorMultiSeqWrapper + +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +logger = logging.getLogger() + +MAX_RETRIES = 3 + + +def build_eval_args( + model_name, + patch_size, + tubelet_size, + num_frames, + logging_folder, + checkpoint, + write_tag, + eval_cfg_paths, + uniform_power=False, + use_sdpa=False, + clip_duration=None, + use_silu=False, + wide_silu=True, + tag=None, +): + """ + Helper function to parse the pre-training configs to construct the + evaluation configs, return as a list of eval configs. + """ + # By convention, the pre-training config should specify any required evals + # in the 'evals' key + if eval_cfg_paths is None: + logger.info("No evaluations specified!") + return + + eval_nodes = None + eval_tasks_per_node = None + args_eval = [] + for i, f in enumerate(eval_cfg_paths): + with open(f, "r") as y_file: + _args = yaml.load(y_file, Loader=yaml.FullLoader) + _tag = _args.get("tag", "") + _args["tag"] = f"{tag}-{_tag}" + _nodes = _args.get("nodes", None) + _tasks = _args.get("tasks_per_node", 8) + eval_nodes = _nodes if eval_nodes is None else eval_nodes + eval_tasks_per_node = _tasks if eval_tasks_per_node is None else eval_tasks_per_node + if (eval_nodes != _nodes) or (eval_tasks_per_node != _tasks): + warnings.warn("Configs for online evals must use same number of nodes for slurm-batch processing") + + # Model params + _args["pretrain"] = {} + _args["pretrain"]["model_name"] = model_name + _args["pretrain"]["patch_size"] = patch_size + _args["pretrain"]["tubelet_size"] = tubelet_size + _args["pretrain"]["uniform_power"] = uniform_power + _args["pretrain"]["use_sdpa"] = use_sdpa + _args["pretrain"]["clip_duration"] = clip_duration + _args["pretrain"]["use_silu"] = use_silu + _args["pretrain"]["wide_silu"] = wide_silu + + # Data params + _args["pretrain"]["frames_per_clip"] = num_frames + + # Misc + _args["pretrain"]["folder"] = logging_folder + _args["pretrain"]["checkpoint"] = checkpoint + _args["pretrain"]["write_tag"] = write_tag + + args_eval += [_args] + + return eval_nodes, eval_tasks_per_node, args_eval + + +def load_checkpoint( + r_path, + encoder, + predictor, + target_encoder, + opt, + scaler, + is_anneal=False, +): + logger.info(f"Loading checkpoint from {r_path}") + checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) + + epoch = 0 + if not is_anneal: + epoch = checkpoint["epoch"] + + # -- loading encoder + pretrained_dict = checkpoint["encoder"] + msg = encoder.load_state_dict(pretrained_dict) + logger.info(f"loaded pretrained encoder from epoch {epoch} with msg: {msg}") + + # -- loading predictor + pretrained_dict = checkpoint["predictor"] + msg = predictor.load_state_dict(pretrained_dict) + logger.info(f"loaded pretrained predictor from epoch {epoch} with msg: {msg}") + + # -- loading target_encoder + if target_encoder is not None: + print(list(checkpoint.keys())) + pretrained_dict = checkpoint["target_encoder"] + msg = target_encoder.load_state_dict(pretrained_dict) + logger.info(f"loaded pretrained target encoder from epoch {epoch} with msg: {msg}") + + # -- loading optimizer + opt.load_state_dict(checkpoint["opt"]) + if scaler is not None: + scaler.load_state_dict(checkpoint["scaler"]) + logger.info(f"loaded optimizers from epoch {epoch}") + logger.info(f"read-path: {r_path}") + del checkpoint + + return ( + encoder, + predictor, + target_encoder, + opt, + scaler, + epoch, + ) + + +def init_video_model( + device, + patch_size=16, + max_num_frames=16, + tubelet_size=2, + model_name="vit_base", + crop_size=224, + pred_depth=6, + pred_num_heads=None, + pred_embed_dim=384, + uniform_power=False, + use_mask_tokens=False, + num_mask_tokens=2, + zero_init_mask_tokens=True, + use_sdpa=False, + use_rope=False, + use_silu=False, + use_pred_silu=False, + wide_silu=False, + use_activation_checkpointing=False, +): + encoder = video_vit.__dict__[model_name]( + img_size=crop_size, + patch_size=patch_size, + num_frames=max_num_frames, + tubelet_size=tubelet_size, + uniform_power=uniform_power, + use_sdpa=use_sdpa, + use_silu=use_silu, + wide_silu=wide_silu, + use_activation_checkpointing=use_activation_checkpointing, + use_rope=use_rope, + ) + encoder = MultiSeqWrapper(encoder) + predictor = vit_pred.__dict__["vit_predictor"]( + img_size=crop_size, + use_mask_tokens=use_mask_tokens, + patch_size=patch_size, + num_frames=max_num_frames, + tubelet_size=tubelet_size, + embed_dim=encoder.backbone.embed_dim, + predictor_embed_dim=pred_embed_dim, + depth=pred_depth, + num_heads=encoder.backbone.num_heads if pred_num_heads is None else pred_num_heads, + uniform_power=uniform_power, + num_mask_tokens=num_mask_tokens, + zero_init_mask_tokens=zero_init_mask_tokens, + use_rope=use_rope, + use_sdpa=use_sdpa, + use_silu=use_pred_silu, + wide_silu=wide_silu, + use_activation_checkpointing=use_activation_checkpointing, + ) + predictor = PredictorMultiSeqWrapper(predictor) + + encoder.to(device) + predictor.to(device) + logger.info(encoder) + logger.info(predictor) + + def count_parameters(model): + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + logger.info(f"Encoder number of parameters: {count_parameters(encoder)}") + logger.info(f"Predictor number of parameters: {count_parameters(predictor)}") + + return encoder, predictor + + +def init_opt( + is_anneal, + encoder, + predictor, + iterations_per_epoch, + start_lr, + ref_lr, + warmup, + num_epochs, + wd=1e-6, + final_wd=1e-6, + final_lr=0.0, + mixed_precision=False, + ipe_scale=1.25, + betas=(0.9, 0.999), + eps=1e-8, + zero_init_bias_wd=True, +): + param_groups = [ + {"params": (p for n, p in encoder.named_parameters() if ("bias" not in n) and (len(p.shape) != 1))}, + {"params": (p for n, p in predictor.named_parameters() if ("bias" not in n) and (len(p.shape) != 1))}, + { + "params": (p for n, p in encoder.named_parameters() if ("bias" in n) or (len(p.shape) == 1)), + "WD_exclude": zero_init_bias_wd, + "weight_decay": 0, + }, + { + "params": (p for n, p in predictor.named_parameters() if ("bias" in n) or (len(p.shape) == 1)), + "WD_exclude": zero_init_bias_wd, + "weight_decay": 0, + }, + ] + + optimizer = torch.optim.AdamW(param_groups, betas=betas, eps=eps) + if not is_anneal: + scheduler = WarmupCosineSchedule( + optimizer, + warmup_steps=int(warmup * iterations_per_epoch), + start_lr=start_lr, + ref_lr=ref_lr, + final_lr=final_lr, + T_max=int(ipe_scale * num_epochs * iterations_per_epoch), + ) + else: + scheduler = LinearDecaySchedule( + optimizer, + ref_lr=ref_lr, + final_lr=final_lr, + T_max=int(ipe_scale * num_epochs * iterations_per_epoch), + ) + wd_scheduler = CosineWDSchedule( + optimizer, + ref_wd=wd, + final_wd=final_wd, + T_max=int(ipe_scale * num_epochs * iterations_per_epoch), + ) + scaler = torch.cuda.amp.GradScaler() if mixed_precision else None + return optimizer, scaler, scheduler, wd_scheduler diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/predictor.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e7f968aac96ddbb3c681eff40b3242f2825548 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/predictor.py @@ -0,0 +1,302 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from functools import partial + +import torch +import torch.nn as nn + +from src.masks.utils import apply_masks +from src.utils.tensors import repeat_interleave_batch, trunc_normal_ + +from app.vjepa_2_1.models.utils.modules import Block + + +class VisionTransformerPredictor(nn.Module): + """Vision Transformer Predictor""" + + def __init__( + self, + img_size=(224, 224), + patch_size=16, + num_frames=1, + tubelet_size=2, + embed_dim=768, + predictor_embed_dim=384, + out_embed_dim=None, + depth=6, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + init_std=0.02, + uniform_power=False, + use_mask_tokens=False, + num_mask_tokens=2, + zero_init_mask_tokens=True, + use_silu=False, + wide_silu=True, + is_causal=False, + use_activation_checkpointing=False, + return_all_tokens=False, + chop_last_n_tokens=0, + use_rope=False, + n_registers=0, + has_cls_first=False, + interpolate_rope=False, + modality_embedding=True, + img_temporal_dim_size=None, + teacher_embed_dim=None, + **kwargs + ): + super().__init__() + self.return_all_tokens = return_all_tokens + self.chop_last_n_tokens = chop_last_n_tokens + self.has_cls_first = has_cls_first + + if depth == 4: + all_hierarchical_layers = [0, 1, 2, 3] + elif depth == 8: + all_hierarchical_layers = [1, 3, 5, 7] + elif depth == 12: + all_hierarchical_layers = [2, 5, 8, 11] + elif depth == 20: + all_hierarchical_layers = [4, 9, 14, 19] + elif depth == 24: + all_hierarchical_layers = [4, 11, 17, 23] + elif depth == 40: + all_hierarchical_layers = [9, 19, 29, 39] + + n_output_distillation = kwargs.get("n_output_distillation", len(all_hierarchical_layers)) + self.hierarchical_layers = all_hierarchical_layers[-n_output_distillation:] + + act_layer_mlp = nn.SiLU if use_silu else nn.GELU + if len(self.hierarchical_layers) == 1: + self.predictor_embed = nn.Linear(embed_dim, predictor_embed_dim, bias=True) + else: + self.predictor_embed = nn.Sequential( + nn.Linear(embed_dim * len(self.hierarchical_layers), embed_dim, bias=True), + act_layer_mlp(), + nn.Linear(embed_dim, predictor_embed_dim, bias=True), + ) + + self.mask_tokens = None + self.num_mask_tokens = 0 + if use_mask_tokens: + self.num_mask_tokens = num_mask_tokens + self.mask_tokens = nn.ParameterList( + [ + nn.Parameter(torch.zeros(1, 1, predictor_embed_dim)) + for i in range(num_mask_tokens) + ] + ) + + if type(img_size) is int: + img_size = (img_size, img_size) + self.img_height, self.img_width = img_size + self.patch_size = patch_size + self.num_frames = num_frames + self.tubelet_size = tubelet_size + self.is_video = num_frames > 1 + + self.grid_height = img_size[0] // self.patch_size + self.grid_width = img_size[1] // self.patch_size + self.grid_depth = num_frames // self.tubelet_size + self.use_activation_checkpointing = use_activation_checkpointing + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] + + if self.is_video: + self.num_patches = ( + (num_frames // tubelet_size) + * (img_size[0] // patch_size) + * (img_size[1] // patch_size) + ) + else: + self.num_patches = (img_size[0] // patch_size) * ( + img_size[1] // patch_size + ) + + self.modality_embedding = False + if img_temporal_dim_size is not None: + if modality_embedding: + self.video_mod_embed = nn.Parameter( + torch.zeros(1, 1, predictor_embed_dim) + ) + nn.init.normal_(self.video_mod_embed, std=1e-6) + self.img_mod_embed = nn.Parameter( + torch.zeros(1, 1, predictor_embed_dim) + ) + nn.init.normal_(self.img_mod_embed, std=1e-6) + self.modality_embedding = True + + self.uniform_power = uniform_power + + self.use_rope = use_rope + self.predictor_blocks = nn.ModuleList( + [ + Block( + use_rope=use_rope, + grid_size=self.grid_height, + grid_depth=self.grid_depth, + dim=predictor_embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=nn.SiLU if use_silu else nn.GELU, + is_causal=is_causal, + wide_silu=wide_silu, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + n_registers=n_registers, + has_cls_first=has_cls_first, + interpolate_rope=interpolate_rope, + patch_size=patch_size, + ) + for i in range(depth) + ] + ) + + if out_embed_dim is None: + if teacher_embed_dim is not None: + out_embed_dim = teacher_embed_dim // len(self.hierarchical_layers) + else: + out_embed_dim = embed_dim + self.predictor_norm = norm_layer(predictor_embed_dim) + self.predictor_proj = nn.Linear( + predictor_embed_dim, + len(self.hierarchical_layers) * out_embed_dim, + bias=True, + ) + if self.return_all_tokens: + self.predictor_proj_context = nn.Linear( + predictor_embed_dim, + out_embed_dim * len(self.hierarchical_layers), + bias=True, + ) + + self.init_std = init_std + if not zero_init_mask_tokens: + for mt in self.mask_tokens: + trunc_normal_(mt, std=init_std) + + self.apply(self._init_weights) + self._rescale_blocks() + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=self.init_std) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + def _rescale_blocks(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.predictor_blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def forward(self, x, masks_x, masks_y, mod="video", mask_index=1): + """ + :param x: context tokens + :param masks_x: indices of context tokens in input + :params masks_y: indices of target tokens in input + """ + assert (masks_x is not None) and ( + masks_y is not None + ), "Cannot run predictor without mask indices" + if not isinstance(masks_x, list): + masks_x = [masks_x] + if not isinstance(masks_y, list): + masks_y = [masks_y] + + B = len(x) // len(masks_x) + + x = self.predictor_embed(x) + _, N_ctxt, D = x.shape + + if not self.use_rope: + x_pos_embed = self.predictor_pos_embed.repeat(B, 1, 1) + x += apply_masks(x_pos_embed, masks_x) + + mask_index = mask_index % self.num_mask_tokens + pred_tokens = self.mask_tokens[mask_index] + pred_tokens = pred_tokens.repeat(B, self.num_patches, 1) + pred_tokens = apply_masks(pred_tokens, masks_y) + + if not self.use_rope: + pos_embs = self.predictor_pos_embed.repeat(B, 1, 1) + pos_embs = apply_masks(pos_embs, masks_y) + pos_embs = repeat_interleave_batch(pos_embs, B, repeat=len(masks_x)) + pred_tokens += pos_embs + + x = x.repeat(len(masks_x), 1, 1) + x = torch.cat([x, pred_tokens], dim=1) + + masks_x = torch.cat(masks_x, dim=0) + masks_y = torch.cat(masks_y, dim=0) + masks = torch.cat([masks_x, masks_y], dim=1) + + argsort = torch.argsort(masks, dim=1) + masks = torch.stack([masks[i, row] for i, row in enumerate(argsort)], dim=0) + x = torch.stack([x[i, row, :] for i, row in enumerate(argsort)], dim=0) + + if self.chop_last_n_tokens > 0: + x = x[:, : -self.chop_last_n_tokens] + masks = masks[:, : -self.chop_last_n_tokens] + + if self.modality_embedding: + if mod == "image": + x += self.img_mod_embed.repeat(B, 1, 1) + else: + x += self.video_mod_embed.repeat(B, 1, 1) + + for i, blk in enumerate(self.predictor_blocks): + if self.use_activation_checkpointing: + x, attn = torch.utils.checkpoint.checkpoint( + blk, x, masks, use_reentrant=False + ) + else: + x, attn = blk(x, mask=masks) + x = self.predictor_norm(x) + + if not self.return_all_tokens: + reverse_argsort = torch.argsort(argsort, dim=1) + x = torch.stack( + [x[i, row, :] for i, row in enumerate(reverse_argsort)], dim=0 + ) + x = x[:, N_ctxt:, :] + x = self.predictor_proj(x) + return x, None + else: + reverse_argsort = torch.argsort(argsort, dim=1) + x = torch.stack( + [x[i, row, :] for i, row in enumerate(reverse_argsort)], dim=0 + ) + x_pred = x[:, N_ctxt:, :] + x_context = x[:, :N_ctxt, :] + x_pred = self.predictor_proj(x_pred) + x_context = self.predictor_proj_context(x_context) + return x_pred, x_context + + +def vit_predictor(**kwargs): + model = VisionTransformerPredictor( + mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6), **kwargs + ) + return model diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/masks_dist.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/masks_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..216f57385b8be3a12d3d47364563afee1e026198 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/masks_dist.py @@ -0,0 +1,77 @@ +import torch +import torch.nn as nn +import torchvision + + +def _get_frame_pos(ids, H_patches=None, W_patches=None, grid_size=None): + if H_patches is None or W_patches is None: + tokens_per_frame = int(grid_size * grid_size) + else: + tokens_per_frame = int(H_patches * W_patches) + return ids // tokens_per_frame + + +def _get_height_pos(ids, H_patches=None, W_patches=None, grid_size=None): + # Remove frame component from ids + if H_patches is None or W_patches is None: + tokens_per_frame = int(grid_size * grid_size) + tokens_per_row = grid_size + else: + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = _get_frame_pos(ids, H_patches, W_patches, grid_size) + ids = ids - tokens_per_frame * frame_ids + # -- + return ids // tokens_per_row + + +def separate_positions(ids, H_patches=None, W_patches=None, grid_size=None): + if H_patches is None or W_patches is None: + tokens_per_frame = int(grid_size * grid_size) + tokens_per_row = grid_size + else: + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = _get_frame_pos(ids, H_patches, W_patches, grid_size) + # -- + height_ids = _get_height_pos(ids, H_patches, W_patches, grid_size) + # -- + # Remove frame component from ids (1st term) and height component (2nd term) + width_ids = (ids - tokens_per_frame * frame_ids) - tokens_per_row * height_ids + return 1.0 * frame_ids, 1.0 * height_ids, 1.0 * width_ids + + +def compute_mask_distance(masks_pred, masks_enc, grid_size, offset_context_loss): + # masks_pred: [fpc][mask] where each mask is [B, N_pred] + # masks_enc: [fpc][mask] where each mask is [B, N_enc] + distances = [] + for masks_pred_i, masks_enc_i in zip(masks_pred, masks_enc): + row_distances = [] + for masks_pred_ij, masks_enc_ij in zip(masks_pred_i, masks_enc_i): + N_enc_tokens = masks_enc_ij.shape[1] + d_enc, h_enc, w_enc = separate_positions( + masks_enc_ij, grid_size=grid_size + ) # (BS, N_enc) + d_pred, h_pred, w_pred = separate_positions( + masks_pred_ij, grid_size=grid_size + ) # (BS, N_pred) + pred = torch.stack([d_pred, h_pred, w_pred], dim=-1) # (BS, N_pred, 3) + enc_distances = [] + for enc_token in range(N_enc_tokens): + enc_position = torch.stack( + [d_enc[:, enc_token], h_enc[:, enc_token], w_enc[:, enc_token]], + dim=-1, + ).unsqueeze( + 1 + ) # (BS, 1, 3) + dist = torch.cdist(enc_position, pred, p=2) # (BS, N_enc) + dmin, argmin = dist.min(dim=-1) + if offset_context_loss: + coeff = grid_size // 16 # Which is the default value of grid_size + dmin = dmin * (1.0 / coeff) + dmin = dmin**0.5 # We want that it decreases less agressive + enc_distances.append(dmin) + enc_distances = torch.stack(enc_distances, dim=-1).squeeze() # (BS, N_enc) + row_distances.append(enc_distances) + distances.append(row_distances) + return distances diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/modules.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..fedf8a2ed6fe3283ca22f65063d43df8340c8405 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/modules.py @@ -0,0 +1,544 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from timm.models.layers import drop_path + + +def rotate_queries_or_keys(x, pos, n_registers, has_cls_first): + B, num_heads, N, D = x.size() + assert ( + D % 2 == 0 + ), "Embedding dimension must be a multiple of 2 for block matrix rotation" + + n_cls = 1 if has_cls_first else 0 + start_ctx = n_cls + end_ctx = N - n_registers + + x_cls = x[..., :n_cls, :] if n_cls else None + x_ctx = x[..., start_ctx:end_ctx, :] + x_reg = x[..., end_ctx:, :] if n_registers > 0 else None + + omega = torch.arange(D // 2, dtype=x.dtype, device=x.device) + omega /= D / 2.0 + omega = 1.0 / 10000**omega + freq = torch.einsum("..., f -> ... f", pos, omega) + + emb_sin = freq.sin() + emb_cos = freq.cos() + + emb_sin = emb_sin.repeat_interleave(2, dim=-1) + emb_cos = emb_cos.repeat_interleave(2, dim=-1) + + y = x_ctx.unflatten(-1, (-1, 2)) + y1, y2 = y.unbind(dim=-1) + y = torch.stack((-y2, y1), dim=-1) + y = y.flatten(-2) + + out_ctx = (x_ctx * emb_cos) + (y * emb_sin) + + parts = [] + if n_cls: + parts.append(x_cls) + parts.append(out_ctx) + if n_registers: + parts.append(x_reg) + out = torch.cat(parts, dim=-2) + + return out + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + def extra_repr(self) -> str: + return "p={}".format(self.drop_prob) + + +class MLP(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.0, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class SwiGLUFFN(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.SiLU, + drop=0.0, + wide_silu=True, + ): + super().__init__() + out_features = out_features or in_features + swiglu_hidden_features = hidden_features = hidden_features or in_features + if wide_silu: + swiglu_hidden_features = int(2 * hidden_features / 3) + align_as = 8 + swiglu_hidden_features = ( + (swiglu_hidden_features + align_as - 1) // align_as * align_as + ) + self.fc1 = nn.Linear(in_features, swiglu_hidden_features) + self.fc2 = nn.Linear(in_features, swiglu_hidden_features) + self.act = act_layer() + self.fc3 = nn.Linear(swiglu_hidden_features, out_features) + + def forward(self, x): + x1 = self.fc1(x) + x2 = self.fc2(x) + hidden = F.silu(x1) * x2 + return self.fc3(hidden) + + +class RoPEAttention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + use_sdpa=True, + grid_size=14, + is_causal=False, + n_registers=0, + has_cls_first=False, + interpolate_rope=False, + patch_size=16, + ): + super().__init__() + self.num_heads = num_heads + self.head_dim = head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop_prob = proj_drop + self.proj_drop = nn.Dropout(proj_drop) + self.use_sdpa = use_sdpa + self.d_dim = int(2 * ((head_dim // 3) // 2)) + self.h_dim = int(2 * ((head_dim // 3) // 2)) + self.w_dim = int(2 * ((head_dim // 3) // 2)) + self.grid_size = grid_size + self.is_causal = is_causal + self.n_registers = n_registers + self.has_cls_first = has_cls_first + self.interpolate_rope = interpolate_rope + self.pretrained_patch_size = patch_size + if patch_size == 14: + self.pretrained_grid_size = int(252 / patch_size) + elif patch_size == 16: + self.pretrained_grid_size = int(256 / patch_size) + + def _get_frame_pos(self, ids, H_patches=None, W_patches=None): + if H_patches is None or W_patches is None: + tokens_per_frame = int(self.grid_size * self.grid_size) + else: + tokens_per_frame = int(H_patches * W_patches) + return ids // tokens_per_frame + + def _get_height_pos(self, ids, H_patches=None, W_patches=None): + if H_patches is None or W_patches is None: + tokens_per_frame = int(self.grid_size * self.grid_size) + tokens_per_row = self.grid_size + else: + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = self._get_frame_pos(ids, H_patches, W_patches) + ids = ids - tokens_per_frame * frame_ids + return ids // tokens_per_row + + def separate_positions(self, ids, H_patches=None, W_patches=None): + if H_patches is None or W_patches is None: + tokens_per_frame = int(self.grid_size * self.grid_size) + tokens_per_row = self.grid_size + else: + tokens_per_frame = int(H_patches * W_patches) + tokens_per_row = W_patches + frame_ids = self._get_frame_pos(ids, H_patches, W_patches) + height_ids = self._get_height_pos(ids, H_patches, W_patches) + width_ids = (ids - tokens_per_frame * frame_ids) - tokens_per_row * height_ids + return 1.0 * frame_ids, 1.0 * height_ids, 1.0 * width_ids + + def forward( + self, + x, + mask=None, + T=None, + H_patches=None, + W_patches=None, + return_attn=False, + ): + B, N, C = x.size() + N_ctx = N - self.n_registers + grid_depth = int(N_ctx // (self.grid_size * self.grid_size)) + + qkv = self.qkv(x).unflatten(-1, (3, self.num_heads, -1)).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + + if mask is not None: + mask = mask.unsqueeze(1).repeat(1, self.num_heads, 1) + d_mask, h_mask, w_mask = self.separate_positions(mask, H_patches, W_patches) + else: + if T is None or H_patches is None or W_patches is None: + mask = torch.arange( + int(grid_depth * self.grid_size * self.grid_size), device=x.device + ) + else: + mask = torch.arange(int(T * H_patches * W_patches), device=x.device) + d_mask, h_mask, w_mask = self.separate_positions(mask, H_patches, W_patches) + + if self.interpolate_rope: + if H_patches is None: + H_patches = int(self.grid_size) + if W_patches is None: + W_patches = int(self.grid_size) + h_mask = h_mask * (self.pretrained_grid_size - 1) / (H_patches - 1) + w_mask = w_mask * (self.pretrained_grid_size - 1) / (W_patches - 1) + + s = 0 + qd = rotate_queries_or_keys( + q[..., s : s + self.d_dim], + pos=d_mask, + n_registers=self.n_registers, + has_cls_first=self.has_cls_first, + ) + kd = rotate_queries_or_keys( + k[..., s : s + self.d_dim], + pos=d_mask, + n_registers=self.n_registers, + has_cls_first=self.has_cls_first, + ) + s += self.d_dim + qh = rotate_queries_or_keys( + q[..., s : s + self.h_dim], + pos=h_mask, + n_registers=self.n_registers, + has_cls_first=self.has_cls_first, + ) + kh = rotate_queries_or_keys( + k[..., s : s + self.h_dim], + pos=h_mask, + n_registers=self.n_registers, + has_cls_first=self.has_cls_first, + ) + s += self.h_dim + qw = rotate_queries_or_keys( + q[..., s : s + self.w_dim], + pos=w_mask, + n_registers=self.n_registers, + has_cls_first=self.has_cls_first, + ) + kw = rotate_queries_or_keys( + k[..., s : s + self.w_dim], + pos=w_mask, + n_registers=self.n_registers, + has_cls_first=self.has_cls_first, + ) + s += self.w_dim + + if s < self.head_dim: + qr = q[..., s:] + kr = k[..., s:] + q = torch.cat([qd, qh, qw, qr], dim=-1) + k = torch.cat([kd, kh, kw, kr], dim=-1) + else: + q = torch.cat([qd, qh, qw], dim=-1) + k = torch.cat([kd, kh, kw], dim=-1) + + if self.use_sdpa: + with torch.backends.cuda.sdp_kernel(): + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal + ) + attn = None + else: + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + if return_attn: + return x, attn + else: + return x, None + + +class Attention(nn.Module): + def __init__( + self, + dim, + num_heads=8, + qkv_bias=False, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + use_sdpa=True, + is_causal=False, + ): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop_prob = proj_drop + self.proj_drop = nn.Dropout(proj_drop) + self.use_sdpa = use_sdpa + self.is_causal = is_causal + + def forward(self, x): + B, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B, N, 3, self.num_heads, C // self.num_heads) + .permute(2, 0, 3, 1, 4) + ) + q, k, v = qkv[0], qkv[1], qkv[2] + + if self.use_sdpa: + with torch.backends.cuda.sdp_kernel(): + x = F.scaled_dot_product_attention( + q, k, v, dropout_p=self.proj_drop_prob, is_causal=self.is_causal + ) + attn = None + else: + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + attn = self.attn_drop(attn) + x = attn @ v + x = x.transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Module): + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + wide_silu=True, + norm_layer=nn.LayerNorm, + use_sdpa=True, + is_causal=False, + grid_size=16, + use_rope=False, + n_registers=0, + has_cls_first=False, + interpolate_rope=False, + patch_size=16, + **kwargs, + ): + super().__init__() + self.norm1 = norm_layer(dim) + self.use_rope = use_rope + if use_rope: + self.attn = RoPEAttention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + use_sdpa=use_sdpa, + is_causal=is_causal, + grid_size=grid_size, + proj_drop=drop, + n_registers=n_registers, + has_cls_first=has_cls_first, + interpolate_rope=interpolate_rope, + patch_size=patch_size, + ) + else: + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + use_sdpa=use_sdpa, + is_causal=is_causal, + proj_drop=drop, + ) + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + if act_layer is nn.SiLU: + self.mlp = SwiGLUFFN( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + wide_silu=wide_silu, + drop=drop, + ) + else: + self.mlp = MLP( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + ) + + def forward( + self, + x, + mask=None, + T=None, + H_patches=None, + W_patches=None, + return_attn=False, + mode="video", + ): + if self.use_rope: + y, attn = self.attn( + self.norm1(x), + mask=mask, + T=T, + H_patches=H_patches, + W_patches=W_patches, + return_attn=return_attn, + ) + else: + y = self.attn(self.norm1(x)) + attn = None + x = x + self.drop_path(y) + x = x + self.drop_path(self.mlp(self.norm2(x))) + if return_attn: + return x, attn + else: + return x, None + + +class CrossAttention(nn.Module): + def __init__(self, dim, num_heads=12, qkv_bias=False, use_sdpa=True): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + self.q = nn.Linear(dim, dim, bias=qkv_bias) + self.kv = nn.Linear(dim, int(dim * 2), bias=qkv_bias) + self.use_sdpa = use_sdpa + + def forward(self, q, x): + B, n, C = q.shape + q = ( + self.q(q) + .reshape(B, n, self.num_heads, C // self.num_heads) + .permute(0, 2, 1, 3) + ) + + B, N, C = x.shape + kv = ( + self.kv(x) + .reshape(B, N, 2, self.num_heads, C // self.num_heads) + .permute(2, 0, 3, 1, 4) + ) + k, v = kv[0], kv[1] + + if self.use_sdpa: + with torch.backends.cuda.sdp_kernel(): + q = F.scaled_dot_product_attention(q, k, v) + else: + xattn = (q @ k.transpose(-2, -1)) * self.scale + xattn = xattn.softmax(dim=-1) + q = xattn @ v + + q = q.transpose(1, 2).reshape(B, n, C) + return q + + +class CrossAttentionBlock(nn.Module): + def __init__( + self, + dim, + num_heads, + mlp_ratio=4.0, + qkv_bias=False, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + ): + super().__init__() + self.norm1 = norm_layer(dim) + self.xattn = CrossAttention(dim, num_heads=num_heads, qkv_bias=qkv_bias) + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = MLP( + in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer + ) + + def forward(self, q, x): + y = self.xattn(q, self.norm1(x)) + q = q + y + q = q + self.mlp(self.norm2(q)) + return q + + +class Lambda_LinearWarmupHold: + """ + Linear warmup from 0 to lambda_value between [start_iter, end_iter], + 0 before start_iter and constant (=lambda_value) from end_iter onwards. + """ + + def __init__( + self, lambda_value: float, start_iter: int = 15_000, end_iter: int = 30_000 + ): + assert end_iter > start_iter, "end_iter must be > start_iter" + self.lambda_value = float(lambda_value) + self.start = int(start_iter) + self.end = int(end_iter) + self.span = self.end - self.start + + def value(self, global_iter: int) -> float: + if global_iter < self.start: + return 0.0 + if global_iter >= self.end: + return self.lambda_value + alpha = (global_iter - self.start) / self.span + return self.lambda_value * alpha diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/patch_embed.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc34352d31e2cdcded8632216ada087660683a5 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/patch_embed.py @@ -0,0 +1,72 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# + +from einops import rearrange + +import torch.nn as nn + + +class AudioPatchEmbed(nn.Module): + """ + Audio to Patch Embedding + """ + + def __init__(self, freq_bands=128, tubelet_size=2, embed_dim=768): + super().__init__() + self.freq_bands = freq_bands + self.tubelet_size = tubelet_size + self.proj = nn.Conv2d(1, embed_dim, kernel_size=(freq_bands, tubelet_size), stride=(freq_bands, tubelet_size)) + + def forward(self, x): + x = rearrange(x, "b t c f -> b c f t") + x = self.proj(x).flatten(2).transpose(1, 2) + return x + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding + """ + + def __init__(self, patch_size=16, in_chans=3, embed_dim=768): + super().__init__() + self.patch_size = patch_size + self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) + + def forward(self, x): + B, C, H, W = x.shape + x = self.proj(x).flatten(2).transpose(1, 2) + return x + + +class PatchEmbed3D(nn.Module): + """ + Image to Patch Embedding + """ + + def __init__( + self, + patch_size=16, + tubelet_size=2, + in_chans=3, + embed_dim=768, + ): + super().__init__() + self.patch_size = patch_size + self.tubelet_size = tubelet_size + + self.proj = nn.Conv3d( + in_channels=in_chans, + out_channels=embed_dim, + kernel_size=(tubelet_size, patch_size, patch_size), + stride=(tubelet_size, patch_size, patch_size), + ) + + def forward(self, x, **kwargs): + B, C, T, H, W = x.shape + x = self.proj(x).flatten(2).transpose(1, 2) + return x diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/pos_embs.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/pos_embs.py new file mode 100644 index 0000000000000000000000000000000000000000..85036dd31af9ddfdf059cddaed1afea360bf2ff5 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/utils/pos_embs.py @@ -0,0 +1,95 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# + +import numpy as np + + +def get_3d_sincos_pos_embed(embed_dim, grid_size, grid_depth, cls_token=False, uniform_power=False): + """ + grid_size: int of the grid height and width + grid_depth: int of the grid depth + returns: + pos_embed: [grid_depth*grid_size*grid_size, embed_dim] (w/o cls_token) + or [1+grid_depth*grid_size*grid_size, embed_dim] (w/ cls_token) + """ + grid_d = np.arange(grid_depth, dtype=float) + grid_h = np.arange(grid_size, dtype=float) + grid_w = np.arange(grid_size, dtype=float) + grid_h, grid_d, grid_w = np.meshgrid( + grid_h, grid_d, grid_w + ) # order of meshgrid is very important for indexing as [d,h,w] + + if not uniform_power: + h_embed_dim = embed_dim // 4 + w_embed_dim = embed_dim // 4 + d_embed_dim = embed_dim // 2 + else: + h_embed_dim = w_embed_dim = d_embed_dim = int(np.ceil(embed_dim / 6) * 2) + + emb_h = get_1d_sincos_pos_embed_from_grid(h_embed_dim, grid_h) # (T*H*W, D1) + emb_w = get_1d_sincos_pos_embed_from_grid(w_embed_dim, grid_w) # (T*H*W, D2) + emb_d = get_1d_sincos_pos_embed_from_grid(d_embed_dim, grid_d) # (T*H*W, D3) + pos_embed = np.concatenate([emb_d, emb_h, emb_w], axis=1) + pos_embed = pos_embed[:, :embed_dim] + if cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False): + """ + grid_size: int of the grid height and width + returns: + pos_embed: [grid_size*grid_size, embed_dim] (w/o cls_token) + or [1+grid_size*grid_size, embed_dim] (w/ cls_token) + """ + grid_h = np.arange(grid_size, dtype=float) + grid_w = np.arange(grid_size, dtype=float) + grid_w, grid_h = np.meshgrid(grid_w, grid_h) # order of meshgrid is very important for indexing as [h, w] + + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid_h) # (H*W, D/2) + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid_w) # (H*W, D/2) + pos_embed = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D) + if cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +def get_1d_sincos_pos_embed(embed_dim, grid_size, cls_token=False): + """ + embed_dim: output dimension for each position + grid_size: int of the grid length + returns: + pos_embed: [grid_size, embed_dim] (w/o cls_token) + or [1+grid_size, embed_dim] (w/ cls_token) + """ + grid = np.arange(grid_size, dtype=float) + pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid) + if cls_token: + pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0) + return pos_embed + + +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,) + returns: (M, D) + """ + assert embed_dim % 2 == 0 + omega = np.arange(embed_dim // 2, dtype=float) + omega /= embed_dim / 2.0 + omega = 1.0 / 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 diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/vision_transformer.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..c8797fbb50d98c2ac2ed239267f9399a8bbb7071 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/models/vision_transformer.py @@ -0,0 +1,608 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from functools import partial + +import torch +import torch.nn as nn + +from src.masks.utils import apply_masks +from src.utils.tensors import trunc_normal_ + +from app.vjepa_2_1.models.utils.modules import Block +from app.vjepa_2_1.models.utils.patch_embed import PatchEmbed, PatchEmbed3D + + +class VisionTransformer(nn.Module): + """Vision Transformer""" + + def __init__( + self, + img_size=(224, 224), + patch_size=16, + num_frames=1, + tubelet_size=2, + in_chans=3, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + norm_layer=nn.LayerNorm, + init_std=0.02, + out_layers=None, + uniform_power=False, + use_silu=False, + wide_silu=True, + use_sdpa=True, + use_activation_checkpointing=False, + is_causal=False, + use_rope=False, + init_type: str = "default", + handle_nonsquare_inputs=True, + img_temporal_dim_size=None, + n_registers=0, + has_cls_first=False, + interpolate_rope=False, + modality_embedding=True, + n_output_distillation=4, + **kwargs, + ): + super().__init__() + self.num_features = self.embed_dim = embed_dim + self.num_heads = num_heads + self.out_layers = out_layers + self.init_type = init_type + self.handle_nonsquare_inputs = handle_nonsquare_inputs + self.img_temporal_dim_size = img_temporal_dim_size + + if type(img_size) is int: + img_size = (img_size, img_size) + self.img_height, self.img_width = img_size + self.patch_size = patch_size + self.num_frames = num_frames + self.tubelet_size = tubelet_size + self.is_video = num_frames > 1 + + self.use_activation_checkpointing = use_activation_checkpointing + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] + + if self.is_video: + self.patch_embed = PatchEmbed3D( + patch_size=patch_size, + tubelet_size=tubelet_size, + in_chans=in_chans, + embed_dim=embed_dim, + ) + self.num_patches = ( + (num_frames // tubelet_size) + * (img_size[0] // patch_size) + * (img_size[1] // patch_size) + ) + else: + self.patch_embed = PatchEmbed( + patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim + ) + self.num_patches = (img_size[0] // patch_size) * (img_size[1] // patch_size) + + if self.img_temporal_dim_size is not None: + if not isinstance(self.img_temporal_dim_size, int): + raise ValueError( + f"img_temporal_dim_size must be an int, got {self.img_temporal_dim_size}" + ) + self.patch_embed_img = PatchEmbed3D( + patch_size=patch_size, + tubelet_size=1, + in_chans=in_chans, + embed_dim=embed_dim, + ) + else: + self.patch_embed_img = None + + self.uniform_power = uniform_power + + self.use_rope = use_rope + self.blocks = nn.ModuleList( + [ + Block( + use_rope=use_rope, + grid_size=img_size[0] // patch_size, + grid_depth=num_frames // tubelet_size, + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + use_sdpa=use_sdpa, + is_causal=is_causal, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=nn.SiLU if use_silu else nn.GELU, + wide_silu=wide_silu, + attn_drop=attn_drop_rate, + drop_path=dpr[i], + norm_layer=norm_layer, + n_registers=n_registers, + has_cls_first=has_cls_first, + interpolate_rope=interpolate_rope, + patch_size=patch_size, + ) + for i in range(depth) + ] + ) + + self.attn_out = False + self.init_std = init_std + self.apply(self._init_weights) + self._rescale_blocks() + + if depth == 12: + self.hierarchical_layers = [2, 5, 8, 11] + if n_output_distillation == 4: + self.out_layers_distillation = [2, 5, 8, 11] + elif n_output_distillation == 1: + self.out_layers_distillation = [11] + + elif depth == 24: + self.hierarchical_layers = [5, 11, 17, 23] + if n_output_distillation == 4: + self.out_layers_distillation = [5, 11, 17, 23] + elif n_output_distillation == 1: + self.out_layers_distillation = [23] + + elif depth == 40: + self.hierarchical_layers = [9, 19, 29, 39] + if n_output_distillation == 4: + self.out_layers_distillation = [9, 19, 29, 39] + elif n_output_distillation == 1: + self.out_layers_distillation = [39] + + elif depth == 48: + self.hierarchical_layers = [11, 23, 37, 47] + if n_output_distillation == 4: + self.out_layers_distillation = [11, 23, 37, 47] + elif n_output_distillation == 1: + self.out_layers_distillation = [47] + else: + print("Check the code! ;)") + self.norms_block = nn.ModuleList( + [norm_layer(embed_dim) for _ in range(len(self.hierarchical_layers))] + ) + + self.cls_token = None + self.return_hierarchical = False + + self.modality_embedding = False + if modality_embedding: + self.img_mod_embed = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.video_mod_embed = nn.Parameter(torch.zeros(1, 1, embed_dim)) + nn.init.normal_(self.img_mod_embed, std=1e-6) + nn.init.normal_(self.video_mod_embed, std=1e-6) + self.modality_embedding = True + + def _init_weights(self, m): + if isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + return + if self.init_type == "default": + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=self.init_std) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv2d): + trunc_normal_(m.weight, std=self.init_std) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Conv3d): + trunc_normal_(m.weight, std=self.init_std) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + elif self.init_type == "xavier_uniform": + if ( + isinstance(m, nn.Linear) + or isinstance(m, nn.Conv2d) + or isinstance(m, nn.Conv3d) + ): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif self.init_type == "xavier_normal": + if ( + isinstance(m, nn.Linear) + or isinstance(m, nn.Conv2d) + or isinstance(m, nn.Conv3d) + ): + nn.init.xavier_normal_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + else: + raise ValueError(f"Unknown init type {self.init_type}") + + def _rescale_blocks(self): + def rescale(param, layer_id): + param.div_(math.sqrt(2.0 * layer_id)) + + for layer_id, layer in enumerate(self.blocks): + rescale(layer.attn.proj.weight.data, layer_id + 1) + rescale(layer.mlp.fc2.weight.data, layer_id + 1) + + def get_num_layers(self): + return len(self.blocks) + + def no_weight_decay(self): + return {} + + def check_temporal_dim(self, shape) -> bool: + if self.img_temporal_dim_size is not None: + if shape[2] == self.img_temporal_dim_size: + return True + + return False + + def forward(self, x, masks=None, training=False): + """ + :param x: input image/video + :param masks: indices of patch tokens to mask (remove) + """ + if masks is not None and not isinstance(masks, list): + masks = [masks] + + if x.ndim == 4: + _, _, H, W = x.shape + T = 1 + elif x.ndim == 5: + _, _, T, H, W = x.shape + if self.check_temporal_dim(x.shape): + T = T // 1 + else: + T = T // self.tubelet_size + + H_patches = H // self.patch_size + W_patches = W // self.patch_size + if not self.handle_nonsquare_inputs: + T = H_patches = W_patches = None + + if not self.use_rope: + pos_embed = self.interpolate_pos_encoding(x, self.pos_embed) + + if self.check_temporal_dim(x.shape): + assert self.patch_embed_img is not None + x = self.patch_embed_img(x) + mode = "img" + if self.modality_embedding: + x += self.img_mod_embed.repeat(x.shape[0], 1, 1) + else: + x = self.patch_embed(x) + mode = "video" + if self.modality_embedding: + x += self.video_mod_embed.repeat(x.shape[0], 1, 1) + + if not self.use_rope: + x += pos_embed + + if masks is not None: + x = apply_masks(x, masks) + masks = torch.cat(masks, dim=0) + + outs = [] + hier = [] + for i, blk in enumerate(self.blocks): + if self.use_activation_checkpointing: + x, attn = torch.utils.checkpoint.checkpoint( + blk, + x, + masks, + T=T, + H_patches=H_patches, + W_patches=W_patches, + use_reentrant=False, + return_attn=self.attn_out, + mode=mode, + ) + else: + x, attn = blk( + x, + mask=masks, + T=T, + H_patches=H_patches, + W_patches=W_patches, + return_attn=self.attn_out, + mode=mode, + ) + + if self.out_layers is not None and i in self.out_layers: + out_idx = self.hierarchical_layers.index(i) + out_norm = self.norms_block[out_idx](x) + outs.append(out_norm) + + if i in self.out_layers_distillation: + out_idx = self.hierarchical_layers.index(i) + hier.append(self.norms_block[out_idx](x)) + + if self.out_layers is not None: + return outs + + if training or self.return_hierarchical: + hier = torch.cat(hier, dim=2) + return hier + else: + x = self.norms_block[-1](x) + return x + + def interpolate_pos_encoding(self, x, pos_embed): + + _, N, dim = pos_embed.shape + + if self.is_video: + + _, _, T, H, W = x.shape + if H == self.img_height and W == self.img_width and T == self.num_frames: + return pos_embed + + elif H == self.img_height and W == self.img_width and T < self.num_frames: + new_N = int( + (T // self.tubelet_size) + * (H // self.patch_size) + * (W // self.patch_size) + ) + return pos_embed[:, :new_N, :] + + T = T // self.tubelet_size + H = H // self.patch_size + W = W // self.patch_size + + N_t = self.num_frames // self.tubelet_size + N_h = self.img_height // self.patch_size + N_w = self.img_width // self.patch_size + assert N_h * N_w * N_t == N, "Positional embedding initialized incorrectly" + + scale_factor = (T / N_t, H / N_h, W / N_w) + + pos_embed = nn.functional.interpolate( + pos_embed.reshape(1, N_t, N_h, N_w, dim).permute(0, 4, 1, 2, 3), + scale_factor=scale_factor, + mode="trilinear", + ) + pos_embed = pos_embed.permute(0, 2, 3, 4, 1).view(1, -1, dim) + return pos_embed + + else: + + _, _, H, W = x.shape + if H == self.img_height and W == self.img_width: + return pos_embed + + npatch = (H // self.patch_size) * (W // self.patch_size) + scale_factor = math.sqrt(npatch / N) + + pos_embed = nn.functional.interpolate( + pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute( + 0, 3, 1, 2 + ), + scale_factor=scale_factor, + mode="bicubic", + ) + pos_embed = pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return pos_embed + + +def vit_synthetic(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1, + depth=1, + num_heads=1, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_tiny(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=192, + depth=12, + num_heads=3, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_small(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=384, + depth=12, + num_heads=6, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_base(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_large(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_large_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_huge(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1280, + depth=32, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_huge_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1280, + depth=32, + num_heads=16, + mlp_ratio=4, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_giant(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=16, + mlp_ratio=48 / 11, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_giant_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=16, + mlp_ratio=48 / 11, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_giant_xformers(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=22, + mlp_ratio=48 / 11, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_giant_xformers_rope(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1408, + depth=40, + num_heads=22, + mlp_ratio=48 / 11, + qkv_bias=True, + use_rope=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_gigantic(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1664, + depth=48, + num_heads=16, + mlp_ratio=64 / 13, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +def vit_gigantic_xformers(patch_size=16, **kwargs): + model = VisionTransformer( + patch_size=patch_size, + embed_dim=1664, + depth=48, + num_heads=26, + mlp_ratio=64 / 13, + qkv_bias=True, + norm_layer=partial(nn.LayerNorm, eps=1e-6), + **kwargs, + ) + return model + + +VIT_EMBED_DIMS = { + "vit_synthetic": 1, + "vit_tiny": 192, + "vit_small": 384, + "vit_base": 768, + "vit_large": 1024, + "vit_huge": 1280, + "vit_giant": 1408, + "vit_gigantic": 1664, +} diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/train.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/train.py new file mode 100644 index 0000000000000000000000000000000000000000..f8fe59499e7e7a8ef64621242537e69b1e7e5d50 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/train.py @@ -0,0 +1,835 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import os + +# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESS +try: + os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"] +except Exception: + pass + +import copy +import gc +import random +import time + +import numpy as np +import torch +import torch.multiprocessing as mp +import torch.nn.functional as F +from app.vjepa_2_1.models.utils.masks_dist import compute_mask_distance +from app.vjepa_2_1.models.utils.modules import Lambda_LinearWarmupHold +from app.vjepa_2_1.transforms import make_transforms +from app.vjepa_2_1.utils import ( + init_opt, + init_video_model, + load_checkpoint, + normalize_nested, +) +from src.datasets.data_manager import init_data +from src.masks.multiseq_multiblock3d import MaskCollator +from src.masks.utils import apply_masks +from src.utils.distributed import init_distributed +from src.utils.logging import AverageMeter, CSVLogger, get_logger, gpu_timer +from torch.nn.parallel import DistributedDataParallel + + +log_timings = True +log_freq = 10 +CHECKPOINT_FREQ = 1 +GARBAGE_COLLECT_ITR_FREQ = 50 +MAX_REPEAT_COUNTS = 10 + +_GLOBAL_SEED = 0 +random.seed(_GLOBAL_SEED) +np.random.seed(_GLOBAL_SEED) +torch.manual_seed(_GLOBAL_SEED) +torch.backends.cudnn.benchmark = True + + +logger = get_logger(__name__, force=True) + + +def main(args, resume_preempt=False): + # ----------------------------------------------------------------------- # + # PASSED IN PARAMS FROM CONFIG FILE + # ----------------------------------------------------------------------- # + + # -- META + folder = args.get("folder") + cfgs_meta = args.get("meta") + load_model = cfgs_meta.get("load_checkpoint") or resume_preempt + r_file = cfgs_meta.get("read_checkpoint", None) + seed = cfgs_meta.get("seed", _GLOBAL_SEED) + save_every_freq = cfgs_meta.get("save_every_freq", -1) + skip_batches = cfgs_meta.get("skip_batches", -1) + use_sdpa = cfgs_meta.get("use_sdpa", False) + sync_gc = cfgs_meta.get("sync_gc", False) + logger.info(f"LD_PRELOAD: {os.environ.get('LD_PRELOAD')}") + which_dtype = cfgs_meta.get("dtype") + logger.info(f"{which_dtype=}") + if which_dtype.lower() == "bfloat16": + dtype = torch.bfloat16 + mixed_precision = True + elif which_dtype.lower() == "float16": + dtype = torch.float16 + mixed_precision = True + else: + dtype = torch.float32 + mixed_precision = False + + # -- MASK + cfgs_mask = args.get("mask") + + # -- MODEL + cfgs_model = args.get("model") + compile_model = cfgs_model.get("compile_model", False) + use_activation_checkpointing = cfgs_model.get("use_activation_checkpointing", False) + model_name = cfgs_model.get("model_name") + pred_depth = cfgs_model.get("pred_depth") + pred_num_heads = cfgs_model.get("pred_num_heads", None) + pred_embed_dim = cfgs_model.get("pred_embed_dim") + uniform_power = cfgs_model.get("uniform_power", False) + use_mask_tokens = cfgs_model.get("use_mask_tokens", False) + zero_init_mask_tokens = cfgs_model.get("zero_init_mask_tokens", True) + use_rope = cfgs_model.get("use_rope", False) + use_silu = cfgs_model.get("use_silu", False) + use_pred_silu = cfgs_model.get("use_pred_silu", False) + wide_silu = cfgs_model.get("wide_silu", True) + is_causal = cfgs_model.get("is_causal", False) + pred_is_causal = cfgs_model.get("pred_is_causal", False) + init_type = cfgs_model.get("init_type", "default") + img_temporal_dim_size = cfgs_model.get("img_temporal_dim_size", None) + n_registers = cfgs_model.get("n_registers", 0) + has_cls_first = cfgs_model.get("has_cls_first", False) + interpolate_rope = cfgs_model.get("interpolate_rope", False) + lambda_value_img = cfgs_model.get("lambda_value_img", 0.0) + lambda_value_vid = cfgs_model.get("lambda_value_vid", 0.0) + n_registers_predictor = cfgs_model.get("n_registers_predictor", 0) + lambda_progressive = cfgs_model.get("lambda_progressive", True) + normalize_predictor = cfgs_model.get("normalize_predictor", False) + modality_embedding = cfgs_model.get("modality_embedding", False) + levels_predictor = cfgs_model.get("levels_predictor", 4) + if model_name == "vit_large": + embed_dim_encoder = 1024 + elif model_name == "vit_giant_xformers": + embed_dim_encoder = 1408 + elif model_name == "vit_gigantic_xformers": + embed_dim_encoder = 1664 + else: + print("Model name not recognized :(") + + # -- DATA + cfgs_data = args.get("data") + dataset_type = cfgs_data.get("dataset_type", "videodataset") + dataset_paths = cfgs_data.get("datasets", []) + datasets_weights = cfgs_data.get("datasets_weights") + dataset_fpcs = cfgs_data.get("dataset_fpcs") + max_num_frames = max(dataset_fpcs) + batch_size = cfgs_data.get("batch_size") + tubelet_size = cfgs_data.get("tubelet_size") + fps = cfgs_data.get("fps") + crop_size = cfgs_data.get("crop_size", 224) + patch_size = cfgs_data.get("patch_size") + grid_size = crop_size // patch_size + pin_mem = cfgs_data.get("pin_mem", False) + num_workers = cfgs_data.get("num_workers", 1) + + # -- IMG DATA + cfgs_img_data = args.get("img_data") + img_rank_ratio = 0.25 + img_mask = None + if cfgs_img_data is not None: + img_dataset_type = cfgs_img_data.get("dataset_type", "imagenet") + img_dataset_paths = cfgs_img_data.get("datasets", []) + img_dataset_weights = cfgs_img_data.get("datasets_weights", []) + img_dataset_fpcs = cfgs_img_data.get("dataset_fpcs") + img_dataset_batch_size = cfgs_img_data.get("batch_size") + img_rank_ratio = cfgs_img_data.get("rank_ratio", img_rank_ratio) + img_num_workers = cfgs_img_data.get("num_workers", num_workers) + + img_mask = args.get("img_mask", img_mask) + + # -- DATA AUGS + cfgs_data_aug = args.get("data_aug") + ar_range = cfgs_data_aug.get("random_resize_aspect_ratio", [3 / 4, 4 / 3]) + rr_scale = cfgs_data_aug.get("random_resize_scale", [0.3, 1.0]) + motion_shift = cfgs_data_aug.get("motion_shift", False) + reprob = cfgs_data_aug.get("reprob", 0.0) + use_aa = cfgs_data_aug.get("auto_augment", False) + + # -- LOSS + cfgs_loss = args.get("loss") + loss_exp = cfgs_loss.get("loss_exp") + shift_by_n = cfgs_loss.get("shift_by_n") + predict_all = cfgs_loss.get("predict_all", True) + weight_distance_loss = cfgs_loss.get("weight_distance_loss", False) + offset_context_loss = cfgs_loss.get("offset_context_loss", False) + + # -- OPTIMIZATION + cfgs_opt = args.get("optimization") + is_anneal = cfgs_opt.get("is_anneal", False) + anneal_ckpt = cfgs_opt.get("anneal_ckpt", None) + if is_anneal and anneal_ckpt is None: + raise ValueError("Must specify anneal_ckpt if is_anneal is True") + resume_anneal = cfgs_opt.get("resume_anneal", False) or ( + is_anneal and resume_preempt + ) + ipe = cfgs_opt.get("ipe", None) + ipe_scale = cfgs_opt.get("ipe_scale", 1.0) + wd = float(cfgs_opt.get("weight_decay")) + final_wd = float(cfgs_opt.get("final_weight_decay")) + num_epochs = cfgs_opt.get("epochs") + warmup = cfgs_opt.get("warmup") + start_lr = cfgs_opt.get("start_lr") + lr = cfgs_opt.get("lr") + final_lr = cfgs_opt.get("final_lr") + ema = cfgs_opt.get("ema") + use_radamw = cfgs_opt.get("use_radamw", False) + betas = cfgs_opt.get("betas", (0.9, 0.999)) + eps = cfgs_opt.get("eps", 1.0e-8) + loss_reg_std_mult = cfgs_opt.get("loss_reg_std_mult", None) + loss_reg_num_tracking_steps = cfgs_opt.get("loss_reg_num_tracking_steps", 300) + loss_reg_min_epoch = cfgs_opt.get("loss_reg_min_epoch", 50) + if loss_reg_std_mult is not None: + logger.info("Loss regulation activated") + # ----------------------------------------------------------------------- # + + np.random.seed(seed) + torch.manual_seed(seed) + torch.backends.cudnn.benchmark = True + try: + mp.set_start_method("spawn") + except Exception: + pass + + # -- init torch distributed backend + world_size, rank = init_distributed() + data_world_size, data_rank = world_size, rank + logger.info(f"Initialized (rank/world-size) {rank}/{world_size}") + img_world_size = 0 + + # make adjustments to batch size for image data + model_fpcs = dataset_fpcs + model_cfgs_mask = cfgs_mask + model_tubelet_size = tubelet_size + if cfgs_img_data is not None: + img_world_size = int(world_size * img_rank_ratio) + num_video_ranks = world_size - img_world_size + img_total_batch_size = img_dataset_batch_size * world_size + video_total_batch_size = batch_size * world_size + + if img_total_batch_size % img_world_size != 0: + raise ValueError( + f"img_total_batch_size ({img_total_batch_size}) must be divisible by num_img_ranks ({img_world_size})" + ) + if video_total_batch_size % num_video_ranks != 0: + raise ValueError( + f"video_total_batch_size ({video_total_batch_size}) must be divisible by num_video_ranks ({num_video_ranks})" + ) + + # img_dataset_batch_size = img_total_batch_size // img_world_size + batch_size = video_total_batch_size // num_video_ranks + + if rank < int(world_size * img_rank_ratio): + crop_size = cfgs_img_data.get("crop_size", 512) + grid_size = crop_size // patch_size + + if rank < int(world_size * img_rank_ratio): + logger.info( + f"On rank {rank}, updating dataset with dataset type {img_dataset_type}" + ) + if img_temporal_dim_size is not None: + if img_dataset_fpcs[0] != 1: + raise NotImplementedError( + "Image loader only supports 1 frame per clip with img_temporal_dim_size=1" + ) + tubelet_size = 1 + else: + tubelet_size = tubelet_size + + dataset_type = img_dataset_type + dataset_paths = img_dataset_paths + datasets_weights = img_dataset_weights + dataset_fpcs = img_dataset_fpcs + batch_size = img_dataset_batch_size + num_workers = img_num_workers + if img_mask is not None: + logger.info("Using image mask") + cfgs_mask = img_mask + + data_rank = rank + data_world_size = img_world_size + lambda_value = lambda_value_img # We select a different lambda value depending on video vs. image + else: + data_rank = rank - img_world_size + data_world_size = world_size - img_world_size + lambda_value = lambda_value_vid # We select a different lambda value depending on video vs. image + + logger.info( + f"For rank {rank} with world size {world_size}, " + f"we have total image batch size {img_total_batch_size}, total video batch size {video_total_batch_size}, " + f"image ranks: {img_world_size}, video ranks: {num_video_ranks}, " + f"using the following params: " + f"dataset_type: {dataset_type}, " + f"dataset_paths: {dataset_paths}, " + f"datasets_weights: {datasets_weights}, " + f"dataset_fpcs: {dataset_fpcs}, " + f"batch_size: {batch_size}, " + f"num_workers: {num_workers}, " + f"data_rank: {data_rank}, " + f"data_world_size: {data_world_size}" + f"lambda_value for the context loss: {lambda_value}" + ) + else: + lambda_value = lambda_value_vid + + # -- set device + if not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device("cuda:0") + torch.cuda.set_device(device) + + # -- log/checkpointing paths + log_file = os.path.join(folder, f"log_r{rank}.csv") + latest_file = "latest.pth.tar" + latest_path = os.path.join(folder, latest_file) + + load_path = None + if load_model: + if is_anneal: + if os.path.exists(latest_path) and resume_anneal: + load_path = latest_path + else: + load_path = anneal_ckpt + resume_anneal = False + else: + load_path = r_file if r_file is not None else latest_path + if not os.path.exists(load_path): + load_path = None + load_model = False + + # -- make csv_logger + csv_logger = CSVLogger( + log_file, + ("%d", "epoch"), + ("%d", "itr"), + ("%.5f", "loss"), + ("%d", "iter-time(ms)"), + ("%d", "gpu-time(ms)"), + ("%d", "dataload-time(ms)"), + ) + + # -- init model + encoder, predictor = init_video_model( + uniform_power=uniform_power, + use_mask_tokens=use_mask_tokens, + num_mask_tokens=int(len(model_cfgs_mask) * len(model_fpcs)), + zero_init_mask_tokens=zero_init_mask_tokens, + device=device, + patch_size=patch_size, + max_num_frames=max_num_frames, + tubelet_size=model_tubelet_size, + model_name=model_name, + crop_size=crop_size, + pred_depth=pred_depth, + pred_num_heads=pred_num_heads, + pred_embed_dim=pred_embed_dim, + is_causal=is_causal, + pred_is_causal=pred_is_causal, + use_sdpa=use_sdpa, + use_silu=use_silu, + use_pred_silu=use_pred_silu, + wide_silu=wide_silu, + use_rope=use_rope, + use_activation_checkpointing=use_activation_checkpointing, + return_all_tokens=predict_all, + chop_last_n_tokens=shift_by_n, + init_type=init_type, + img_temporal_dim_size=img_temporal_dim_size, + n_registers=n_registers, + n_registers_predictor=n_registers_predictor, + has_cls_first=has_cls_first, + interpolate_rope=interpolate_rope, + modality_embedding=modality_embedding, + ) + target_encoder = copy.deepcopy(encoder) + + if compile_model: + logger.info("Compiling encoder, target_encoder, and predictor.") + torch._dynamo.config.optimize_ddp = False + encoder.compile() + target_encoder.compile() + predictor.compile() + + mask_collator = MaskCollator( + cfgs_mask=cfgs_mask, + dataset_fpcs=dataset_fpcs, + crop_size=crop_size, + patch_size=patch_size, + tubelet_size=tubelet_size, + ) + + transform = make_transforms( + random_horizontal_flip=True, + random_resize_aspect_ratio=ar_range, + random_resize_scale=rr_scale, + reprob=reprob, + auto_augment=use_aa, + motion_shift=motion_shift, + crop_size=crop_size, + ) + + # -- init data-loaders/samplers + (unsupervised_loader, unsupervised_sampler) = init_data( + data=dataset_type, + root_path=dataset_paths, + batch_size=batch_size, + training=True, + # clip_len=clip_len, + dataset_fpcs=dataset_fpcs, + fps=fps, + transform=transform, + rank=data_rank, + world_size=data_world_size, + datasets_weights=datasets_weights, + collator=mask_collator, + num_workers=num_workers, + pin_mem=pin_mem, + log_dir=None, + ) + try: + _dlen = len(unsupervised_loader) + except Exception: + try: + _dlen = unsupervised_loader.num_batches + except Exception: + _dlen = -1 + if ipe is None: + ipe = _dlen + logger.info(f"Using batch size of {batch_size}, fpcs of {dataset_fpcs}") + logger.info(f"iterations per epoch/dataset length: {ipe}/{_dlen}") + + # zizi + + # -- init optimizer and scheduler + optimizer, scaler, scheduler, wd_scheduler = init_opt( + is_anneal=is_anneal, + encoder=encoder, + predictor=predictor, + use_radamw=use_radamw, + wd=wd, + final_wd=final_wd, + start_lr=start_lr, + ref_lr=lr, + final_lr=final_lr, + iterations_per_epoch=ipe, + warmup=warmup, + num_epochs=num_epochs, + ipe_scale=ipe_scale, + mixed_precision=mixed_precision, + betas=betas, + eps=eps, + ) + encoder = DistributedDataParallel(encoder, static_graph=True) + predictor = DistributedDataParallel( + predictor, static_graph=False, find_unused_parameters=True + ) + target_encoder = DistributedDataParallel(target_encoder) + for p in target_encoder.parameters(): + p.requires_grad = False + + # -- momentum schedule + momentum_scheduler = ( + ema[0] + i * (ema[1] - ema[0]) / (ipe * num_epochs * ipe_scale) + for i in range(int(ipe * num_epochs) + 1) + ) + lambda_sched = Lambda_LinearWarmupHold(lambda_value=lambda_value) + + start_epoch = 0 + # -- load training checkpoint + print("Loadind checkpoint from: ", load_path) + if load_model or os.path.exists(latest_path): + ( + encoder, + predictor, + target_encoder, + optimizer, + scaler, + start_epoch, + ) = load_checkpoint( + r_path=load_path, + encoder=encoder, + predictor=predictor, + target_encoder=target_encoder, + opt=optimizer, + scaler=scaler, + is_anneal=is_anneal and not resume_anneal, + ) + if not is_anneal or resume_anneal: + for _ in range(start_epoch * ipe): + scheduler.step() + wd_scheduler.step() + next(momentum_scheduler) + mask_collator.step() + + def save_checkpoint(epoch, path): + if rank != 0: + return + save_dict = { + "encoder": encoder.state_dict(), + "predictor": predictor.state_dict(), + "opt": optimizer.state_dict(), + "scaler": None if scaler is None else scaler.state_dict(), + "target_encoder": target_encoder.state_dict(), + "epoch": epoch, + "loss": loss_meter.avg, + "batch_size": batch_size, + "world_size": world_size, + "lr": lr, + } + try: + torch.save(save_dict, path) + except Exception as e: + logger.info(f"Encountered exception when saving checkpoint: {e}") + + logger.info("Initializing loader...") + unsupervised_sampler.set_epoch(start_epoch) + loader = iter(unsupervised_loader) + + if skip_batches > 0: + logger.info(f"Skip {skip_batches} batches") + + for itr in range(skip_batches): + if itr % 10 == 0: + logger.info(f"Skip {itr}/{skip_batches} batches") + try: + _ = next(loader) + except Exception: + loader = iter(unsupervised_loader) + _ = next(loader) + + if sync_gc: + gc.disable() + gc.collect() + + trailing_losses = [] + step_count = 0 + + # -- TRAINING LOOP + for epoch in range(start_epoch, num_epochs): + logger.info("Epoch %d" % (epoch + 1)) + + loss_meter = AverageMeter() + mask_meters = {fpc: AverageMeter() for fpc in dataset_fpcs} + iter_time_meter = AverageMeter() + gpu_time_meter = AverageMeter() + data_elapsed_time_meter = AverageMeter() + + for itr in range(ipe): + itr_start_time = time.time() + + iter_retries = 0 + iter_successful = False + while not iter_successful: + try: + sample = next(loader) + iter_successful = True + except StopIteration: + logger.info("Exhausted data loaders. Refreshing...") + if "airstore" in dataset_type.lower(): + unsupervised_sampler.increase_epoch() + else: + unsupervised_sampler.set_epoch(epoch) + loader = iter(unsupervised_loader) + except Exception as e: + NUM_RETRIES = 5 + if iter_retries < NUM_RETRIES: + logger.warning( + f"Encountered exception when loading data (num retries {iter_retries}):\n{e}" + ) + iter_retries += 1 + time.sleep(5) + else: + raise RuntimeError( + f"Exceeded max retries ({NUM_RETRIES}) when loading data." + ) from e + + for _fpc_sample in sample: + bs, fpc = _fpc_sample[0][-1][0].size() + mask_meters[fpc].update(bs / batch_size) + + def load_clips(): + all_clips, all_masks_enc, all_masks_pred = [], [], [] + for fpc_sample in sample: + udata, masks_enc, masks_pred = fpc_sample + all_clips += [udata[0][0].to(device, non_blocking=True)] + all_masks_enc += [ + [m.to(device, non_blocking=True) for m in masks_enc] + ] + all_masks_pred += [ + [m.to(device, non_blocking=True) for m in masks_pred] + ] + return all_clips, all_masks_enc, all_masks_pred + + clips, masks_enc, masks_pred = load_clips() + data_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 + + if sync_gc and (itr + 1) % GARBAGE_COLLECT_ITR_FREQ == 0: + logger.info("Running garbage collection...") + gc.collect() + + def train_step(): + _new_lr = scheduler.step() + _new_wd = wd_scheduler.step() + + def forward_target(c, embed_dim=embed_dim_encoder): + with torch.no_grad(): + h = target_encoder(c, gram_mode=False, training_mode=True) + new_h = [] + for hi in h: + if levels_predictor > 1: + hi_0 = F.layer_norm(hi[:, :, :embed_dim], (embed_dim,)) + hi_1 = F.layer_norm( + hi[:, :, embed_dim : embed_dim * 2], + (embed_dim,), + ) + hi_2 = F.layer_norm( + hi[:, :, embed_dim * 2 : embed_dim * 3], + (embed_dim,), + ) + hi_3 = F.layer_norm(hi[:, :, -embed_dim:], (embed_dim,)) + hi_norm = torch.cat([hi_0, hi_1, hi_2, hi_3], dim=2) + new_h.append(hi_norm) + else: + new_h.append(F.layer_norm(hi, (hi.size(-1),))) + return new_h + + def forward_context(clips, embed_dim=embed_dim_encoder): + modality = "video" + if img_temporal_dim_size is not None: + if clips[0].shape[2] == img_temporal_dim_size: + modality = "image" + z = encoder(clips, masks_enc, gram_mode=False, training_mode=True) + z_pred, z_context = predictor( + z, masks_enc, masks_pred, mod=modality + ) + if normalize_predictor: + z_pred = normalize_nested(z_pred, embed_dim) + + if predict_all: + z_context = normalize_nested(z_context, embed_dim) + return z_pred, z_context + + def loss_fn(z, h, masks_to_apply, cls_loss, d_weights): + if cls_loss: + h_cls = [hi[:, 0].unsqueeze(1) for hi in h] + h = [ + apply_masks(hi[:, 1:], mi, concat=False) + for hi, mi in zip(h, masks_to_apply) + ] + loss, n = 0, 0 + for zi, hi, hi_cls in zip(z, h, h_cls): + for zij, hij in zip(zi, hi): + h_term = torch.cat([hi_cls, hij], dim=1) + loss += ( + torch.mean(torch.abs(zij - h_term) ** loss_exp) + / loss_exp + ) + n += 1 + + loss /= n + return loss + else: + h = [ + apply_masks(hi, mi, concat=False) + for hi, mi in zip(h, masks_to_apply) + ] + + if d_weights is not None: + loss, n = 0, 0 + for zi, hi, d_i in zip(z, h, d_weights): + for zij, hij, d_ij in zip(zi, hi, d_i): + loss_n = torch.abs(zij - hij) ** loss_exp * ( + 1 / d_ij.unsqueeze(2) + ) + loss += torch.mean(loss_n) / loss_exp + n += 1 + loss /= n + return loss + else: + loss, n = 0, 0 + for zi, hi in zip(z, h): + for zij, hij in zip(zi, hi): + loss += ( + torch.mean(torch.abs(zij - hij) ** loss_exp) + / loss_exp + ) + n += 1 + loss /= n + return loss + + # Step 1. Forward + with torch.cuda.amp.autocast(dtype=dtype, enabled=mixed_precision): + h = forward_target(clips) + z_pred, z_context = forward_context(clips) + loss = 0 + loss_pred = loss_fn( + z_pred, h, masks_pred, cls_loss=has_cls_first, d_weights=None + ) + loss += loss_pred + + # Context loss + if predict_all: + distance_weights = compute_mask_distance( + masks_pred, masks_enc, grid_size, offset_context_loss + ) + if weight_distance_loss: + d_weights = distance_weights + else: + d_weights = None + loss_context = loss_fn( + z_context, h, masks_enc, cls_loss=False, d_weights=d_weights + ) + if lambda_progressive: + lambda_value_step = lambda_sched.value(epoch * ipe + itr) + else: + lambda_value_step = lambda_value + loss += loss_context * lambda_value_step + + # Step 2. Backward & step + run_step = True + if loss_reg_std_mult is not None: + meanval = np.mean(trailing_losses) + stdval = np.std(trailing_losses) + max_bound = meanval + loss_reg_std_mult * stdval + if ( + loss > max_bound + and epoch > loss_reg_min_epoch + and len(trailing_losses) + > int(0.5 * loss_reg_num_tracking_steps) + ): + run_step = False + loss.backward() + logger.info( + f"Loss {loss} is above bound {meanval} + {loss_reg_std_mult} * {stdval}. Skipping step." + ) + + if run_step: + if mixed_precision: + scaler.scale(loss).backward() + scaler.unscale_(optimizer) + else: + loss.backward() + if mixed_precision: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + optimizer.zero_grad() + + # Step 3. momentum update of target encoder + m = min(next(momentum_scheduler), ema[1]) + with torch.no_grad(): + params_k = [] + params_q = [] + for param_q, param_k in zip( + encoder.parameters(), target_encoder.parameters() + ): + params_k.append(param_k) + params_q.append(param_q) + torch._foreach_mul_(params_k, m) + torch._foreach_add_(params_k, params_q, alpha=1 - m) + + return ( + float(loss), + _new_lr, + _new_wd, + run_step, + ) + + ( + loss, + _new_lr, + _new_wd, + run_step, + ), gpu_etime_ms = gpu_timer(train_step) + iter_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 + loss_meter.update(loss) + iter_time_meter.update(iter_elapsed_time_ms) + gpu_time_meter.update(gpu_etime_ms) + data_elapsed_time_meter.update(data_elapsed_time_ms) + + if loss_reg_std_mult is not None: + if run_step: + trailing_losses.append(loss) + if len(trailing_losses) > loss_reg_num_tracking_steps: + trailing_losses = trailing_losses[1:] + else: + step_count += 1 + if step_count > MAX_REPEAT_COUNTS: + raise RuntimeError( + "Loss is above bound for too many tries. Exiting." + ) + + # -- Logging + def log_stats(): + csv_logger.log( + epoch + 1, + itr, + loss, + iter_elapsed_time_ms, + gpu_etime_ms, + data_elapsed_time_ms, + ) + if ( + (itr % log_freq == 0) + or (itr == ipe - 1) + or np.isnan(loss) + or np.isinf(loss) + ): + logger.info( + "[%d, %5d] loss: %.3f " + "masks: %s " + "[wd: %.2e] [lr: %.2e] " + "[mem: %.2e] " + "[iter: %.1f ms] " + "[gpu: %.1f ms] " + "[data: %.1f ms]" + % ( + epoch + 1, + itr, + loss_meter.avg, + "[" + + ", ".join( + [ + f"{k}: " + "%.1f" % mask_meters[k].avg + for k in mask_meters + ] + ) + + "]", + _new_wd, + _new_lr, + torch.cuda.max_memory_allocated() / 1024.0**2, + iter_time_meter.avg, + gpu_time_meter.avg, + data_elapsed_time_meter.avg, + ) + ) + + log_stats() + assert not np.isnan(loss), "loss is nan" + + # -- Save Checkpoint + logger.info("avg. loss %.3f" % loss_meter.avg) + if (epoch + 1) % CHECKPOINT_FREQ == 0 or epoch == (num_epochs - 1): + save_checkpoint(epoch + 1, latest_path) + if save_every_freq > 0 and (epoch + 1) % save_every_freq == 0: + save_every_file = f"e{epoch}.pth.tar" + save_every_path = os.path.join(folder, save_every_file) + save_checkpoint(epoch + 1, save_every_path) diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/transforms.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..0fad7ef393074cd7dd6992585d853ae09b645d7c --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/transforms.py @@ -0,0 +1,139 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np + +import src.datasets.utils.video.transforms as video_transforms +import torch +import torchvision.transforms as transforms +from PIL import Image +from src.datasets.utils.video.randerase import RandomErasing + + +def make_transforms( + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), +): + _frames_augmentation = VideoTransform( + random_horizontal_flip=random_horizontal_flip, + random_resize_aspect_ratio=random_resize_aspect_ratio, + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + crop_size=crop_size, + normalize=normalize, + ) + return _frames_augmentation + + +class VideoTransform(object): + def __init__( + self, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + ): + self.random_horizontal_flip = random_horizontal_flip + self.random_resize_aspect_ratio = random_resize_aspect_ratio + self.random_resize_scale = random_resize_scale + self.auto_augment = auto_augment + self.motion_shift = motion_shift + self.crop_size = crop_size + self.mean = torch.tensor(normalize[0], dtype=torch.float32) + self.std = torch.tensor(normalize[1], dtype=torch.float32) + if not self.auto_augment: + self.mean *= 255.0 + self.std *= 255.0 + + self.autoaug_transform = video_transforms.create_random_augment( + input_size=(crop_size, crop_size), + auto_augment="rand-m7-n4-mstd0.5-inc1", + interpolation="bicubic", + ) + + self.spatial_transform = ( + video_transforms.random_resized_crop_with_shift + if motion_shift + else video_transforms.random_resized_crop + ) + + self.reprob = reprob + self.erase_transform = RandomErasing( + reprob, + mode="pixel", + max_count=1, + num_splits=1, + device="cpu", + ) + + def __call__(self, buffer): + # Handle PIL Image input (from ImageNet datasets) + if isinstance(buffer, Image.Image): + # Convert PIL Image to tensor with shape T H W C (T=1 for single image) + buffer = np.array(buffer) # H W C + buffer = np.expand_dims(buffer, axis=0) # T H W C where T=1 + buffer = torch.tensor(buffer, dtype=torch.float32) + + if self.auto_augment: + buffer = [transforms.ToPILImage()(frame) for frame in buffer] + buffer = self.autoaug_transform(buffer) + buffer = [transforms.ToTensor()(img) for img in buffer] + buffer = torch.stack(buffer) # T C H W + buffer = buffer.permute(0, 2, 3, 1) # T H W C + elif torch.is_tensor(buffer): + buffer = buffer.to(torch.float32) + else: + buffer = torch.tensor(buffer, dtype=torch.float32) + + buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W + + buffer = self.spatial_transform( + images=buffer, + target_height=self.crop_size, + target_width=self.crop_size, + scale=self.random_resize_scale, + ratio=self.random_resize_aspect_ratio, + ) + if self.random_horizontal_flip: + buffer, _ = video_transforms.horizontal_flip(0.5, buffer) + + buffer = _tensor_normalize_inplace(buffer, self.mean, self.std) + if self.reprob > 0: + buffer = buffer.permute(1, 0, 2, 3) + buffer = self.erase_transform(buffer) + buffer = buffer.permute(1, 0, 2, 3) + + return buffer + + +def _tensor_normalize_inplace(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize (with dimensions C, T, H, W). + mean (tensor): mean value to subtract (in 0 to 255 floats). + std (tensor): std to divide (in 0 to 255 floats). + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + + C, T, H, W = tensor.shape + tensor = tensor.view(C, -1).permute(1, 0) + tensor.sub_(mean).div_(std) + tensor = tensor.permute(1, 0).view(C, T, H, W) + return tensor diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/utils.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d32fd6269d325f2e0b53974536718fb977615d --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/utils.py @@ -0,0 +1,368 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import sys + +import app.vjepa_2_1.models.predictor as vit_pred +import app.vjepa_2_1.models.vision_transformer as video_vit +import torch +import torch.nn.functional as F +import yaml +from app.vjepa_2_1.wrappers import MultiSeqWrapper, PredictorMultiSeqWrapper +from src.utils.checkpoint_loader import robust_checkpoint_loader +from src.utils.schedulers import ( + CosineWDSchedule, + LinearDecaySchedule, + WarmupCosineSchedule, +) + +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +logger = logging.getLogger() + + +def normalize_and_concat(tensor, embed_dim): + """Split tensor into 4 chunks of size embed_dim along the last axis, + apply LayerNorm to each chunk, then concatenate back.""" + chunks = [ + F.layer_norm(tensor[:, :, i * embed_dim : (i + 1) * embed_dim], (embed_dim,)) + for i in range(4) + ] + return torch.cat(chunks, dim=2) + + +def normalize_nested(nested, embed_dim): + """Apply normalize_and_concat recursively over nested lists.""" + return [ + [[normalize_and_concat(z, embed_dim) for z in inner] for inner in outer] + for outer in nested + ] + + +def build_eval_args( + model_name, + patch_size, + tubelet_size, + num_frames, + logging_folder, + checkpoint, + write_tag, + eval_cfg_paths, + uniform_power=False, + use_sdpa=False, + clip_duration=None, + use_silu=False, + wide_silu=True, + tag=None, +): + """ + Helper function to parse the pre-training configs to construct the + evaluation configs, return as a list of eval configs. + """ + import warnings + + if eval_cfg_paths is None: + logger.info("No evaluations specified!") + return + + eval_nodes = None + eval_tasks_per_node = None + args_eval = [] + for i, f in enumerate(eval_cfg_paths): + with open(f, "r") as y_file: + _args = yaml.load(y_file, Loader=yaml.FullLoader) + _tag = _args.get("tag", "") + _args["tag"] = f"{tag}-{_tag}" + _nodes = _args.get("nodes", None) + _tasks = _args.get("tasks_per_node", 8) + eval_nodes = _nodes if eval_nodes is None else eval_nodes + eval_tasks_per_node = ( + _tasks if eval_tasks_per_node is None else eval_tasks_per_node + ) + if (eval_nodes != _nodes) or (eval_tasks_per_node != _tasks): + warnings.warn( + "Configs for online evals must use same number of nodes for slurm-batch processing" + ) + + _args["pretrain"] = {} + _args["pretrain"]["model_name"] = model_name + _args["pretrain"]["patch_size"] = patch_size + _args["pretrain"]["tubelet_size"] = tubelet_size + _args["pretrain"]["uniform_power"] = uniform_power + _args["pretrain"]["use_sdpa"] = use_sdpa + _args["pretrain"]["clip_duration"] = clip_duration + _args["pretrain"]["use_silu"] = use_silu + _args["pretrain"]["wide_silu"] = wide_silu + _args["pretrain"]["frames_per_clip"] = num_frames + _args["pretrain"]["folder"] = logging_folder + _args["pretrain"]["checkpoint"] = checkpoint + _args["pretrain"]["write_tag"] = write_tag + + args_eval += [_args] + + return eval_nodes, eval_tasks_per_node, args_eval + + +def load_checkpoint( + r_path, + encoder, + predictor, + target_encoder, + opt, + scaler, + is_anneal=False, +): + logger.info(f"Loading {r_path}") + checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) + + epoch = 0 + if not is_anneal: + epoch = checkpoint["epoch"] + + pretrained_dict = checkpoint["encoder"] + for k, v in encoder.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info( + f'key "{k}" is of different shape in model and loaded state dict' + ) + pretrained_dict[k] = v + msg = encoder.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained encoder from epoch {epoch} with msg: {msg}") + + pretrained_dict = checkpoint["predictor"] + for k, v in predictor.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info( + f'key "{k}" is of different shape in model and loaded state dict' + ) + pretrained_dict[k] = v + msg = predictor.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained predictor from epoch {epoch} with msg: {msg}") + + if target_encoder is not None: + pretrained_dict = checkpoint["target_encoder"] + for k, v in target_encoder.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info( + f'key "{k}" is of different shape in model and loaded state dict' + ) + pretrained_dict[k] = v + msg = target_encoder.load_state_dict(pretrained_dict, strict=False) + logger.info( + f"loaded pretrained target encoder from epoch {epoch} with msg: {msg}" + ) + + try: + opt.load_state_dict(checkpoint["opt"]) + except ValueError: + print("[warn] Optimizer groups mismatch; reinitializing optimizer.") + if scaler is not None: + scaler.load_state_dict(checkpoint["scaler"]) + logger.info(f"loaded optimizers from epoch {epoch}") + logger.info(f"read-path: {r_path}") + del checkpoint + + return ( + encoder, + predictor, + target_encoder, + opt, + scaler, + epoch, + ) + + +def init_video_model( + device, + patch_size=16, + max_num_frames=16, + tubelet_size=2, + model_name="vit_base", + crop_size=224, + pred_depth=6, + pred_num_heads=None, + pred_embed_dim=384, + uniform_power=False, + use_mask_tokens=False, + num_mask_tokens=2, + zero_init_mask_tokens=True, + use_sdpa=False, + use_rope=False, + use_silu=False, + use_pred_silu=False, + wide_silu=False, + is_causal=False, + pred_is_causal=False, + use_activation_checkpointing=False, + return_all_tokens=False, + chop_last_n_tokens=0, + init_type="default", + img_temporal_dim_size=None, + n_registers=0, + n_registers_predictor=0, + has_cls_first=False, + interpolate_rope=False, + modality_embedding=False, +): + encoder = video_vit.__dict__[model_name]( + img_size=crop_size, + patch_size=patch_size, + num_frames=max_num_frames, + tubelet_size=tubelet_size, + uniform_power=uniform_power, + use_sdpa=use_sdpa, + use_silu=use_silu, + wide_silu=wide_silu, + use_activation_checkpointing=use_activation_checkpointing, + is_causal=is_causal, + use_rope=use_rope, + init_type=init_type, + img_temporal_dim_size=img_temporal_dim_size, + n_registers=n_registers, + has_cls_first=has_cls_first, + interpolate_rope=interpolate_rope, + modality_embedding=modality_embedding, + ) + encoder = MultiSeqWrapper(encoder) + predictor = vit_pred.__dict__["vit_predictor"]( + img_size=crop_size, + use_mask_tokens=use_mask_tokens, + patch_size=patch_size, + num_frames=max_num_frames, + tubelet_size=tubelet_size, + embed_dim=encoder.backbone.embed_dim, + predictor_embed_dim=pred_embed_dim, + depth=pred_depth, + num_heads=( + encoder.backbone.num_heads if pred_num_heads is None else pred_num_heads + ), + uniform_power=uniform_power, + num_mask_tokens=num_mask_tokens, + zero_init_mask_tokens=zero_init_mask_tokens, + use_rope=use_rope, + use_sdpa=use_sdpa, + is_causal=pred_is_causal, + use_silu=use_pred_silu, + wide_silu=wide_silu, + use_activation_checkpointing=use_activation_checkpointing, + return_all_tokens=return_all_tokens, + chop_last_n_tokens=chop_last_n_tokens, + n_registers=n_registers_predictor, + has_cls_first=has_cls_first, + interpolate_rope=interpolate_rope, + modality_embedding=modality_embedding, + img_temporal_dim_size=img_temporal_dim_size, + ) + predictor = PredictorMultiSeqWrapper(predictor) + + encoder.to(device) + predictor.to(device) + logger.info(encoder) + logger.info(predictor) + + def count_parameters(model): + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + logger.info(f"Encoder number of parameters: {count_parameters(encoder)}") + logger.info(f"Predictor number of parameters: {count_parameters(predictor)}") + + return encoder, predictor + + +def init_opt( + is_anneal, + encoder, + predictor, + iterations_per_epoch, + start_lr, + ref_lr, + warmup, + num_epochs, + use_radamw=False, + wd=1e-6, + final_wd=1e-6, + final_lr=0.0, + mixed_precision=False, + ipe_scale=1.25, + betas=(0.9, 0.999), + eps=1e-8, + zero_init_bias_wd=True, +): + param_groups = [ + { + "params": ( + p + for n, p in encoder.named_parameters() + if ("bias" not in n) and (len(p.shape) != 1) + ) + }, + { + "params": ( + p + for n, p in predictor.named_parameters() + if ("bias" not in n) and (len(p.shape) != 1) + ) + }, + { + "params": ( + p + for n, p in encoder.named_parameters() + if ("bias" in n) or (len(p.shape) == 1) + ), + "WD_exclude": zero_init_bias_wd, + "weight_decay": 0, + }, + { + "params": ( + p + for n, p in predictor.named_parameters() + if ("bias" in n) or (len(p.shape) == 1) + ), + "WD_exclude": zero_init_bias_wd, + "weight_decay": 0, + }, + ] + + if use_radamw: + from src.utils.adamw import AdamW as RAdamW + + logger.info("Using Rescaled-AdamW") + optimizer = RAdamW(param_groups, betas=betas, eps=eps) + else: + logger.info("Using AdamW") + optimizer = torch.optim.AdamW(param_groups, betas=betas, eps=eps) + + if not is_anneal: + scheduler = WarmupCosineSchedule( + optimizer, + warmup_steps=int(warmup * iterations_per_epoch), + start_lr=start_lr, + ref_lr=ref_lr, + final_lr=final_lr, + T_max=int(ipe_scale * num_epochs * iterations_per_epoch), + ) + else: + scheduler = LinearDecaySchedule( + optimizer, + ref_lr=ref_lr, + final_lr=final_lr, + T_max=int(ipe_scale * num_epochs * iterations_per_epoch), + ) + wd_scheduler = CosineWDSchedule( + optimizer, + ref_wd=wd, + final_wd=final_wd, + T_max=int(ipe_scale * num_epochs * iterations_per_epoch), + ) + + scaler = torch.cuda.amp.GradScaler() if mixed_precision else None + return optimizer, scaler, scheduler, wd_scheduler diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/wrappers.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..d31dfb8010cc15ffba879b383d0da97525dd8345 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_2_1/wrappers.py @@ -0,0 +1,115 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# + +import torch.nn as nn +import torch.nn.functional as F + + +class MultiSeqWrapper(nn.Module): + + def __init__(self, backbone): + super().__init__() + self.backbone = backbone + self.embed_dim = backbone.embed_dim + + def forward(self, x, masks=None, gram_mode=False, training_mode=False): + """ + :param x: [list] List of Tensors of different seq lengths + :param masks: [list] List of Tensors (index: masks for given seq length) + """ + if masks is None: + outputs = [] + for x_fpc in x: + if gram_mode: + # First we make the image bigger + B, C, T, H, W = x_fpc.shape + x_2d = x_fpc.permute(0, 2, 1, 3, 4).reshape( + B * T, C, H, W + ) # (B*T, C, H, W) + x_up = F.interpolate( + x_2d, scale_factor=2, mode="bicubic", align_corners=False + ) + _, _, H_up, W_up = x_up.shape + x_up = x_up.view(B, T, C, H_up, W_up).permute( + 0, 2, 1, 3, 4 + ) # (B,C,T,H_up,W_up) + + # Then we make the pass through the backbone + out = self.backbone(x_up) + B, N, D = out.shape + H_up_patches = W_up_patches = int( + H_up // 16 + ) # We have hardcoded this to the patch size + if T == 1: + T_up_patches = 1 # In this case, it is a LVD image + else: + T_up_patches = int( + T // 2 + ) # We have hardcoded this to the tubelet size + out_3d = out.view( + B, T_up_patches, H_up_patches, W_up_patches, D + ) # (bs, T, H, W, D) + out_3d = out_3d.permute(0, 4, 1, 2, 3) # (bs, D, T, H, W) + + # Downscale to original 2D size + out_2d = out_3d.permute(0, 2, 1, 3, 4).reshape( + B * T_up_patches, D, H_up_patches, W_up_patches + ) # (B*T, C, H_up, W_up) + out = F.interpolate( + out_2d, + size=(int(H_up_patches // 2), int(W_up_patches // 2)), + mode="bicubic", + align_corners=False, + ) + out = out.view( + B, + T_up_patches, + D, + int(H_up_patches // 2), + int(W_up_patches // 2), + ).permute( + 0, 2, 1, 3, 4 + ) # (B,C,T,H,W) + out = out.permute(0, 2, 3, 4, 1).reshape( + B, + T_up_patches * int(H_up_patches // 2) * int(W_up_patches // 2), + D, + ) # (B,C,T,H,W) -> (B, T, H, W, C) -> (B, T * H * W, C) + outputs.append(out) + else: + outputs.append(self.backbone(x_fpc, training=training_mode)) + return outputs + + outs = [[] for _ in x] + for i, (x_fpc, m_fpc) in enumerate(zip(x, masks)): + for m in m_fpc: + outs[i] += [self.backbone(x_fpc, masks=m, training=training_mode)] + return outs + + +class PredictorMultiSeqWrapper(nn.Module): + + def __init__(self, backbone): + super().__init__() + self.backbone = backbone + + def forward(self, x, masks_x, masks_y, mod="video"): + """ + :param x: [list] List of encoder outputs for different seq lengths + :param masks_x: [list] List of encoder masks + :param masks_y: [list] List of predictor masks + """ + n = 0 + outs_pred = [[] for _ in x] + outs_context = [[] for _ in x] + for i, (x_fpc, mx_fpc, my_fpc) in enumerate(zip(x, masks_x, masks_y)): + for xij, mx, my in zip(x_fpc, mx_fpc, my_fpc): + x_pred, x_context = self.backbone(xij, mx, my, mask_index=i, mod=mod) + outs_pred[i] += [x_pred] + outs_context[i] += [x_context] + n += 1 + return outs_pred, outs_context diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/droid.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/droid.py new file mode 100644 index 0000000000000000000000000000000000000000..630fe6d7525d0552fb233179f95a4078d84e1c61 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/droid.py @@ -0,0 +1,232 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# + +import json +import os +from logging import getLogger +from math import ceil + +import h5py +import numpy as np +import pandas as pd +import torch +import torch.utils.data +from decord import VideoReader, cpu +from scipy.spatial.transform import Rotation + +_GLOBAL_SEED = 0 +logger = getLogger() + + +def init_data( + data_path, + batch_size, + frames_per_clip=16, + fps=5, + crop_size=224, + rank=0, + world_size=1, + camera_views=0, + stereo_view=False, + drop_last=True, + num_workers=10, + pin_mem=True, + persistent_workers=True, + collator=None, + transform=None, + camera_frame=False, + tubelet_size=2, +): + dataset = DROIDVideoDataset( + data_path=data_path, + frames_per_clip=frames_per_clip, + transform=transform, + fps=fps, + camera_views=camera_views, + frameskip=tubelet_size, + camera_frame=camera_frame, + ) + + dist_sampler = torch.utils.data.distributed.DistributedSampler( + dataset, num_replicas=world_size, rank=rank, shuffle=True + ) + + data_loader = torch.utils.data.DataLoader( + dataset, + collate_fn=collator, + sampler=dist_sampler, + batch_size=batch_size, + drop_last=drop_last, + pin_memory=pin_mem, + num_workers=num_workers, + persistent_workers=(num_workers > 0) and persistent_workers, + ) + + logger.info("VideoDataset unsupervised data loader created") + + return data_loader, dist_sampler + + +def get_json(directory): + for filename in os.listdir(directory): + if filename.endswith(".json"): + file_path = os.path.join(directory, filename) + try: + with open(file_path, "r") as f: + return json.load(f) + except json.JSONDecodeError: + print(f"Error decoding JSON in file: {filename}") + except Exception as e: + print(f"An unexpected error occurred while processing {filename}: {e}") + + +class DROIDVideoDataset(torch.utils.data.Dataset): + """Video classification dataset.""" + + def __init__( + self, + data_path, + camera_views=["left_mp4_path", "right_mp4_path"], + frameskip=2, + frames_per_clip=16, + fps=5, + transform=None, + camera_frame=False, + ): + self.data_path = data_path + self.frames_per_clip = frames_per_clip + self.frameskip = frameskip + self.fps = fps + self.transform = transform + self.camera_frame = camera_frame + if VideoReader is None: + raise ImportError('Unable to import "decord" which is required to read videos.') + + # Camera views + # --- + # wrist camera view + # left camera view + # right camera view + self.camera_views = camera_views + self.h5_name = "trajectory.h5" + + samples = list(pd.read_csv(data_path, header=None, delimiter=" ").values[:, 0]) + self.samples = samples + + def __getitem__(self, index): + path = self.samples[index] + + # -- keep trying to load videos until you find a valid sample + loaded_video = False + while not loaded_video: + try: + buffer, actions, states, extrinsics, indices = self.loadvideo_decord(path) + loaded_video = True + except Exception as e: + logger.info(f"Encountered exception when loading video {path=} {e=}") + loaded_video = False + index = np.random.randint(self.__len__()) + path = self.samples[index] + + return buffer, actions, states, extrinsics, indices + + def poses_to_diffs(self, poses): + xyz = poses[:, :3] # shape [T, 3] + thetas = poses[:, 3:6] # euler angles, shape [T, 3] + matrices = [Rotation.from_euler("xyz", theta, degrees=False).as_matrix() for theta in thetas] + xyz_diff = xyz[1:] - xyz[:-1] + angle_diff = [matrices[t + 1] @ matrices[t].T for t in range(len(matrices) - 1)] + angle_diff = [Rotation.from_matrix(mat).as_euler("xyz", degrees=False) for mat in angle_diff] + angle_diff = np.stack([d for d in angle_diff], axis=0) + closedness = poses[:, -1:] + closedness_delta = closedness[1:] - closedness[:-1] + return np.concatenate([xyz_diff, angle_diff, closedness_delta], axis=1) + + def transform_frame(self, poses, extrinsics): + gripper = poses[:, -1:] + poses = poses[:, :-1] + + def pose_to_transform(pose): + trans = pose[:3] # shape [3] + theta = pose[3:6] # euler angles, shape [3] + Rot = Rotation.from_euler("xyz", theta, degrees=False).as_matrix() + T = np.eye(4) + T[:3, :3] = Rot + T[:3, 3] = trans + return T + + def transform_to_pose(transform): + trans = transform[:3, 3] + Rot = transform[:3, :3] + angle = Rotation.from_matrix(Rot).as_euler("xyz", degrees=False) + return np.concatenate([trans, angle], axis=0) + + new_pose = [] + for p, e in zip(poses, extrinsics): + p_transform = pose_to_transform(p) + e_transform = pose_to_transform(e) + new_pose_transform = np.linalg.inv(e_transform) @ p_transform + new_pose += [transform_to_pose(new_pose_transform)] + new_pose = np.stack(new_pose, axis=0) + + return np.concatenate([new_pose, gripper], axis=1) + + def loadvideo_decord(self, path): + # -- load metadata + metadata = get_json(path) + if metadata is None: + raise Exception(f"No metadata for video {path=}") + + # -- load trajectory info + tpath = os.path.join(path, self.h5_name) + trajectory = h5py.File(tpath) + + # -- randomly sample a camera view + camera_view = self.camera_views[torch.randint(0, len(self.camera_views), (1,))] + mp4_name = metadata[camera_view].split("recordings/MP4/")[-1] + camera_name = mp4_name.split(".")[0] + extrinsics = trajectory["observation"]["camera_extrinsics"][f"{camera_name}_left"] + states = np.concatenate( + [ + np.array(trajectory["observation"]["robot_state"]["cartesian_position"]), + np.array(trajectory["observation"]["robot_state"]["gripper_position"])[:, None], + ], + axis=1, + ) # [T, 7] + vpath = os.path.join(path, "recordings/MP4", mp4_name) + vr = VideoReader(vpath, num_threads=-1, ctx=cpu(0)) + # -- + vfps = vr.get_avg_fps() + fpc = self.frames_per_clip + fps = self.fps if self.fps is not None else vfps + fstp = ceil(vfps / fps) + nframes = int(fpc * fstp) + vlen = len(vr) + + if vlen < nframes: + raise Exception(f"Video is too short {vpath=}, {nframes=}, {vlen=}") + + # sample a random window of nframes + ef = np.random.randint(nframes, vlen) + sf = ef - nframes + indices = np.arange(sf, sf + nframes, fstp).astype(np.int64) + # -- + states = states[indices, :][:: self.frameskip] + extrinsics = extrinsics[indices, :][:: self.frameskip] + if self.camera_frame: + states = self.transform_frame(states, extrinsics) + actions = self.poses_to_diffs(states) + # -- + vr.seek(0) # go to start of video before sampling frames + buffer = vr.get_batch(indices).asnumpy() + if self.transform is not None: + buffer = self.transform(buffer) + + return buffer, actions, states, extrinsics, indices + + def __len__(self): + return len(self.samples) diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/train.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/train.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e4fac1eb419e632c1a09b11ddc364c3932f647 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/train.py @@ -0,0 +1,524 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# + +import os + +# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESS +try: + # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE + # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE + # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE + # -- TO EACH PROCESS + os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"] +except Exception: + pass + +import copy +import gc +import random +import time + +import numpy as np +import torch +import torch.multiprocessing as mp +import torch.nn.functional as F +from torch.nn.parallel import DistributedDataParallel + +from app.vjepa_droid.droid import init_data +from app.vjepa_droid.transforms import make_transforms +from app.vjepa_droid.utils import init_opt, init_video_model, load_checkpoint, load_pretrained +from src.utils.distributed import init_distributed +from src.utils.logging import AverageMeter, CSVLogger, get_logger, gpu_timer + +# -- +log_timings = True +log_freq = 10 +CHECKPOINT_FREQ = 1 +GARBAGE_COLLECT_ITR_FREQ = 50 +# -- + +_GLOBAL_SEED = 0 +random.seed(_GLOBAL_SEED) +np.random.seed(_GLOBAL_SEED) +torch.manual_seed(_GLOBAL_SEED) +torch.backends.cudnn.benchmark = True + + +logger = get_logger(__name__, force=True) + + +def main(args, resume_preempt=False): + # ----------------------------------------------------------------------- # + # PASSED IN PARAMS FROM CONFIG FILE + # ----------------------------------------------------------------------- # + + # -- META + folder = args.get("folder") + cfgs_meta = args.get("meta") + r_file = cfgs_meta.get("resume_checkpoint", None) + p_file = cfgs_meta.get("pretrain_checkpoint", None) + load_predictor = cfgs_meta.get("load_predictor", False) + context_encoder_key = cfgs_meta.get("context_encoder_key", "encoder") + target_encoder_key = cfgs_meta.get("target_encoder_key", "target_encoder") + load_encoder = cfgs_meta.get("load_encoder", True) + seed = cfgs_meta.get("seed", _GLOBAL_SEED) + save_every_freq = cfgs_meta.get("save_every_freq", -1) + skip_batches = cfgs_meta.get("skip_batches", -1) + use_sdpa = cfgs_meta.get("use_sdpa", False) + sync_gc = cfgs_meta.get("sync_gc", False) + which_dtype = cfgs_meta.get("dtype") + logger.info(f"{which_dtype=}") + if which_dtype.lower() == "bfloat16": + dtype = torch.bfloat16 + mixed_precision = True + elif which_dtype.lower() == "float16": + dtype = torch.float16 + mixed_precision = True + else: + dtype = torch.float32 + mixed_precision = False + + # -- MODEL + cfgs_model = args.get("model") + compile_model = cfgs_model.get("compile_model", False) + use_activation_checkpointing = cfgs_model.get("use_activation_checkpointing", False) + model_name = cfgs_model.get("model_name") + pred_depth = cfgs_model.get("pred_depth") + pred_num_heads = cfgs_model.get("pred_num_heads", None) + pred_embed_dim = cfgs_model.get("pred_embed_dim") + pred_is_frame_causal = cfgs_model.get("pred_is_frame_causal", True) + uniform_power = cfgs_model.get("uniform_power", False) + use_rope = cfgs_model.get("use_rope", False) + use_silu = cfgs_model.get("use_silu", False) + use_pred_silu = cfgs_model.get("use_pred_silu", False) + wide_silu = cfgs_model.get("wide_silu", True) + use_extrinsics = cfgs_model.get("use_extrinsics", False) + + # -- DATA + cfgs_data = args.get("data") + datasets = cfgs_data.get("datasets", []) + dataset_path = datasets[0] + dataset_fpcs = cfgs_data.get("dataset_fpcs") + max_num_frames = max(dataset_fpcs) + camera_frame = cfgs_data.get("camera_frame", False) + camera_views = cfgs_data.get("camera_views", ["left_mp4_path"]) + stereo_view = cfgs_data.get("stereo_view", False) + batch_size = cfgs_data.get("batch_size") + tubelet_size = cfgs_data.get("tubelet_size") + fps = cfgs_data.get("fps") + crop_size = cfgs_data.get("crop_size", 256) + patch_size = cfgs_data.get("patch_size") + pin_mem = cfgs_data.get("pin_mem", False) + num_workers = cfgs_data.get("num_workers", 1) + persistent_workers = cfgs_data.get("persistent_workers", True) + + # -- DATA AUGS + cfgs_data_aug = args.get("data_aug") + horizontal_flip = cfgs_data_aug.get("horizontal_flip", False) + ar_range = cfgs_data_aug.get("random_resize_aspect_ratio", [3 / 4, 4 / 3]) + rr_scale = cfgs_data_aug.get("random_resize_scale", [0.3, 1.0]) + motion_shift = cfgs_data_aug.get("motion_shift", False) + reprob = cfgs_data_aug.get("reprob", 0.0) + use_aa = cfgs_data_aug.get("auto_augment", False) + + # -- LOSS + cfgs_loss = args.get("loss") + loss_exp = cfgs_loss.get("loss_exp") + normalize_reps = cfgs_loss.get("normalize_reps") + auto_steps = min(cfgs_loss.get("auto_steps", 1), max_num_frames) + # -- + tokens_per_frame = int((crop_size // patch_size) ** 2) + + # -- OPTIMIZATION + cfgs_opt = args.get("optimization") + ipe = cfgs_opt.get("ipe", None) + wd = float(cfgs_opt.get("weight_decay")) + final_wd = float(cfgs_opt.get("final_weight_decay")) + num_epochs = cfgs_opt.get("epochs") + anneal = cfgs_opt.get("anneal") + warmup = cfgs_opt.get("warmup") + start_lr = cfgs_opt.get("start_lr") + lr = cfgs_opt.get("lr") + final_lr = cfgs_opt.get("final_lr") + enc_lr_scale = cfgs_opt.get("enc_lr_scale", 1.0) + betas = cfgs_opt.get("betas", (0.9, 0.999)) + eps = cfgs_opt.get("eps", 1.0e-8) + # ----------------------------------------------------------------------- # + # ----------------------------------------------------------------------- # + + np.random.seed(seed) + torch.manual_seed(seed) + torch.backends.cudnn.benchmark = True + try: + mp.set_start_method("spawn") + except Exception: + pass + + # -- init torch distributed backend + world_size, rank = init_distributed() + logger.info(f"Initialized (rank/world-size) {rank}/{world_size}") + + # -- set device + if not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device("cuda:0") + torch.cuda.set_device(device) + + # -- log/checkpointing paths + log_file = os.path.join(folder, f"log_r{rank}.csv") + latest_path = os.path.join(folder, "latest.pt") + resume_path = os.path.join(folder, r_file) if r_file is not None else latest_path + if not os.path.exists(resume_path): + resume_path = None + + # -- make csv_logger + csv_logger = CSVLogger( + log_file, + ("%d", "epoch"), + ("%d", "itr"), + ("%.5f", "loss"), + ("%d", "iter-time(ms)"), + ("%d", "gpu-time(ms)"), + ("%d", "dataload-time(ms)"), + mode="+a", + ) + + # -- init model + encoder, predictor = init_video_model( + uniform_power=uniform_power, + device=device, + patch_size=patch_size, + max_num_frames=512, + tubelet_size=tubelet_size, + model_name=model_name, + crop_size=crop_size, + pred_depth=pred_depth, + pred_num_heads=pred_num_heads, + pred_embed_dim=pred_embed_dim, + action_embed_dim=7, + pred_is_frame_causal=pred_is_frame_causal, + use_extrinsics=use_extrinsics, + use_sdpa=use_sdpa, + use_silu=use_silu, + use_pred_silu=use_pred_silu, + wide_silu=wide_silu, + use_rope=use_rope, + use_activation_checkpointing=use_activation_checkpointing, + ) + target_encoder = copy.deepcopy(encoder) + + if compile_model: + logger.info("Compiling encoder, target_encoder, and predictor.") + torch._dynamo.config.optimize_ddp = False + encoder.compile() + target_encoder.compile() + predictor.compile() + + video_collator = torch.utils.data.default_collate + transform = make_transforms( + random_horizontal_flip=horizontal_flip, + random_resize_aspect_ratio=ar_range, + random_resize_scale=rr_scale, + reprob=reprob, + auto_augment=use_aa, + motion_shift=motion_shift, + crop_size=crop_size, + ) + + # -- init data-loaders/samplers + (unsupervised_loader, unsupervised_sampler) = init_data( + data_path=dataset_path, + batch_size=batch_size, + frames_per_clip=max_num_frames, + tubelet_size=1, + fps=fps, + camera_views=camera_views, + camera_frame=camera_frame, + stereo_view=stereo_view, + transform=transform, + collator=video_collator, + num_workers=num_workers, + world_size=world_size, + pin_mem=pin_mem, + persistent_workers=persistent_workers, + rank=rank, + ) + _dlen = len(unsupervised_loader) + if ipe is None: + ipe = _dlen + logger.info(f"iterations per epoch/dataset length: {ipe}/{_dlen}") + + # -- init optimizer and scheduler + optimizer, scaler, scheduler, wd_scheduler = init_opt( + encoder=encoder, + predictor=predictor, + wd=wd, + final_wd=final_wd, + start_lr=start_lr, + ref_lr=lr, + final_lr=final_lr, + enc_lr_scale=enc_lr_scale, + iterations_per_epoch=ipe, + anneal=anneal, + warmup=warmup, + num_epochs=num_epochs, + mixed_precision=mixed_precision, + betas=betas, + eps=eps, + ) + encoder = DistributedDataParallel(encoder, static_graph=True) + predictor = DistributedDataParallel(predictor, static_graph=False, find_unused_parameters=True) + target_encoder = DistributedDataParallel(target_encoder) + for p in target_encoder.parameters(): + p.requires_grad = False + + # -- looad pretrained weights + encoder, predictor, target_encoder = load_pretrained( + r_path=p_file, + encoder=encoder, + predictor=predictor, + context_encoder_key=context_encoder_key, + target_encoder_key=target_encoder_key, + target_encoder=target_encoder, + load_predictor=load_predictor, + load_encoder=load_encoder, + ) + + start_epoch = 0 + # -- load training checkpoint + if os.path.exists(latest_path): + ( + encoder, + predictor, + target_encoder, + optimizer, + scaler, + start_epoch, + ) = load_checkpoint( + r_path=resume_path, + encoder=encoder, + predictor=predictor, + target_encoder=target_encoder, + opt=optimizer, + scaler=scaler, + ) + for _ in range(start_epoch * ipe): + scheduler.step() + wd_scheduler.step() + + def save_checkpoint(epoch, path): + if rank != 0: + return + save_dict = { + "encoder": encoder.state_dict(), + "predictor": predictor.state_dict(), + "opt": optimizer.state_dict(), + "scaler": None if scaler is None else scaler.state_dict(), + "target_encoder": target_encoder.state_dict(), + "epoch": epoch, + "loss": loss_meter.avg, + "batch_size": batch_size, + "world_size": world_size, + "lr": lr, + } + try: + torch.save(save_dict, path) + except Exception as e: + logger.info(f"Encountered exception when saving checkpoint: {e}") + + logger.info("Initializing loader...") + unsupervised_sampler.set_epoch(start_epoch) + loader = iter(unsupervised_loader) + + if skip_batches > 0: + logger.info(f"Skip {skip_batches} batches") + # -- update distributed-data-loader epoch + + for itr in range(skip_batches): + if itr % 10 == 0: + logger.info(f"Skip {itr}/{skip_batches} batches") + try: + _ = next(loader) + except Exception: + loader = iter(unsupervised_loader) + _ = next(loader) + + if sync_gc: + gc.disable() + gc.collect() + + # -- TRAINING LOOP + for epoch in range(start_epoch, num_epochs): + logger.info("Epoch %d" % (epoch + 1)) + + loss_meter = AverageMeter() + jloss_meter = AverageMeter() + sloss_meter = AverageMeter() + iter_time_meter = AverageMeter() + gpu_time_meter = AverageMeter() + data_elapsed_time_meter = AverageMeter() + + for itr in range(ipe): + itr_start_time = time.time() + + iter_retries = 0 + iter_successful = False + while not iter_successful: + try: + sample = next(loader) + iter_successful = True + except StopIteration: + logger.info("Exhausted data loaders. Refreshing...") + unsupervised_sampler.set_epoch(epoch) + loader = iter(unsupervised_loader) + except Exception as e: + NUM_RETRIES = 5 + if iter_retries < NUM_RETRIES: + logger.warning(f"Encountered exception when loading data (num retries {iter_retries}):\n{e}") + iter_retries += 1 + time.sleep(5) + else: + logger.warning(f"Exceeded max retries ({NUM_RETRIES}) when loading data. Skipping batch.") + raise e + + def load_clips(): + clips = sample[0].to(device, non_blocking=True) # [B C T H W] + actions = sample[1].to(device, dtype=torch.float, non_blocking=True) # [B T-1 7] + states = sample[2].to(device, dtype=torch.float, non_blocking=True) # [B T 7] + extrinsics = sample[3].to(device, dtype=torch.float, non_blocking=True) # [B T 7] + return (clips, actions, states, extrinsics) + + clips, actions, states, extrinsics = load_clips() + data_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 + + if sync_gc and (itr + 1) % GARBAGE_COLLECT_ITR_FREQ == 0: + logger.info("Running garbage collection...") + gc.collect() + + def train_step(): + _new_lr = scheduler.step() + _new_wd = wd_scheduler.step() + # -- + + def forward_target(c): + with torch.no_grad(): + c = c.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1) + h = target_encoder(c) + h = h.view(batch_size, max_num_frames, -1, h.size(-1)).flatten(1, 2) + if normalize_reps: + h = F.layer_norm(h, (h.size(-1),)) + return h + + def forward_predictions(z): + + def _step_predictor(_z, _a, _s, _e): + _z = predictor(_z, _a, _s, _e) + if normalize_reps: + _z = F.layer_norm(_z, (_z.size(-1),)) + return _z + + # -- one step of predictor with teacher forcing + _z, _a, _s, _e = z[:, :-tokens_per_frame], actions, states[:, :-1], extrinsics[:, :-1] + z_tf = _step_predictor(_z, _a, _s, _e) + + # -- full auto-regressive rollouts of predictor + _z = torch.cat([z[:, : tokens_per_frame], z_tf[:, : tokens_per_frame]], dim=1) + for n in range(1, auto_steps): + _a, _s, _e = actions[:, : n + 1], states[:, : n + 1], extrinsics[:, : n + 1] + _z_nxt = _step_predictor(_z, _a, _s, _e)[:, -tokens_per_frame:] + _z = torch.cat([_z, _z_nxt], dim=1) + z_ar = _z[:, tokens_per_frame:] + + return z_tf, z_ar + + def loss_fn(z, h): + _h = h[:, tokens_per_frame : z.size(1) + tokens_per_frame] + return torch.mean(torch.abs(z - _h) ** loss_exp) / loss_exp + + # Step 1. Forward + with torch.cuda.amp.autocast(dtype=dtype, enabled=mixed_precision): + h = forward_target(clips) + z_tf, z_ar = forward_predictions(h) + jloss = loss_fn(z_tf, h) + sloss = loss_fn(z_ar, h) + loss = jloss + sloss + + # Step 2. Backward & step + if mixed_precision: + scaler.scale(loss).backward() + scaler.unscale_(optimizer) + else: + loss.backward() + if mixed_precision: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + optimizer.zero_grad() + + return ( + float(loss), + float(jloss), + float(sloss), + _new_lr, + _new_wd, + ) + + ( + loss, + jloss, + sloss, + _new_lr, + _new_wd, + ), gpu_etime_ms = gpu_timer(train_step) + iter_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 + loss_meter.update(loss) + jloss_meter.update(jloss) + sloss_meter.update(sloss) + iter_time_meter.update(iter_elapsed_time_ms) + gpu_time_meter.update(gpu_etime_ms) + data_elapsed_time_meter.update(data_elapsed_time_ms) + + # -- Logging + def log_stats(): + csv_logger.log(epoch + 1, itr, loss, iter_elapsed_time_ms, gpu_etime_ms, data_elapsed_time_ms) + if (itr % log_freq == 0) or (itr == ipe - 1) or np.isnan(loss) or np.isinf(loss): + logger.info( + "[%d, %5d] loss: %.3f [%.2f, %.2f] " + "[wd: %.2e] [lr: %.2e] " + "[mem: %.2e] " + "[iter: %.1f ms] " + "[gpu: %.1f ms] " + "[data: %.1f ms]" + % ( + epoch + 1, + itr, + loss_meter.avg, + jloss_meter.avg, + sloss_meter.avg, + _new_wd, + _new_lr, + torch.cuda.max_memory_allocated() / 1024.0**2, + iter_time_meter.avg, + gpu_time_meter.avg, + data_elapsed_time_meter.avg, + ) + ) + + log_stats() + assert not np.isnan(loss), "loss is nan" + + # -- Save Checkpoint + logger.info("avg. loss %.3f" % loss_meter.avg) + # -- Save Last + if epoch % CHECKPOINT_FREQ == 0 or epoch == (num_epochs - 1): + save_checkpoint(epoch + 1, latest_path) + if save_every_freq > 0 and epoch % save_every_freq == 0: + save_every_file = f"e{epoch}.pt" + save_every_path = os.path.join(folder, save_every_file) + save_checkpoint(epoch + 1, save_every_path) diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/transforms.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..ac73701bbc73189d98b1afd5070de970c444ff56 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/transforms.py @@ -0,0 +1,156 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# + +import torch +import torchvision.transforms as transforms + +import src.datasets.utils.video.transforms as video_transforms +from src.datasets.utils.video.randerase import RandomErasing + + +def make_transforms( + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), +): + + _frames_augmentation = VideoTransform( + random_horizontal_flip=random_horizontal_flip, + random_resize_aspect_ratio=random_resize_aspect_ratio, + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + crop_size=crop_size, + normalize=normalize, + ) + return _frames_augmentation + + +class VideoTransform(object): + + def __init__( + self, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + ): + + self.random_horizontal_flip = random_horizontal_flip + self.random_resize_aspect_ratio = random_resize_aspect_ratio + self.random_resize_scale = random_resize_scale + self.auto_augment = auto_augment + self.motion_shift = motion_shift + self.crop_size = crop_size + self.mean = torch.tensor(normalize[0], dtype=torch.float32) + self.std = torch.tensor(normalize[1], dtype=torch.float32) + if not self.auto_augment: + # Without auto-augment, PIL and tensor conversions simply scale uint8 space by 255. + self.mean *= 255.0 + self.std *= 255.0 + + self.autoaug_transform = video_transforms.create_random_augment( + input_size=(crop_size, crop_size), + # auto_augment="rand-m4-n4-w1-mstd0.5-inc1", + auto_augment="rand-m7-n4-mstd0.5-inc1", + interpolation="bicubic", + ) + + self.spatial_transform = ( + video_transforms.random_resized_crop_with_shift if motion_shift else video_transforms.random_resized_crop + ) + + self.reprob = reprob + self.erase_transform = RandomErasing( + reprob, + mode="pixel", + max_count=1, + num_splits=1, + device="cpu", + ) + + def __call__(self, buffer): + + if self.auto_augment: + buffer = [transforms.ToPILImage()(frame) for frame in buffer] + buffer = self.autoaug_transform(buffer) + buffer = [transforms.ToTensor()(img) for img in buffer] + buffer = torch.stack(buffer) # T C H W + buffer = buffer.permute(0, 2, 3, 1) # T H W C + elif torch.is_tensor(buffer): + # TODO: ensure input is always a tensor? + buffer = buffer.to(torch.float32) + else: + buffer = torch.tensor(buffer, dtype=torch.float32) + + buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W + + buffer = self.spatial_transform( + images=buffer, + target_height=self.crop_size, + target_width=self.crop_size, + scale=self.random_resize_scale, + ratio=self.random_resize_aspect_ratio, + ) + if self.random_horizontal_flip: + buffer, _ = video_transforms.horizontal_flip(0.5, buffer) + + buffer = _tensor_normalize_inplace(buffer, self.mean, self.std) + if self.reprob > 0: + buffer = buffer.permute(1, 0, 2, 3) + buffer = self.erase_transform(buffer) + buffer = buffer.permute(1, 0, 2, 3) + + return buffer + + +def tensor_normalize(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize. + mean (tensor or list): mean value to subtract. + std (tensor or list): std to divide. + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + tensor = tensor / 255.0 + if type(mean) == list: + mean = torch.tensor(mean) + if type(std) == list: + std = torch.tensor(std) + tensor = tensor - mean + tensor = tensor / std + return tensor + + +def _tensor_normalize_inplace(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize (with dimensions C, T, H, W). + mean (tensor): mean value to subtract (in 0 to 255 floats). + std (tensor): std to divide (in 0 to 255 floats). + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + + C, T, H, W = tensor.shape + tensor = tensor.view(C, -1).permute(1, 0) # Make C the last dimension + tensor.sub_(mean).div_(std) + tensor = tensor.permute(1, 0).view(C, T, H, W) # Put C back in front + return tensor diff --git a/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/utils.py b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..50d014a0116748030000d803437e502938ea38ce --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/app/vjepa_droid/utils.py @@ -0,0 +1,253 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +# + +import logging +import sys + +import torch + +import src.models.ac_predictor as vit_ac_pred +import src.models.vision_transformer as video_vit +from src.utils.checkpoint_loader import robust_checkpoint_loader +from src.utils.schedulers import CosineWDSchedule, WSDSchedule + +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +logger = logging.getLogger() + + +def load_pretrained( + r_path, + encoder=None, + predictor=None, + target_encoder=None, + context_encoder_key="encoder", + target_encoder_key="target_encoder", + load_predictor=False, + load_encoder=True, +): + logger.info(f"Loading pretrained model from {r_path}") + checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) + + epoch = checkpoint["epoch"] + + if load_encoder: + # -- loading encoder + pretrained_dict = checkpoint[context_encoder_key] + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + msg = encoder.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained encoder from epoch {epoch} with msg: {msg}") + + if load_predictor: + # -- loading predictor + pretrained_dict = checkpoint["predictor"] + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + msg = predictor.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained predictor from epoch {epoch} with msg: {msg}") + + # -- loading target_encoder + if load_encoder: + if target_encoder is not None: + print(list(checkpoint.keys())) + pretrained_dict = checkpoint[target_encoder_key] + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + msg = target_encoder.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained target encoder from epoch {epoch} with msg: {msg}") + + del checkpoint + + return ( + encoder, + predictor, + target_encoder, + ) + + +def load_checkpoint( + r_path, + encoder, + predictor, + target_encoder, + opt=None, + scaler=None, + replace_kw=["backbone."], +): + logger.info(f"Loading checkpoint from {r_path}") + checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) + + epoch = checkpoint["epoch"] + + # -- loading encoder + pretrained_dict = checkpoint["encoder"] + for kw in replace_kw: + pretrained_dict = {k.replace(kw, ""): v for k, v in pretrained_dict.items()} + msg = encoder.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained encoder from epoch {epoch} with msg: {msg}") + + # -- loading predictor + pretrained_dict = checkpoint["predictor"] + for kw in replace_kw: + pretrained_dict = {k.replace(kw, ""): v for k, v in pretrained_dict.items()} + msg = predictor.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained predictor from epoch {epoch} with msg: {msg}") + + # -- loading target_encoder + if target_encoder is not None: + print(list(checkpoint.keys())) + pretrained_dict = checkpoint["target_encoder"] + for kw in replace_kw: + pretrained_dict = {k.replace(kw, ""): v for k, v in pretrained_dict.items()} + msg = target_encoder.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained target encoder from epoch {epoch} with msg: {msg}") + + # -- loading optimizer + if opt is not None: + opt.load_state_dict(checkpoint["opt"]) + + if scaler is not None: + scaler.load_state_dict(checkpoint["scaler"]) + + logger.info(f"loaded optimizers from epoch {epoch}") + logger.info(f"read-path: {r_path}") + del checkpoint + + return ( + encoder, + predictor, + target_encoder, + opt, + scaler, + epoch, + ) + + +def init_video_model( + device, + patch_size=16, + max_num_frames=16, + tubelet_size=2, + model_name="vit_base", + crop_size=224, + pred_depth=6, + pred_num_heads=None, + pred_embed_dim=384, + uniform_power=False, + use_sdpa=False, + use_rope=False, + use_silu=False, + use_pred_silu=False, + wide_silu=False, + pred_is_frame_causal=True, + use_activation_checkpointing=False, + return_all_tokens=False, + action_embed_dim=7, + use_extrinsics=False, + old_pred=False, +): + encoder = video_vit.__dict__[model_name]( + img_size=crop_size, + patch_size=patch_size, + num_frames=max_num_frames, + tubelet_size=tubelet_size, + uniform_power=uniform_power, + use_sdpa=use_sdpa, + use_silu=use_silu, + wide_silu=wide_silu, + use_activation_checkpointing=use_activation_checkpointing, + use_rope=use_rope, + ) + + predictor = vit_ac_pred.__dict__["vit_ac_predictor"]( + img_size=crop_size, + patch_size=patch_size, + num_frames=max_num_frames, + tubelet_size=tubelet_size, + embed_dim=encoder.embed_dim, + predictor_embed_dim=pred_embed_dim, + action_embed_dim=action_embed_dim, + depth=pred_depth, + is_frame_causal=pred_is_frame_causal, + num_heads=encoder.num_heads if pred_num_heads is None else pred_num_heads, + uniform_power=uniform_power, + use_rope=use_rope, + use_sdpa=use_sdpa, + use_silu=use_pred_silu, + wide_silu=wide_silu, + use_extrinsics=use_extrinsics, + use_activation_checkpointing=use_activation_checkpointing, + ) + + encoder.to(device) + predictor.to(device) + logger.info(encoder) + logger.info(predictor) + + def count_parameters(model): + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + logger.info(f"Encoder number of parameters: {count_parameters(encoder)}") + logger.info(f"Predictor number of parameters: {count_parameters(predictor)}") + + return encoder, predictor + + +def init_opt( + encoder, + predictor, + iterations_per_epoch, + start_lr, + ref_lr, + warmup, + anneal, + num_epochs, + wd=1e-6, + final_wd=1e-6, + final_lr=0.0, + mixed_precision=False, + betas=(0.9, 0.999), + eps=1e-8, + zero_init_bias_wd=True, + enc_lr_scale=1.0, +): + param_groups = [ + { + "params": (p for n, p in encoder.named_parameters() if ("bias" not in n) and (len(p.shape) != 1)), + "lr_scale": enc_lr_scale, + }, + { + "params": (p for n, p in predictor.named_parameters() if ("bias" not in n) and (len(p.shape) != 1)), + }, + { + "params": (p for n, p in encoder.named_parameters() if ("bias" in n) or (len(p.shape) == 1)), + "WD_exclude": zero_init_bias_wd, + "weight_decay": 0, + "lr_scale": enc_lr_scale, + }, + { + "params": (p for n, p in predictor.named_parameters() if ("bias" in n) or (len(p.shape) == 1)), + "WD_exclude": zero_init_bias_wd, + "weight_decay": 0, + }, + ] + + optimizer = torch.optim.AdamW(param_groups, betas=betas, eps=eps) + scheduler = WSDSchedule( + optimizer, + warmup_steps=int(warmup * iterations_per_epoch), + anneal_steps=int(anneal * iterations_per_epoch), + start_lr=start_lr, + ref_lr=ref_lr, + final_lr=final_lr, + T_max=int(num_epochs * iterations_per_epoch), + ) + wd_scheduler = CosineWDSchedule( + optimizer, + ref_wd=wd, + final_wd=final_wd, + T_max=int(num_epochs * iterations_per_epoch), + ) + scaler = torch.cuda.amp.GradScaler() if mixed_precision else None + return optimizer, scaler, scheduler, wd_scheduler diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/coin.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/coin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5534f7c7d1fd85819b659aa992ca6b077149ee09 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/coin.yaml @@ -0,0 +1,163 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitg-384/coin +mem_per_gpu: 220G +nodes: 16 +resume_checkpoint: true +tag: coin-vitg16-384-16x8x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_folder/COIN/train_paths.csv + dataset_val: /your_data_folder/COIN/val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 180 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cd0475f1a223a615f9724f09bd32f1d8d57f0ee0 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/diving48.yaml @@ -0,0 +1,61 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitg16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitg-384/diving48 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [24, 29, 34, 39] + pretrain_kwargs: + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dac5d4cbb1304ec12cb7a6abf06316f06b85e9e4 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/ek100.yaml @@ -0,0 +1,196 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitg16-384 +eval_name: action_anticipation_frozen +folder: /your_folder/evals/vitg-384/ek100 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + # e.g. /home/username/EPIC-KITCHENS + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 384 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 12 + num_heads: 12 + predictor_embed_dim: 384 + num_mask_tokens: 10 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/in1k.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/in1k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..99513dae801b8bf5047cd985d6ba6c8941a319e5 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/in1k.yaml @@ -0,0 +1,162 @@ +cpus_per_task: 16 +eval_name: image_classification_frozen +folder: /your_folder/evals/vitg-384/in1k +mem_per_gpu: 220G +nodes: 16 +resume_checkpoint: true +tag: in1k-vitg16-384-18f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_name: ImageNet + num_classes: 1000 + root_path: /your_data_path/ImageNet_FullSize/240712/061417/ + resolution: 384 + optimization: + batch_size: 8 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + num_epochs: 20 + use_bfloat16: true +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.image_classification_frozen.modelcustom.vit_encoder + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + img_as_video_nframes: 18 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/jester.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/jester.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fe708cd128708ae2def30e91ad65a0750f428df --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/jester.yaml @@ -0,0 +1,61 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: jester-vitg16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitg-384/jester +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/Jester/annotations/jester_train_paths.csv + dataset_val: /your_data_dir/Jester/annotations/jester_validation_paths.csv + num_classes: 27 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [24, 29, 34, 39] + pretrain_kwargs: + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/k400.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/k400.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d248b384fba1533a49267c32f592e4887dd717d --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/k400.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitg-384/k400 +mem_per_gpu: 220G +nodes: 32 +num_workers: 8 +resume_checkpoint: true +tag: k400-vitg16-384-16x8x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/k400_train_paths.csv + dataset_val: /your_data_path/k400_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 400 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..727a4475f4147bc4b2ac3f224e475990652a4054 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitg-384/ssv2.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitg-384/ssv2 +mem_per_gpu: 220G +nodes: 16 +num_workers: 8 +resume_checkpoint: true +tag: ssv2-vitg16-384-64x2x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 2 + frames_per_clip: 64 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 2 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/coin.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/coin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8339558b8a618d7a73954a852288b81ca2b13f3e --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/coin.yaml @@ -0,0 +1,163 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitl/coin +mem_per_gpu: 220G +nodes: 8 +resume_checkpoint: true +tag: coin-vitl16-384-16x8x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_folder/COIN/train_paths.csv + dataset_val: /your_data_folder/COIN/val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 180 + num_segments: 8 + num_views_per_segment: 3 + resolution: 256 + optimization: + batch_size: 2 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..372dd0c2bd4be47c8dadf5891e98a218d6e718de --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/diving48.yaml @@ -0,0 +1,61 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitl16-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitl/diving48 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 256 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [17, 19, 21, 23] + pretrain_kwargs: + encoder: + model_name: vit_large + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..60fdfe92a58e7938868a8962e3c70bd9a2e44f67 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/ek100.yaml @@ -0,0 +1,196 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitl16 +eval_name: action_anticipation_frozen +folder: /your_folder/evals/vitl/ek100 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + # e.g. /home/username/EPIC-KITCHENS + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 256 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + encoder: + model_name: vit_large + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 12 + num_heads: 12 + predictor_embed_dim: 384 + num_mask_tokens: 10 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/in1k.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/in1k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..961a3913fa4d5e577a25c0c1105a839b907ddf6c --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/in1k.yaml @@ -0,0 +1,162 @@ +cpus_per_task: 16 +eval_name: image_classification_frozen +folder: /your_folder/evals/vitl/in1k +mem_per_gpu: 220G +nodes: 8 +resume_checkpoint: true +tag: in1k-vitl16-384-18f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_name: ImageNet + num_classes: 1000 + root_path: /your_data_path/ImageNet_FullSize/240712/061417/ + resolution: 256 + optimization: + batch_size: 16 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + num_epochs: 20 + use_bfloat16: true +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.image_classification_frozen.modelcustom.vit_encoder + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + img_as_video_nframes: 16 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/jester.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/jester.yaml new file mode 100644 index 0000000000000000000000000000000000000000..df9ed517c0292cbf48b0cbe172f2e683a7239c59 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/jester.yaml @@ -0,0 +1,61 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: jester-vitl16-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitl/jester +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/Jester/annotations/jester_train_paths.csv + dataset_val: /your_data_dir/Jester/annotations/jester_validation_paths.csv + num_classes: 27 + resolution: 256 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [17, 19, 21, 23] + pretrain_kwargs: + encoder: + model_name: vit_large + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/k400.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/k400.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51874edceacc4c6e98ee18a70efc43bd6bc4e0b6 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/k400.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitl/k400 +mem_per_gpu: 220G +nodes: 8 +num_workers: 8 +resume_checkpoint: true +tag: k400-vitl16-16x8x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/k400_train_paths.csv + dataset_val: /your_data_path/k400_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 400 + num_segments: 8 + num_views_per_segment: 3 + resolution: 256 + optimization: + batch_size: 4 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e8c8634ad8a7c805487a9dfaf215b54640c8a35 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval/vitl/ssv2.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitl/ssv2 +mem_per_gpu: 220G +nodes: 8 +max_workers: 8 +resume_checkpoint: true +tag: ssv2-vitl16-16x2x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 256 + optimization: + batch_size: 4 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/coin.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/coin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdd89dece95ce5e197742dbfb1877b0cab386764 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/coin.yaml @@ -0,0 +1,163 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitg-384/coin +mem_per_gpu: 220G +nodes: 16 +resume_checkpoint: true +tag: coin-vitg16-384-16x8x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_folder/COIN/train_paths.csv + dataset_val: /your_data_folder/COIN/val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 180 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitg_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac68b44abae89a81e9675391d18e596d03f77527 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/diving48.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitg16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitg-384/diving48 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitg_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [9, 19, 29, 39] + pretrain_kwargs: + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..faa319137ee9e3d8dd53bcc029b2d4db7eef05bb --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/ek100.yaml @@ -0,0 +1,199 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitg16-384 +eval_name: action_anticipation_frozen +folder: /your_folder/evals_2_1/vitg-384/ek100 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + # e.g. /home/username/EPIC-KITCHENS + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 384 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitg_384.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + use_v2_1: true + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 24 + num_heads: 12 + predictor_embed_dim: 384 + num_mask_tokens: 8 + img_temporal_dim_size: 1 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/in1k.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/in1k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..73e4321d682d236e96b983d58b58591f5e616622 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/in1k.yaml @@ -0,0 +1,162 @@ +cpus_per_task: 16 +eval_name: image_classification_frozen +folder: /your_folder/evals_2_1/vitg-384/in1k +mem_per_gpu: 220G +nodes: 16 +resume_checkpoint: true +tag: in1k-vitg16-384-18f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_name: ImageNet + num_classes: 1000 + root_path: /your_data_path/ImageNet_FullSize/240712/061417/ + resolution: 384 + optimization: + batch_size: 8 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + num_epochs: 20 + use_bfloat16: true +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitg_384.pt + module_name: evals.image_classification_frozen.modelcustom.vit_encoder + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + img_as_video_nframes: 18 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/jester.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/jester.yaml new file mode 100644 index 0000000000000000000000000000000000000000..78cb2aac1b5297ce009cd9b9e0f1a8e130140703 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/jester.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: jester-vitg16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitg-384/jester +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/Jester/annotations/jester_train_paths.csv + dataset_val: /your_data_dir/Jester/annotations/jester_validation_paths.csv + num_classes: 27 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitg_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [9, 19, 29, 39] + pretrain_kwargs: + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/k400.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/k400.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3cc6677f1101198200b2f7172592dee842553411 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/k400.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitg-384/k400 +mem_per_gpu: 220G +nodes: 32 +num_workers: 8 +resume_checkpoint: true +tag: k400-vitg16-384-16x8x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/k400_train_paths.csv + dataset_val: /your_data_path/k400_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 400 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitg_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..97c85f24a1686b03f8025d9f162d1657e1cdd48e --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_giant-384/ssv2.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitg-384/ssv2 +mem_per_gpu: 220G +nodes: 16 +num_workers: 8 +resume_checkpoint: true +tag: ssv2-vitg16-384-64x2x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 2 + frames_per_clip: 64 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitg_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/coin.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/coin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..31195de4e389f9a62d768d4c0ff2c287099a9da3 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/coin.yaml @@ -0,0 +1,163 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitG-384/coin +mem_per_gpu: 220G +nodes: 16 +resume_checkpoint: true +tag: coin-vitG16-384-16x8x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_folder/COIN/train_paths.csv + dataset_val: /your_data_folder/COIN/val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 180 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_gigantic_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..21d628628652aa761cf8ee435a856d986c919638 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/diving48.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitG16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitG-384/diving48 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [11, 23, 37, 47] + pretrain_kwargs: + encoder: + model_name: vit_gigantic_xformers + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f51c8a5d2775b98849b4919dfcc6d2dd618c40ca --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/ek100.yaml @@ -0,0 +1,199 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitG16-384 +eval_name: action_anticipation_frozen +folder: /your_folder/evals_2_1/vitG-384/ek100 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + # e.g. /home/username/EPIC-KITCHENS + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 384 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitG_384.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + use_v2_1: true + encoder: + model_name: vit_gigantic_xformers + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 24 + num_heads: 12 + predictor_embed_dim: 384 + num_mask_tokens: 8 + img_temporal_dim_size: 1 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/in1k.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/in1k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..43c69869499486e636c5cae3d44b85930d30c110 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/in1k.yaml @@ -0,0 +1,162 @@ +cpus_per_task: 16 +eval_name: image_classification_frozen +folder: /your_folder/evals_2_1/vitG-384/in1k +mem_per_gpu: 220G +nodes: 16 +resume_checkpoint: true +tag: in1k-vitG16-384-18f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_name: ImageNet + num_classes: 1000 + root_path: /your_data_path/ImageNet_FullSize/240712/061417/ + resolution: 384 + optimization: + batch_size: 8 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + num_epochs: 20 + use_bfloat16: true +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitG_384.pt + module_name: evals.image_classification_frozen.modelcustom.vit_encoder + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_gigantic_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + img_as_video_nframes: 18 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/jester.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/jester.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fd38a3946a1afc08d844bec10c3654bc27c0f4f6 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/jester.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: jester-vitG16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitG-384/jester +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/Jester/annotations/jester_train_paths.csv + dataset_val: /your_data_dir/Jester/annotations/jester_validation_paths.csv + num_classes: 27 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [11, 23, 37, 47] + pretrain_kwargs: + encoder: + model_name: vit_gigantic_xformers + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/k400.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/k400.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e2563151a030f3baa2fa37d4cf9b5b7125031af --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/k400.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitG-384/k400 +mem_per_gpu: 220G +nodes: 32 +num_workers: 8 +resume_checkpoint: true +tag: k400-vitG16-384-16x8x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/k400_train_paths.csv + dataset_val: /your_data_path/k400_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 400 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_gigantic_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..206dfdd5a9768aadc59e2cc2413d71876974ad0b --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vit_gigantic-384/ssv2.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitG-384/ssv2 +mem_per_gpu: 220G +nodes: 16 +num_workers: 8 +resume_checkpoint: true +tag: ssv2-vitG16-384-64x2x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 2 + frames_per_clip: 64 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 1 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: 1 + model_name: vit_gigantic_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/coin.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/coin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e30343d26a8262d21541621e21fdb608d25cf12c --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/coin.yaml @@ -0,0 +1,163 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitb-384/coin +mem_per_gpu: 220G +nodes: 8 +resume_checkpoint: true +tag: coin-vitb16-384-16x8x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_folder/COIN/train_paths.csv + dataset_val: /your_data_folder/COIN/val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 180 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 2 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitb_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_base + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4d0f9aceb1c451bc558daa3669b0fc599a53c497 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/diving48.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitb16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitb-384/diving48 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitb_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [2, 5, 8, 11] + pretrain_kwargs: + encoder: + model_name: vit_base + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c445e1937ebc8d564a99fc7edc46e93260b0d2a --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/ek100.yaml @@ -0,0 +1,202 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitb16-384 +eval_name: action_anticipation_frozen +folder: /your_folder/evals_2_1/vitb-384/ek100 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + # e.g. /home/username/EPIC-KITCHENS + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 384 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitb_dist_vitG_384.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + use_v2_1: true + encoder: + model_name: vit_base + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 12 + num_heads: 12 + predictor_embed_dim: 384 + teacher_embed_dim: 1664 + num_mask_tokens: 8 + n_output_distillation: 1 + return_all_tokens: true + img_temporal_dim_size: 1 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/in1k.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/in1k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..049e332f3fe447b3e4b2f389b88d5e2632f1d886 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/in1k.yaml @@ -0,0 +1,162 @@ +cpus_per_task: 16 +eval_name: image_classification_frozen +folder: /your_folder/evals_2_1/vitb-384/in1k +mem_per_gpu: 220G +nodes: 8 +resume_checkpoint: true +tag: in1k-vitb16-384-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_name: ImageNet + num_classes: 1000 + root_path: /your_data_path/ImageNet_FullSize/240712/061417/ + resolution: 384 + optimization: + batch_size: 16 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + num_epochs: 20 + use_bfloat16: true +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitb_dist_vitG_384.pt + module_name: evals.image_classification_frozen.modelcustom.vit_encoder + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_base + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + img_as_video_nframes: 16 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/jester.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/jester.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5958a266f9a0b92ab56ed3396fe850954514abc4 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/jester.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: jester-vitb16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitb-384/jester +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/Jester/annotations/jester_train_paths.csv + dataset_val: /your_data_dir/Jester/annotations/jester_validation_paths.csv + num_classes: 27 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitb_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [2, 5, 8, 11] + pretrain_kwargs: + encoder: + model_name: vit_base + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/k400.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/k400.yaml new file mode 100644 index 0000000000000000000000000000000000000000..da3f5128904143d6a0ce57631bac89ab6ac656c6 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/k400.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitb-384/k400 +mem_per_gpu: 220G +nodes: 8 +num_workers: 8 +resume_checkpoint: true +tag: k400-vitb16-384-16x8x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/k400_train_paths.csv + dataset_val: /your_data_path/k400_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 400 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 4 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitb_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_base + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..66aebaaedb177c0341dda03216cf65023aa2c187 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitb-384/ssv2.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitb-384/ssv2 +mem_per_gpu: 220G +nodes: 8 +max_workers: 8 +resume_checkpoint: true +tag: ssv2-vitb16-384-16x2x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 4 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitb_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_base + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/coin.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/coin.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4e6861390687d3605d4de568ceb8371dceb28a1 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/coin.yaml @@ -0,0 +1,163 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitl-384/coin +mem_per_gpu: 220G +nodes: 8 +resume_checkpoint: true +tag: coin-vitl16-384-16x8x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_folder/COIN/train_paths.csv + dataset_val: /your_data_folder/COIN/val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 180 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 2 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitl_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..144846bcab256f97922bb6ac9130d8bd6a4b7a75 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/diving48.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitl16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitl-384/diving48 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitl_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [5, 11, 17, 23] + pretrain_kwargs: + encoder: + model_name: vit_large + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c57e4126f7d6b5fef5234f6c74e181045fee4b9d --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/ek100.yaml @@ -0,0 +1,202 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitl16-384 +eval_name: action_anticipation_frozen +folder: /your_folder/evals_2_1/vitl-384/ek100 +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + # e.g. /home/username/EPIC-KITCHENS + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 384 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.0001 + final_weight_decay: 0.0001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.001 + final_weight_decay: 0.001 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.01 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. + + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.1 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitl_dist_vitG_384.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + use_v2_1: true + encoder: + model_name: vit_large + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 12 + num_heads: 12 + predictor_embed_dim: 384 + teacher_embed_dim: 1664 + num_mask_tokens: 8 + n_output_distillation: 1 + return_all_tokens: true + img_temporal_dim_size: 1 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/in1k.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/in1k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..408d466ae34e8419e7a3ddd4ca9f292e05b9554a --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/in1k.yaml @@ -0,0 +1,162 @@ +cpus_per_task: 16 +eval_name: image_classification_frozen +folder: /your_folder/evals_2_1/vitl-384/in1k +mem_per_gpu: 220G +nodes: 8 +resume_checkpoint: true +tag: in1k-vitl16-384-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_name: ImageNet + num_classes: 1000 + root_path: /your_data_path/ImageNet_FullSize/240712/061417/ + resolution: 384 + optimization: + batch_size: 16 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0005 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.001 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.0015 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + - final_lr: 0.0 + final_weight_decay: 0.008 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.008 + - final_lr: 0.0 + final_weight_decay: 0.004 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.004 + - final_lr: 0.0 + final_weight_decay: 0.002 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.002 + - final_lr: 0.0 + final_weight_decay: 0.001 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.001 + - final_lr: 0.0 + final_weight_decay: 0.0005 + lr: 0.002 + start_lr: 0.0002 + warmup: 5 + weight_decay: 0.0005 + num_epochs: 20 + use_bfloat16: true +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitl_dist_vitG_384.pt + module_name: evals.image_classification_frozen.modelcustom.vit_encoder + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + img_as_video_nframes: 16 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/jester.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/jester.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e00ca60782a1eb6984c8d2e200510f210783a4b1 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/jester.yaml @@ -0,0 +1,62 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: jester-vitl16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitl-384/jester +resume_checkpoint: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/Jester/annotations/jester_train_paths.csv + dataset_val: /your_data_dir/Jester/annotations/jester_validation_paths.csv + num_classes: 27 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + final_lr: 0.0 + warmup: 0. + - weight_decay: 0.8 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + final_lr: 0.0 + warmup: 0. +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitl_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [5, 11, 17, 23] + pretrain_kwargs: + encoder: + model_name: vit_large + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/k400.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/k400.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cd8bd672095b66ba4af5040458740e6ef990610 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/k400.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitl-384/k400 +mem_per_gpu: 220G +nodes: 8 +num_workers: 8 +resume_checkpoint: true +tag: k400-vitl16-384-16x8x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/k400_train_paths.csv + dataset_val: /your_data_path/k400_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 400 + num_segments: 8 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 4 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitl_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..38056e1d13005afd24620aa20b5cd4f180bbda42 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/eval_2_1/vitl-384/ssv2.yaml @@ -0,0 +1,164 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals_2_1/vitl-384/ssv2 +mem_per_gpu: 220G +nodes: 8 +max_workers: 8 +resume_checkpoint: true +tag: ssv2-vitl16-384-16x2x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 4 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.01 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.01 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.1 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.1 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.4 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.4 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.005 + start_lr: 0.005 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.003 + start_lr: 0.003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.001 + start_lr: 0.001 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0003 + start_lr: 0.0003 + warmup: 0.0 + weight_decay: 0.8 + - final_lr: 0.0 + final_weight_decay: 0.8 + lr: 0.0001 + start_lr: 0.0001 + warmup: 0.0 + weight_decay: 0.8 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_1_checkpoints/vjepa2_1_vitl_dist_vitG_384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: ema_encoder + img_temporal_dim_size: 1 + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0a47cb7d9821824039a59ea97ad8ae63c27bac5 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/diving48.yaml @@ -0,0 +1,50 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitg16-384-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitg-384/diving48 +resume_checkpoint: true +val_only: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 384 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.0 + final_weight_decay: 0.0 + lr: 0.0 + start_lr: 0.0 + final_lr: 0.0 + warmup: 0.0 +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [24, 29, 34, 39] + pretrain_kwargs: + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42aa1e5b206120a22ad65be2e9c0f5d9053f104b --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/ek100.yaml @@ -0,0 +1,79 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitg16-384 +eval_name: action_anticipation_frozen +folder: /your_folder/evals/vitg-384/ek100 +resume_checkpoint: true +val_only: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 384 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0 + final_weight_decay: 0.0 + lr: 0.0 + start_lr: 0.0 + final_lr: 0.0 + warmup: 0.0 +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + encoder: + model_name: vit_giant_xformers + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 12 + num_heads: 12 + predictor_embed_dim: 384 + num_mask_tokens: 10 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4603b8afb238b853caf1f7724e8d38ff480614dd --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitg-384/ssv2.yaml @@ -0,0 +1,51 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitg-384/ssv2 +mem_per_gpu: 220G +nodes: 16 +num_workers: 8 +resume_checkpoint: true +val_only: true +tag: ssv2-vitg16-384-64x2x3 +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 2 + frames_per_clip: 64 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 384 + optimization: + batch_size: 2 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.0 + start_lr: 0.0 + warmup: 0.0 + weight_decay: 0.0 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitg-384.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_giant_xformers + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/diving48.yaml b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/diving48.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6789f8782b57f6fa79f91a98a624ba09e2139081 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/diving48.yaml @@ -0,0 +1,50 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +mem_per_gpu: 200G +tag: diving48-vitl16-32x4x3 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitl/diving48 +resume_checkpoint: true +val_only: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + dataset_type: VideoDataset + dataset_train: /your_data_dir/diving48/annotations/Diving48_train_paths.csv + dataset_val: /your_data_dir/diving48/annotations/Diving48_test_paths.csv + num_classes: 48 + resolution: 256 + frames_per_clip: 32 + frame_step: 2 + num_segments: 4 + num_views_per_segment: 3 + optimization: + use_pos_embed: false + num_epochs: 100 + batch_size: 2 + use_bfloat16: true + multihead_kwargs: + - weight_decay: 0.0 + final_weight_decay: 0.0 + lr: 0.0 + start_lr: 0.0 + final_lr: 0.0 + warmup: 0.0 +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip_multilevel + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false + out_layers: [17, 19, 21, 23] + pretrain_kwargs: + encoder: + model_name: vit_large + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/ek100.yaml b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/ek100.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42e9a74e60783312fbf216bd5a9bb15536313f70 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/ek100.yaml @@ -0,0 +1,79 @@ +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 12 +tag: ek100-vitl16 +eval_name: action_anticipation_frozen +folder: /your_folder/evals/vitl/ek100 +resume_checkpoint: true +val_only: true +experiment: + classifier: + num_probe_blocks: 4 + num_heads: 16 + data: + anticipation_time_sec: + - 1.0 + - 1.0 + auto_augment: true + file_format: 0 + dataset: EK100 + base_path: /your_ek100_root_dir/ + dataset_train: /your_data/EPIC_100_train.csv + dataset_val: /your_data/EPIC_100_validation.csv + frames_per_clip: 32 + frames_per_second: 8 + motion_shift: false + num_workers: 2 + pin_memory: true + random_resize_scale: + - 0.08 + - 1.0 + reprob: 0.25 + resolution: 256 + train_anticipation_point: + - 0.0 + - 0.25 + train_anticipation_time_sec: + - 0.25 + - 1.75 + optimization: + num_epochs: 20 + batch_size: 2 + use_bfloat16: true + use_focal_loss: true + multihead_kwargs: + - weight_decay: 0.0 + final_weight_decay: 0.0 + lr: 0.0 + start_lr: 0.0 + final_lr: 0.0 + warmup: 0.0 +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.action_anticipation_frozen.modelcustom.vit_encoder_predictor_concat_ar + wrapper_kwargs: + no_predictor: false + num_output_frames: 2 + num_steps: 1 + pretrain_kwargs: + encoder: + model_name: vit_large + checkpoint_key: target_encoder + tubelet_size: 2 + patch_size: 16 + uniform_power: true + use_rope: true + predictor: + model_name: vit_predictor + checkpoint_key: predictor + num_frames: 64 + depth: 12 + num_heads: 12 + predictor_embed_dim: 384 + num_mask_tokens: 10 + uniform_power: true + use_mask_tokens: true + use_sdpa: true + use_silu: false + wide_silu: false + use_rope: true diff --git a/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/ssv2.yaml b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/ssv2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61b14ab05266ae1f198e15efa7fee43fe2ef1a26 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/inference/vitl/ssv2.yaml @@ -0,0 +1,51 @@ +cpus_per_task: 16 +eval_name: video_classification_frozen +folder: /your_folder/evals/vitl/ssv2 +mem_per_gpu: 220G +nodes: 8 +max_workers: 8 +resume_checkpoint: true +val_only: true +tag: ssv2-vitl16-16x2x3-16f +tasks_per_node: 8 +experiment: + classifier: + num_heads: 16 + num_probe_blocks: 4 + data: + dataset_type: VideoDataset + dataset_train: /your_data_path/ssv2_train_paths.csv + dataset_val: /your_data_path/ssv2_val_paths.csv + frame_step: 4 + frames_per_clip: 16 + num_classes: 174 + num_segments: 2 + num_views_per_segment: 3 + resolution: 256 + optimization: + batch_size: 4 + multihead_kwargs: + - final_lr: 0.0 + final_weight_decay: 0.0 + lr: 0.0 + start_lr: 0.0 + warmup: 0.0 + weight_decay: 0.0 + num_epochs: 20 + use_bfloat16: true + use_pos_embed: false +model_kwargs: + checkpoint: /your_vjepa2_checkpoints/vitl.pt + module_name: evals.video_classification_frozen.modelcustom.vit_encoder_multiclip + pretrain_kwargs: + encoder: + checkpoint_key: target_encoder + img_temporal_dim_size: null + model_name: vit_large + patch_size: 16 + tubelet_size: 2 + uniform_power: true + use_rope: true + wrapper_kwargs: + max_frames: 128 + use_pos_embed: false diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/cooldown-256px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/cooldown-256px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fd61648b923241644b4ba002d0e336f9badaeee --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/cooldown-256px-64f.yaml @@ -0,0 +1,101 @@ +app: vjepa +cpus_per_task: 32 +folder: /your_folder/anneal/64.8.vitg16-256px-64f +mem_per_gpu: 220G +nodes: 64 +tasks_per_node: 8 +data: + dataset_type: VideoDataset + datasets: + - /your_k710_root_dir/k710_train_paths.csv + - /your_data_path/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 6 + crop_size: 256 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + model_name: vit_giant_xformers + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain/16.8.vitg.256px.16f/e0.pt + ema: + - 0.99925 + - 0.99925 + epochs: 4 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 30 + ipe_scale: 1.25 + is_anneal: true + lr: 0.000525 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/cooldown-384px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/cooldown-384px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c9898e8cca689680876984af82673b3e1cc9f848 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/cooldown-384px-64f.yaml @@ -0,0 +1,101 @@ +app: vjepa +cpus_per_task: 32 +folder: /your_folder/anneal/64.8.vitg16-384px-64f +mem_per_gpu: 220G +nodes: 64 +tasks_per_node: 8 +data: + dataset_type: VideoDataset + datasets: + - /your_k710_root_dir/k710_train_paths.csv + - /your_data_path/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 6 + crop_size: 384 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + model_name: vit_giant_xformers + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain/16.8.vitg.256px.16f/e0.pt + ema: + - 0.99925 + - 0.99925 + epochs: 40 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + is_anneal: true + lr: 0.000525 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/droid-256px-8f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/droid-256px-8f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..81bcd91d1552421c8a1c8cae12c58190094ae2ff --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/droid-256px-8f.yaml @@ -0,0 +1,70 @@ +app: vjepa_droid +cpus_per_task: 12 +folder: /your_folder/droid/4.8.vitg16-256px-8f +mem_per_gpu: 220G +nodes: 4 +tasks_per_node: 8 +data: + batch_size: 8 + camera_views: + - left_mp4_path + crop_size: 256 + datasets: + # CSV file, each line is a trajectory dir path + # See https://github.com/facebookresearch/vjepa2/issues/65 + - /your_file_path/droid_train_paths.csv + dataset_fpcs: + - 8 + fps: 4 + num_workers: 12 + patch_size: 16 + pin_mem: true + stereo_view: false + tubelet_size: 2 +data_aug: + auto_augment: false + horizontal_flip: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 1.777 + - 1.777 + reprob: 0.0 +loss: + auto_steps: 2 + loss_exp: 1.0 + normalize_reps: true + reg_coeff: 0.0 +meta: + dtype: bfloat16 + eval_freq: 100 + resume_checkpoint: null + load_predictor: false + pretrain_checkpoint: /your_vjepa2_checkpoints/vitg.pt + context_encoder_key: target_encoder + target_encoder_key: target_encoder + save_every_freq: 25 + seed: 239 + use_sdpa: true +model: + model_name: vit_giant_xformers + pred_depth: 24 + pred_embed_dim: 1024 + pred_is_frame_causal: true + pred_num_heads: 16 + uniform_power: true + use_activation_checkpointing: true + use_extrinsics: false + use_rope: true +optimization: + anneal: 15 + epochs: 315 + final_lr: 0.0 + final_weight_decay: 0.04 + ipe: 300 + lr: 0.000425 + start_lr: 0.000075 + warmup: 15 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/pretrain-256px-16f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/pretrain-256px-16f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3099b0089a0c8cfef870874413ee2d1ff8e22fb8 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vitg16/pretrain-256px-16f.yaml @@ -0,0 +1,98 @@ +app: vjepa +nodes: 16 +tasks_per_node: 8 +cpus_per_task: 16 +mem_per_gpu: 220G +folder: /your_folder/pretrain/16.8.vitg.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_k710_root_dir/k710_train_paths.csv + - /your_data_path/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 24 + crop_size: 256 + patch_size: 16 + dataset_fpcs: + - 16 + - 16 + - 16 + tubelet_size: 2 + fps: 4 + num_workers: 8 + persistent_workers: true + pin_mem: true +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + model_name: vit_giant_xformers + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + ema: + - 0.99925 + - 0.99925 + epochs: 800 + final_lr: 0.000525 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + lr: 0.000525 + start_lr: 0.0001 + warmup: 40 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vith16/cooldown-256px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vith16/cooldown-256px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3df953c2efe3c0635e3b3e99d0203ffca02dc541 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vith16/cooldown-256px-64f.yaml @@ -0,0 +1,101 @@ +app: vjepa +cpus_per_task: 32 +folder: /your_folder/anneal/32.8.vith16-256px-64f +mem_per_gpu: 220G +nodes: 32 +tasks_per_node: 8 +data: + dataset_type: VideoDataset + datasets: + - /your_k710_root_dir/k710_train_paths.csv + - /your_data_path/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 12 + crop_size: 256 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + model_name: vit_huge + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain/16.8.vith.256px.16f/e0.pt + ema: + - 0.99925 + - 0.99925 + epochs: 40 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + is_anneal: true + lr: 0.000525 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vith16/pretrain-256px-16f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vith16/pretrain-256px-16f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3afbcd349aeb991acf804dc52e122b5bcc78d903 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vith16/pretrain-256px-16f.yaml @@ -0,0 +1,98 @@ +app: vjepa +nodes: 16 +tasks_per_node: 8 +cpus_per_task: 16 +mem_per_gpu: 220G +folder: /your_folder/pretrain/16.8.vith.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_k710_root_dir/k710_train_paths.csv + - /your_data_path/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 24 + crop_size: 256 + patch_size: 16 + dataset_fpcs: + - 16 + - 16 + - 16 + tubelet_size: 2 + fps: 4 + num_workers: 8 + persistent_workers: true + pin_mem: true +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + model_name: vit_huge + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + ema: + - 0.99925 + - 0.99925 + epochs: 10 + final_lr: 0.000525 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + lr: 0.000525 + start_lr: 0.0001 + warmup: 40 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vitl16/cooldown-256px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vitl16/cooldown-256px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fd7e9fd5cd09ffe97a1cc2b0c664a717da26706d --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vitl16/cooldown-256px-64f.yaml @@ -0,0 +1,101 @@ +app: vjepa +cpus_per_task: 32 +folder: /your_folder/anneal/32.8.vitl16-256px-64f +mem_per_gpu: 220G +nodes: 32 +tasks_per_node: 8 +data: + dataset_type: VideoDataset + datasets: + - /your_k710_root_dir/k710_train_paths.csv + - /your_data_path/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 12 + crop_size: 256 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + model_name: vit_large + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain/16.8.vitl.256px.16f/e0.pt + ema: + - 0.99925 + - 0.99925 + epochs: 40 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + is_anneal: true + lr: 0.000525 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train/vitl16/pretrain-256px-16f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train/vitl16/pretrain-256px-16f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..535736f64af6492584a189d015f133e0d6ed8ed8 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train/vitl16/pretrain-256px-16f.yaml @@ -0,0 +1,98 @@ +app: vjepa +nodes: 16 +tasks_per_node: 8 +cpus_per_task: 16 +mem_per_gpu: 220G +folder: /your_folder/pretrain/16.8.vitl.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_k710_root_dir/k710_train_paths.csv + - /your_data_path/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 24 + crop_size: 256 + patch_size: 16 + dataset_fpcs: + - 16 + - 16 + - 16 + tubelet_size: 2 + fps: 4 + num_workers: 8 + persistent_workers: true + pin_mem: true +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + model_name: vit_large + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + ema: + - 0.99925 + - 0.99925 + epochs: 10 + final_lr: 0.000525 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + lr: 0.000525 + start_lr: 0.0001 + warmup: 40 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_giant16/cooldown-256px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_giant16/cooldown-256px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7a40962ee2ac8267160aa901a256468a598acf4 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_giant16/cooldown-256px-64f.yaml @@ -0,0 +1,144 @@ +app: vjepa_2_1 +nodes: 32 +tasks_per_node: 8 +cpus_per_task: 32 +mem_per_gpu: 220G +folder: /your_folder/cooldown_2_1/16.8.vitg.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 12 + crop_size: 256 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 + +img_data: + batch_size: 72 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +loss: + computing_gram_loss: false + gram_HighRes: false + gram_ckpt: None + gram_loss_weight: 10.0 + loss_exp: 1.0 + predict_all: true + shift_by_n: 0 + weight_distance_loss: false +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + lambda_progressive: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + modality_embedding: true + model_name: vit_giant_xformers + n_registers: 0 + normalize_predictor: false + pred_depth: 24 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain_2_1/16.8.vitg.256px.16f/latest.pth.tar + ema: + - 0.99925 + - 0.99925 + epochs: 40 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + is_anneal: true + lr: 0.0006 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_giant16/pretrain-256px-16f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_giant16/pretrain-256px-16f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..170cd2f5476d3c575d8be036f33d2f75e81968c9 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_giant16/pretrain-256px-16f.yaml @@ -0,0 +1,149 @@ +app: vjepa_2_1 +nodes: 16 +tasks_per_node: 8 +cpus_per_task: 16 +mem_per_gpu: 220G +folder: /your_folder/pretrain_2_1/16.8.vitg.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 24 + crop_size: 256 + patch_size: 16 + dataset_fpcs: + - 16 + - 16 + - 16 + tubelet_size: 2 + fps: 4 + num_workers: 8 + persistent_workers: true + pin_mem: true +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 + predict_all: true + reg_coeff: 0.0 + shift_by_n: 0 + weight_distance_loss: true + +img_data: + batch_size: 72 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + is_causal: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + local_window: + - -1 + - -1 + - -1 + modality_embedding: true + model_name: vit_giant_xformers + n_registers: 0 + n_registers_predictor: 0 + normalize_predictor: false + pred_depth: 24 + pred_embed_dim: 384 + pred_is_causal: false + pred_local_window: + - -1 + - -1 + - -1 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + vit_conv: false + zero_init_mask_tokens: true +optimization: + ema: + - 0.99925 + - 0.99925 + epochs: 1000 + final_lr: 0.0006 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + lr: 0.0006 + start_lr: 0.0001 + warmup: 40 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_gigantic16/cooldown-256px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_gigantic16/cooldown-256px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eca1e592f3e74dd683735ab02e56d397f279a49b --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_gigantic16/cooldown-256px-64f.yaml @@ -0,0 +1,144 @@ +app: vjepa_2_1 +nodes: 64 +tasks_per_node: 8 +cpus_per_task: 64 +mem_per_gpu: 220G +folder: /your_folder/cooldown_2_1/16.8.vitG.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 6 + crop_size: 256 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 + +img_data: + batch_size: 36 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +loss: + computing_gram_loss: false + gram_HighRes: false + gram_ckpt: None + gram_loss_weight: 10.0 + loss_exp: 1.0 + predict_all: true + shift_by_n: 0 + weight_distance_loss: false +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + lambda_progressive: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + modality_embedding: true + model_name: vit_gigantic_xformers + n_registers: 0 + normalize_predictor: false + pred_depth: 24 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain_2_1/16.8.vitG.256px.16f/latest.pth.tar + ema: + - 0.99925 + - 0.99925 + epochs: 40 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + is_anneal: true + lr: 0.0006 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_gigantic16/pretrain-256px-16f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_gigantic16/pretrain-256px-16f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..288c045fac92047d324877b5721fbef69d1849ba --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vit_gigantic16/pretrain-256px-16f.yaml @@ -0,0 +1,149 @@ +app: vjepa_2_1 +nodes: 32 +tasks_per_node: 8 +cpus_per_task: 32 +mem_per_gpu: 220G +folder: /your_folder/pretrain_2_1/16.8.vitG.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 12 + crop_size: 256 + patch_size: 16 + dataset_fpcs: + - 16 + - 16 + - 16 + tubelet_size: 2 + fps: 4 + num_workers: 8 + persistent_workers: true + pin_mem: true +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 + predict_all: true + reg_coeff: 0.0 + shift_by_n: 0 + weight_distance_loss: true + +img_data: + batch_size: 36 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + is_causal: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + local_window: + - -1 + - -1 + - -1 + modality_embedding: true + model_name: vit_gigantic_xformers + n_registers: 0 + n_registers_predictor: 0 + normalize_predictor: false + pred_depth: 24 + pred_embed_dim: 384 + pred_is_causal: false + pred_local_window: + - -1 + - -1 + - -1 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + vit_conv: false + zero_init_mask_tokens: true +optimization: + ema: + - 0.99925 + - 0.99925 + epochs: 1000 + final_lr: 0.0006 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + lr: 0.0006 + start_lr: 0.0001 + warmup: 40 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitb16/cooldown-256px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitb16/cooldown-256px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..343ae9baf88bef626bd6f2c09fd5da693ab71482 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitb16/cooldown-256px-64f.yaml @@ -0,0 +1,144 @@ +app: vjepa_2_1 +nodes: 16 +tasks_per_node: 8 +cpus_per_task: 16 +mem_per_gpu: 220G +folder: /your_folder/cooldown_2_1/16.8.vitb.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 24 + crop_size: 256 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 + +img_data: + batch_size: 144 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +loss: + computing_gram_loss: false + gram_HighRes: false + gram_ckpt: None + gram_loss_weight: 10.0 + loss_exp: 1.0 + predict_all: true + shift_by_n: 0 + weight_distance_loss: false +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + lambda_progressive: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + modality_embedding: true + model_name: vit_base + n_registers: 0 + normalize_predictor: false + pred_depth: 12 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain_2_1/16.8.vitb.256px.16f/latest.pth.tar + ema: + - 0.99925 + - 0.99925 + epochs: 40 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + is_anneal: true + lr: 0.0006 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitb16/pretrain-256px-16f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitb16/pretrain-256px-16f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dca536f36308f9611daa0c10c5176103494818be --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitb16/pretrain-256px-16f.yaml @@ -0,0 +1,149 @@ +app: vjepa_2_1 +nodes: 8 +tasks_per_node: 8 +cpus_per_task: 8 +mem_per_gpu: 220G +folder: /your_folder/pretrain_2_1/16.8.vitb.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 48 + crop_size: 256 + patch_size: 16 + dataset_fpcs: + - 16 + - 16 + - 16 + tubelet_size: 2 + fps: 4 + num_workers: 8 + persistent_workers: true + pin_mem: true +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 + predict_all: true + reg_coeff: 0.0 + shift_by_n: 0 + weight_distance_loss: true + +img_data: + batch_size: 144 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + is_causal: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + local_window: + - -1 + - -1 + - -1 + modality_embedding: true + model_name: vit_base + n_registers: 0 + n_registers_predictor: 0 + normalize_predictor: false + pred_depth: 12 + pred_embed_dim: 384 + pred_is_causal: false + pred_local_window: + - -1 + - -1 + - -1 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + vit_conv: false + zero_init_mask_tokens: true +optimization: + ema: + - 0.99925 + - 0.99925 + epochs: 1000 + final_lr: 0.0006 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + lr: 0.0006 + start_lr: 0.0001 + warmup: 40 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitl16/cooldown-256px-64f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitl16/cooldown-256px-64f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..73308856d8aab3ecc7d7ba3dce40d63fbedac26c --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitl16/cooldown-256px-64f.yaml @@ -0,0 +1,144 @@ +app: vjepa_2_1 +nodes: 32 +tasks_per_node: 8 +cpus_per_task: 32 +mem_per_gpu: 220G +folder: /your_folder/cooldown_2_1/16.8.vitl.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 12 + crop_size: 256 + dataset_fpcs: + - 64 + - 64 + - 64 + fps: 4 + num_workers: 12 + patch_size: 16 + persistent_workers: true + pin_mem: false + tubelet_size: 2 +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 + +img_data: + batch_size: 72 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +loss: + computing_gram_loss: false + gram_HighRes: false + gram_ckpt: None + gram_loss_weight: 10.0 + loss_exp: 1.0 + predict_all: true + shift_by_n: 0 + weight_distance_loss: false +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + lambda_progressive: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + modality_embedding: true + model_name: vit_large + n_registers: 0 + normalize_predictor: false + pred_depth: 24 + pred_embed_dim: 384 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + zero_init_mask_tokens: true +optimization: + anneal_ckpt: /your_folder/pretrain_2_1/16.8.vitl.256px.16f/latest.pth.tar + ema: + - 0.99925 + - 0.99925 + epochs: 40 + final_lr: 1.0e-06 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + is_anneal: true + lr: 0.0006 + resume_anneal: true + start_lr: 0.0001 + warmup: 0 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitl16/pretrain-256px-16f.yaml b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitl16/pretrain-256px-16f.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3988cf9ac346aff92a354987e9a54f58cdf482dd --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/configs/train_2_1/vitl16/pretrain-256px-16f.yaml @@ -0,0 +1,149 @@ +app: vjepa_2_1 +nodes: 16 +tasks_per_node: 8 +cpus_per_task: 16 +mem_per_gpu: 220G +folder: /your_folder/pretrain_2_1/16.8.vitl.256px.16f +data: + dataset_type: VideoDataset + datasets: + - /your_data/k710_train_paths.csv + - /your_data/ssv2_train_paths.csv + - /your_data/howto_320p.csv + datasets_weights: + - 0.335 + - 0.100 + - 0.565 + batch_size: 24 + crop_size: 256 + patch_size: 16 + dataset_fpcs: + - 16 + - 16 + - 16 + tubelet_size: 2 + fps: 4 + num_workers: 8 + persistent_workers: true + pin_mem: true +data_aug: + auto_augment: false + motion_shift: false + random_resize_aspect_ratio: + - 0.75 + - 1.35 + random_resize_scale: + - 0.3 + - 1.0 + reprob: 0.0 +loss: + loss_exp: 1.0 + predict_all: true + reg_coeff: 0.0 + shift_by_n: 0 + weight_distance_loss: true + +img_data: + batch_size: 72 + crop_size: 256 + dataset_fpcs: + - 1 + dataset_type: VideoDataset + datasets: + - /your_data/imagenet1k.csv + datasets_weights: + - 1.0 + rank_ratio: 0.5 +img_mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 10 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 + +mask: +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 8 + spatial_scale: + - 0.15 + - 0.15 + temporal_scale: + - 1.0 + - 1.0 +- aspect_ratio: + - 0.75 + - 1.5 + full_complement: false + max_keep: null + max_temporal_keep: 1.0 + num_blocks: 2 + spatial_scale: + - 0.7 + - 0.7 + temporal_scale: + - 1.0 + - 1.0 +meta: + dtype: bfloat16 + eval_freq: 100 + load_checkpoint: true + read_checkpoint: null + save_every_freq: 50 + seed: 239 + use_sdpa: true +model: + has_cls_first: false + img_temporal_dim_size: 1 + interpolate_rope: true + is_causal: false + lambda_value_img: 0.5 + lambda_value_vid: 0.5 + local_window: + - -1 + - -1 + - -1 + modality_embedding: true + model_name: vit_large + n_registers: 0 + n_registers_predictor: 0 + normalize_predictor: false + pred_depth: 24 + pred_embed_dim: 384 + pred_is_causal: false + pred_local_window: + - -1 + - -1 + - -1 + pred_num_heads: 12 + uniform_power: true + use_activation_checkpointing: true + use_mask_tokens: true + use_rope: true + vit_conv: false + zero_init_mask_tokens: true +optimization: + ema: + - 0.99925 + - 0.99925 + epochs: 1000 + final_lr: 0.0006 + final_weight_decay: 0.04 + ipe: 300 + ipe_scale: 1.25 + lr: 0.0006 + start_lr: 0.0001 + warmup: 40 + weight_decay: 0.04 diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/dataloader.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..d06f55024383ad44593610f5387f88d7df870a2e --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/dataloader.py @@ -0,0 +1,236 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + + +from logging import getLogger + +import torch +import torchvision.transforms as transforms + +import src.datasets.utils.video.transforms as video_transforms +import src.datasets.utils.video.volume_transforms as volume_transforms +from evals.action_anticipation_frozen.epickitchens import filter_annotations as ek100_filter_annotations +from evals.action_anticipation_frozen.epickitchens import make_webvid as ek100_make_webvid +from src.datasets.utils.video.randerase import RandomErasing + +_GLOBAL_SEED = 0 +logger = getLogger() + + +def init_data( + base_path, + annotations_path, + batch_size, + dataset, + frames_per_clip=16, + fps=5, + crop_size=224, + rank=0, + world_size=1, + drop_last=True, + num_workers=10, + pin_mem=True, + persistent_workers=True, + training=True, + decode_video=True, + anticipation_time_sec=0.0, + decode_one_clip=False, + random_resize_scale=(0.9, 1.0), + reprob=0, + auto_augment=False, + motion_shift=False, + anticipation_point=[0.1, 0.1], +): + # -- make video transformations + transform = make_transforms( + training=training, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + crop_size=crop_size, + ) + + make_webvid = None + if "ek100" in dataset.lower(): + make_webvid = ek100_make_webvid + + dataset, data_loader, data_info = make_webvid( + training=training, + decode_one_clip=decode_one_clip, + world_size=world_size, + rank=rank, + base_path=base_path, + annotations_path=annotations_path, + batch_size=batch_size, + transform=transform, + frames_per_clip=frames_per_clip, + num_workers=num_workers, + fps=fps, + decode_video=decode_video, + anticipation_time_sec=anticipation_time_sec, + persistent_workers=persistent_workers, + pin_memory=pin_mem, + anticipation_point=anticipation_point, + ) + + return dataset, data_loader, data_info + + +def filter_annotations( + dataset, + base_path, + train_annotations_path, + val_annotations_path, + **kwargs, +): + _filter = None + if "ek100" in dataset.lower(): + _filter = ek100_filter_annotations + + return _filter( + base_path=base_path, + train_annotations_path=train_annotations_path, + val_annotations_path=val_annotations_path, + **kwargs, + ) + + +def make_transforms( + training=True, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), +): + + transform = VideoTransform( + training=training, + random_horizontal_flip=random_horizontal_flip, + random_resize_aspect_ratio=random_resize_aspect_ratio, + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + crop_size=crop_size, + normalize=normalize, + ) + + return transform + + +class VideoTransform(object): + + def __init__( + self, + training=True, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + ): + + self.training = training + + short_side_size = int(crop_size * 256 / 224) + self.eval_transform = video_transforms.Compose( + [ + video_transforms.Resize(short_side_size, interpolation="bilinear"), + video_transforms.CenterCrop(size=(crop_size, crop_size)), + volume_transforms.ClipToTensor(), + video_transforms.Normalize(mean=normalize[0], std=normalize[1]), + ] + ) + + self.random_horizontal_flip = random_horizontal_flip + self.random_resize_aspect_ratio = random_resize_aspect_ratio + self.random_resize_scale = random_resize_scale + self.auto_augment = auto_augment + self.motion_shift = motion_shift + self.crop_size = crop_size + self.normalize = torch.tensor(normalize) + + self.autoaug_transform = video_transforms.create_random_augment( + input_size=(crop_size, crop_size), + auto_augment="rand-m7-n4-mstd0.5-inc1", + interpolation="bicubic", + ) + + self.spatial_transform = ( + video_transforms.random_resized_crop_with_shift if motion_shift else video_transforms.random_resized_crop + ) + + self.reprob = reprob + self.erase_transform = RandomErasing( + reprob, + mode="pixel", + max_count=1, + num_splits=1, + device="cpu", + ) + + def __call__(self, buffer): + + if not self.training: + return self.eval_transform(buffer) + + buffer = [transforms.ToPILImage()(frame) for frame in buffer] + + if self.auto_augment: + buffer = self.autoaug_transform(buffer) + + buffer = [transforms.ToTensor()(img) for img in buffer] + buffer = torch.stack(buffer) # T C H W + buffer = buffer.permute(0, 2, 3, 1) # T H W C + + buffer = tensor_normalize(buffer, self.normalize[0], self.normalize[1]) + buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W + + buffer = self.spatial_transform( + images=buffer, + target_height=self.crop_size, + target_width=self.crop_size, + scale=self.random_resize_scale, + ratio=self.random_resize_aspect_ratio, + ) + if self.random_horizontal_flip: + buffer, _ = video_transforms.horizontal_flip(0.5, buffer) + + if self.reprob > 0: + buffer = buffer.permute(1, 0, 2, 3) + buffer = self.erase_transform(buffer) + buffer = buffer.permute(1, 0, 2, 3) + + return buffer + + +def tensor_normalize(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize. + mean (tensor or list): mean value to subtract. + std (tensor or list): std to divide. + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + tensor = tensor / 255.0 + if isinstance(mean, list): + mean = torch.tensor(mean) + if isinstance(std, list): + std = torch.tensor(std) + tensor = tensor - mean + tensor = tensor / std + return tensor diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/epickitchens.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/epickitchens.py new file mode 100644 index 0000000000000000000000000000000000000000..c0582b8fc0953ff12d1e127e8b75b527822266c0 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/epickitchens.py @@ -0,0 +1,323 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import multiprocessing +import os +import random +from dataclasses import dataclass +from itertools import islice +from multiprocessing import Value + +import numpy as np +import pandas as pd +import torch +import webdataset as wds +from decord import VideoReader, cpu +from torch.utils.data import DataLoader, IterableDataset +from torch.utils.data.distributed import DistributedSampler + +from src.datasets.utils.worker_init_fn import pl_worker_init_function + +multiprocessing.set_start_method("spawn", force=True) + + +class SharedEpoch: + def __init__(self, epoch: int = 0): + self.shared_epoch = Value("i", epoch) + + def set_value(self, epoch): + self.shared_epoch.value = epoch + + def get_value(self): + return self.shared_epoch.value + + +@dataclass +class DataInfo: + dataloader: DataLoader + sampler: DistributedSampler = None + shared_epoch: SharedEpoch = None + + def set_epoch(self, epoch): + if self.shared_epoch is not None: + self.shared_epoch.set_value(epoch) + if self.sampler is not None and isinstance(self.sampler, DistributedSampler): + self.sampler.set_epoch(epoch) + + +def get_dataset_size(shards_list): + num_shards = len(shards_list) + total_size = num_shards + return total_size, num_shards + + +def log_and_continue(exn): + """Call in an exception handler to ignore any exception, issue a warning, and continue.""" + logging.warning(f"Handling webdataset error ({repr(exn)}). Ignoring.") + return True + + +class split_by_node(wds.PipelineStage): + """Node splitter that uses provided rank/world_size instead of from torch.distributed""" + + def __init__( + self, + rank=0, + world_size=1, + ): + self.rank = rank + self.world_size = world_size + + def run(self, src): + if self.world_size > 1: + yield from islice(src, self.rank, None, self.world_size) + else: + yield from src + + +class decode_videos_to_clips(wds.PipelineStage): + + def __init__( + self, + annotations, + frames_per_clip=16, + fps=5, + transform=None, + anticipation_time_sec=[0.0, 0.0], + anticipation_point=[0.25, 0.75], + ): + self.annotations = annotations + self.frames_per_clip = frames_per_clip + self.fps = fps + self.transform = transform + self.anticipation_time = anticipation_time_sec + self.anticipation_point = anticipation_point + + def run(self, src): + for path in src: + # -- get all action annotations for the video + video_id = path.split("/")[-1].split(".")[0] + ano = self.annotations[video_id] + + # -- get action annotations and frame stamps + start_frames = ano["start_frame"].values + stop_frames = ano["stop_frame"].values + + # -- load clips corresponding to action annotations + try: + vr = VideoReader(path, num_threads=-1, ctx=cpu(0)) + vr.seek(0) + # -- + vfps = vr.get_avg_fps() + fpc = self.frames_per_clip + fstp = int(vfps / self.fps) + nframes = int(fpc * fstp) + except Exception as e: + logging.info(f"Encountered exception loading video {e=}") + continue + + for i, (sf, ef) in enumerate(zip(start_frames, stop_frames)): + labels_verb = int(ano["verb_class"].values[i]) + labels_noun = int(ano["noun_class"].values[i]) + + # sample an anticipation time + at = random.uniform(*self.anticipation_time) + aframes = int(at * vfps) + + # sample an anticipation frame b/w start and end of action + ap = random.uniform(*self.anticipation_point) + af = int(sf * ap + (1 - ap) * ef - aframes) + + indices = np.arange(af - nframes, af, fstp).astype(np.int64) + # If not enough frames in video for anticipation, just pad with + # first frame + indices[indices < 0] = 0 + + try: + buffer = vr.get_batch(indices).asnumpy() + except Exception as e: + logging.info(f"Encountered exception getting indices {e=}") + continue + + if self.transform is not None: + buffer = self.transform(buffer) + + yield dict( + video=buffer, + verb=labels_verb, + noun=labels_noun, + anticipation_time=at, + ) + + +class ResampledShards(IterableDataset): + """An iterable dataset yielding a list of urls.""" + + def __init__(self, urls, epoch, training): + super().__init__() + self.epoch = epoch + self.training = training + self.urls = np.array(urls) + logging.info("Done initializing ResampledShards") + + def __iter__(self): + """Return an iterator over the shards.""" + if self.training: + epoch = self.epoch.get_value() + gen = torch.Generator() + gen.manual_seed(epoch) + yield from self.urls[torch.randperm(len(self.urls), generator=gen)] + else: + yield from self.urls[torch.arange(len(self.urls))] + + +def get_video_wds_dataset( + batch_size, + input_shards, + video_decoder, + training, + epoch=0, + world_size=1, + rank=0, + num_workers=1, + persistent_workers=True, + pin_memory=True, +): + assert input_shards is not None + _, num_shards = get_dataset_size(input_shards) + logging.info(f"Total number of shards across all data is {num_shards=}") + + epoch = SharedEpoch(epoch=epoch) + pipeline = [ + ResampledShards(input_shards, epoch=epoch, training=training), + split_by_node(rank=rank, world_size=world_size), + wds.split_by_worker, + video_decoder, + wds.to_tuple("video", "verb", "noun", "anticipation_time"), + wds.batched(batch_size, partial=True, collation_fn=torch.utils.data.default_collate), + ] + dataset = wds.DataPipeline(*pipeline) + + dataloader = torch.utils.data.DataLoader( + dataset, + batch_size=None, + shuffle=False, + num_workers=num_workers, + persistent_workers=(num_workers > 0) and persistent_workers, + worker_init_fn=pl_worker_init_function, + pin_memory=pin_memory, + ) + + return dataset, DataInfo(dataloader=dataloader, shared_epoch=epoch) + + +def filter_annotations( + base_path, + train_annotations_path, + val_annotations_path, + file_format=1, +): + + tdf = pd.read_csv(train_annotations_path) + vdf = pd.read_csv(val_annotations_path) + + # 1. Remove actions in val that are not in train + tactions = set([(v, n) for v, n in zip(tdf["verb_class"].values, tdf["noun_class"].values)]) + tverbs = set([v for v, _ in tactions]) + tnouns = set([n for _, n in tactions]) + keep_inds = [(v, n) in tactions for v, n in zip(vdf["verb_class"].values, vdf["noun_class"].values)] + vdf = vdf[keep_inds] + + # 2. Determine new class labels + verb_classes = {k: i for i, k in enumerate(tverbs)} + noun_classes = {k: i for i, k in enumerate(tnouns)} + action_classes = {k: i for i, k in enumerate(tactions)} + + val_verb_classes = set([verb_classes[v] for v in vdf["verb_class"].values]) + val_noun_classes = set([noun_classes[n] for n in vdf["noun_class"].values]) + val_action_classes = set([action_classes[a] for a in zip(vdf["verb_class"].values, vdf["noun_class"].values)]) + + def build_annotations(df): + video_paths, annotations = [], {} + unique_videos = list(dict.fromkeys(df["video_id"].values)) + for uv in unique_videos: + pid = uv.split("_")[0] + # There are two common file formats for storing EK + if file_format == 0: + # File format 0: $base_path/$participant_id/videos/$video_id.MP4 + fpath = os.path.join(base_path, pid, "videos", uv + ".MP4") + else: + # File format 1: $base_path/$participant_id/$video_id.MP4 + fpath = os.path.join(base_path, pid, uv + ".MP4") + if not os.path.exists(fpath): + logging.info(f"file path not found {fpath=}") + continue + video_paths += [fpath] + annotations[uv] = df[df["video_id"] == uv].sort_values(by="start_frame") + return video_paths, annotations + + train_annotations = build_annotations(tdf) + val_annotations = build_annotations(vdf) + + return dict( + verbs=verb_classes, + nouns=noun_classes, + actions=action_classes, + val_verbs=val_verb_classes, + val_nouns=val_noun_classes, + val_actions=val_action_classes, + train=train_annotations, + val=val_annotations, + ) + + +def make_webvid( + base_path, + annotations_path, + batch_size, + transform, + frames_per_clip=16, + fps=5, + num_workers=8, + world_size=1, + rank=0, + anticipation_time_sec=[0.0, 0.0], + persistent_workers=True, + pin_memory=True, + training=True, + anticipation_point=[0.1, 0.1], + **kwargs, +): + + paths, annotations = annotations_path + num_clips = sum([len(a) for a in annotations.values()]) + + video_decoder = decode_videos_to_clips( + annotations=annotations, + frames_per_clip=frames_per_clip, + fps=fps, + transform=transform, + anticipation_time_sec=anticipation_time_sec, + anticipation_point=anticipation_point, + ) + + dataset, datainfo = get_video_wds_dataset( + batch_size=batch_size, + input_shards=paths, + epoch=0, + world_size=world_size, + rank=rank, + num_workers=num_workers, + video_decoder=video_decoder, + persistent_workers=persistent_workers, + pin_memory=pin_memory, + training=training, + ) + + datainfo.dataloader.num_batches = num_clips // (world_size * batch_size) + datainfo.dataloader.num_samples = num_clips + + return dataset, datainfo.dataloader, datainfo diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/eval.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..5dcce775b530937dd700af157fbdcccb563cafd6 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/eval.py @@ -0,0 +1,749 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os + +# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESS +try: + # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE + # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE + # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE + # -- TO EACH PROCESS + os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"] +except Exception: + pass + +import logging +import pprint +import random +import time + +import numpy as np +import torch +import torch.multiprocessing as mp +from torch.nn.parallel import DistributedDataParallel + +from evals.action_anticipation_frozen.dataloader import filter_annotations, init_data +from evals.action_anticipation_frozen.losses import sigmoid_focal_loss +from evals.action_anticipation_frozen.metrics import ClassMeanRecall +from evals.action_anticipation_frozen.models import init_classifier, init_module +from evals.action_anticipation_frozen.utils import init_opt +from src.utils.checkpoint_loader import robust_checkpoint_loader +from src.utils.distributed import init_distributed +from src.utils.logging import AverageMeter, CSVLogger + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + +_GLOBAL_SEED = 0 +random.seed(_GLOBAL_SEED) +np.random.seed(_GLOBAL_SEED) +torch.manual_seed(_GLOBAL_SEED) +torch.cuda.manual_seed(_GLOBAL_SEED) +torch.backends.cudnn.benchmark = True + + +pp = pprint.PrettyPrinter(indent=4) + + +def main(args_eval, resume_preempt=False): + # ----------------------------------------------------------------------- # + # PASSED IN PARAMS FROM CONFIG FILE + # ----------------------------------------------------------------------- # + + # -- VAL ONLY + val_only = args_eval.get("val_only", False) + if val_only: + logger.info("VAL ONLY") + + # -- EXPERIMENT + pretrain_folder = args_eval.get("folder", None) + resume_checkpoint = args_eval.get("resume_checkpoint", False) or resume_preempt + val_only = args_eval.get("val_only", False) + eval_tag = args_eval.get("tag", None) + + # -- PRETRAIN + args_pretrain = args_eval.get("model_kwargs") + checkpoint = args_pretrain.get("checkpoint") + module_name = args_pretrain.get("module_name") + args_model = args_pretrain.get("pretrain_kwargs") + args_wrapper = args_pretrain.get("wrapper_kwargs") + + args_exp = args_eval.get("experiment") + + # -- CLASSIFIER + args_classifier = args_exp.get("classifier") + num_probe_blocks = args_classifier.get("num_probe_blocks", 1) + num_heads = args_classifier.get("num_heads") + + # -- DATA + args_data = args_exp.get("data") + dataset = args_data.get("dataset") # Name of dataset (e.g., "EK100") + base_path = args_data.get("base_path") # Root directory containing videos + file_format = args_data.get("file_format", 1) + num_workers = args_data.get("num_workers", 12) + pin_mem = args_data.get("pin_memory", True) + # -- / frame sampling hyper-params + frames_per_clip = args_data.get("frames_per_clip") + frames_per_second = args_data.get("frames_per_second") + resolution = args_data.get("resolution", 224) + # -- / anticipation details + train_anticipation_time_sec = args_data.get("train_anticipation_time_sec") + train_anticipation_point = args_data.get("train_anticipation_point") + val_anticipation_point = args_data.get("val_anticipation_point", [0.0, 0.0]) + val_anticipation_time_sec = args_data.get("anticipation_time_sec") + # -- / data augmentations + auto_augment = args_data.get("auto_augment") + motion_shift = args_data.get("motion_shift") + reprob = args_data.get("reprob") + random_resize_scale = args_data.get("random_resize_scale") + # -- + train_annotations_path = args_data.get("dataset_train") + val_annotations_path = args_data.get("dataset_val") + train_data_path = base_path # os.path.join(base_path, "train") + val_data_path = base_path # os.path.join(base_path, "test") + + # -- OPTIMIZATION + args_opt = args_exp.get("optimization") + batch_size = args_opt.get("batch_size") + num_epochs = args_opt.get("num_epochs") + use_bfloat16 = args_opt.get("use_bfloat16") + use_focal_loss = args_opt.get("use_focal_loss", False) + criterion = sigmoid_focal_loss if use_focal_loss else torch.nn.CrossEntropyLoss() + opt_kwargs = [ + dict( + ref_wd=kwargs.get("weight_decay"), + final_wd=kwargs.get("final_weight_decay"), + start_lr=kwargs.get("start_lr"), + ref_lr=kwargs.get("lr"), + final_lr=kwargs.get("final_lr"), + warmup=kwargs.get("warmup"), + ) + for kwargs in args_opt.get("multihead_kwargs") + ] + + # ----------------------------------------------------------------------- # + + try: + mp.set_start_method("spawn") + except Exception: + pass + + if not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device("cuda:0") + torch.cuda.set_device(device) + + world_size, rank = init_distributed() + logger.info(f"Initialized (rank/world-size) {rank}/{world_size}") + + # -- log/checkpointing paths + folder = os.path.join(pretrain_folder, "action_anticipation_frozen/") + if eval_tag is not None: + folder = os.path.join(folder, eval_tag) + if not os.path.exists(folder): + os.makedirs(folder, exist_ok=True) + log_file = os.path.join(folder, f"log_r{rank}.csv") + latest_path = os.path.join(folder, "latest.pt") + + action_is_verb_noun = True + if dataset in ["COIN_anticipation"]: + action_is_verb_noun = False + + # -- make csv_logger + if rank == 0: + if action_is_verb_noun: + csv_logger = CSVLogger( + log_file, + ("%d", "epoch"), + ("%.5f", "train-acc"), + ("%.5f", "train-acc-verb"), + ("%.5f", "train-acc-noun"), + ("%.5f", "train-recall"), + ("%.5f", "train-recall-verb"), + ("%.5f", "train-recall-noun"), + ("%.5f", "val-acc"), + ("%.5f", "val-acc-verb"), + ("%.5f", "val-acc-noun"), + ("%.5f", "val-recall"), + ("%.5f", "val-recall-verb"), + ("%.5f", "val-recall-noun"), + ) + else: + csv_logger = CSVLogger( + log_file, + ("%d", "epoch"), + ("%.5f", "train-acc"), + ("%.5f", "train-recall"), + ("%.5f", "val-acc"), + ("%.5f", "val-recall"), + ) + + # -- process annotations to unify action class labels between train/val + _annotations = filter_annotations( + dataset, + base_path, + train_annotations_path, + val_annotations_path, + file_format=file_format, + ) + action_classes = _annotations["actions"] + verb_classes = {} + noun_classes = {} + if action_is_verb_noun: + verb_classes = _annotations["verbs"] + noun_classes = _annotations["nouns"] + # -- + val_actions = _annotations["val_actions"] + val_verbs = {} + val_nouns = {} + if action_is_verb_noun: + val_verbs = _annotations["val_verbs"] + val_nouns = _annotations["val_nouns"] + # -- + train_annotations = _annotations["train"] + val_annotations = _annotations["val"] + + # -- init models + model = init_module( + module_name=module_name, + frames_per_clip=frames_per_clip, + frames_per_second=frames_per_second, + resolution=resolution, + checkpoint=checkpoint, + model_kwargs=args_model, + wrapper_kwargs=args_wrapper, + device=device, + ) + classifiers = init_classifier( + embed_dim=model.embed_dim, + num_heads=num_heads, + verb_classes=verb_classes, + noun_classes=noun_classes, + action_classes=action_classes, + num_blocks=num_probe_blocks, + device=device, + num_classifiers=len(opt_kwargs), + ) + + # --init data + train_set, train_loader, train_data_info = init_data( + dataset=dataset, + training=True, + base_path=train_data_path, + annotations_path=train_annotations, + batch_size=batch_size, + frames_per_clip=frames_per_clip, + fps=frames_per_second, + anticipation_time_sec=train_anticipation_time_sec, + anticipation_point=train_anticipation_point, + # -- + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + # -- + crop_size=resolution, + world_size=world_size, + rank=rank, + num_workers=num_workers, + pin_mem=pin_mem, + persistent_workers=False, + ) + ipe = train_loader.num_batches + logger.info(f"Dataloader created... iterations per epoch: {ipe}") + _, val_loader, _ = init_data( + dataset=dataset, + training=False, + base_path=val_data_path, + annotations_path=val_annotations, + batch_size=batch_size, + frames_per_clip=frames_per_clip, + fps=frames_per_second, + anticipation_time_sec=val_anticipation_time_sec, + anticipation_point=val_anticipation_point, + crop_size=resolution, + world_size=world_size, + rank=rank, + num_workers=num_workers, + pin_mem=pin_mem, + persistent_workers=False, + ) + val_ipe = val_loader.num_batches + logger.info(f"Val dataloader created... iterations per epoch: {val_ipe}") + + # -- optimizer and scheduler + optimizer, scaler, scheduler, wd_scheduler = init_opt( + classifiers=classifiers, + opt_kwargs=opt_kwargs, + iterations_per_epoch=ipe, + num_epochs=num_epochs, + use_bfloat16=use_bfloat16, + ) + classifiers = [DistributedDataParallel(c, static_graph=True) for c in classifiers] + + # -- load training checkpoint + start_epoch = 0 + if resume_checkpoint and os.path.exists(latest_path): + classifiers, optimizer, scaler, start_epoch = load_checkpoint( + device=device, + r_path=latest_path, + classifiers=classifiers, + opt=optimizer, + scaler=scaler, + val_only=val_only, + ) + for _ in range(start_epoch * ipe): + [s.step() for s in scheduler] + [wds.step() for wds in wd_scheduler] + if val_only: + start_epoch = 0 + + def save_checkpoint(epoch): + save_dict = { + "classifiers": [c.state_dict() for c in classifiers], + "opt": [o.state_dict() for o in optimizer], + "scaler": None if scaler is None else [s.state_dict() for s in scaler], + "epoch": epoch, + "batch_size": batch_size, + "world_size": world_size, + } + if rank == 0: + torch.save(save_dict, latest_path) + + # -- Train action recognition model + for epoch in range(start_epoch, num_epochs): + logging.info(f"Epoch {epoch}") + + train_data_info.set_epoch(epoch) + + # report train action recognition (AR) + if not val_only: + logging.info("Training...") + # with torch.autograd.detect_anomaly(): # TODO Remove + train_metrics = train_one_epoch( + action_is_verb_noun=action_is_verb_noun, + ipe=ipe, + device=device, + model=model, + classifiers=classifiers, + scaler=scaler, + optimizer=optimizer, + scheduler=scheduler, + wd_scheduler=wd_scheduler, + data_loader=train_loader, + use_bfloat16=use_bfloat16, + verb_classes=verb_classes, + noun_classes=noun_classes, + action_classes=action_classes, + criterion=criterion, + ) + + # report val action anticipation (AA) + val_metrics = validate( + action_is_verb_noun=action_is_verb_noun, + ipe=val_ipe, + device=device, + model=model, + classifiers=classifiers, + data_loader=val_loader, + use_bfloat16=use_bfloat16, + valid_verbs=val_verbs, + valid_nouns=val_nouns, + valid_actions=val_actions, + verb_classes=verb_classes, + noun_classes=noun_classes, + action_classes=action_classes, + criterion=criterion, + ) + if val_only: + logger.info( + "val acc (v/n): %.1f%% (%.1f%% %.1f%%) " + "val recall (v/n): %.1f%% (%.1f%% %.1f%%) " + % ( + val_metrics["action"]["accuracy"], + val_metrics["verb"]["accuracy"], + val_metrics["noun"]["accuracy"], + val_metrics["action"]["recall"], + val_metrics["verb"]["recall"], + val_metrics["noun"]["recall"], + ) + ) + return + + if action_is_verb_noun: + logger.info( + "[%5d] " + "train acc (v/n): %.1f%% (%.1f%% %.1f%%) " + "train recall (v/n): %.1f%% (%.1f%% %.1f%%) " + "val acc (v/n): %.1f%% (%.1f%% %.1f%%) " + "val recall (v/n): %.1f%% (%.1f%% %.1f%%) " + % ( + epoch + 1, + train_metrics["action"]["accuracy"], + train_metrics["verb"]["accuracy"], + train_metrics["noun"]["accuracy"], + train_metrics["action"]["recall"], + train_metrics["verb"]["recall"], + train_metrics["noun"]["recall"], + val_metrics["action"]["accuracy"], + val_metrics["verb"]["accuracy"], + val_metrics["noun"]["accuracy"], + val_metrics["action"]["recall"], + val_metrics["verb"]["recall"], + val_metrics["noun"]["recall"], + ) + ) + if rank == 0: + csv_logger.log( + epoch + 1, + train_metrics["action"]["accuracy"], + train_metrics["verb"]["accuracy"], + train_metrics["noun"]["accuracy"], + train_metrics["action"]["recall"], + train_metrics["verb"]["recall"], + train_metrics["noun"]["recall"], + val_metrics["action"]["accuracy"], + val_metrics["verb"]["accuracy"], + val_metrics["noun"]["accuracy"], + val_metrics["action"]["recall"], + val_metrics["verb"]["recall"], + val_metrics["noun"]["recall"], + ) + else: + logger.info( + "[%5d] " + "train acc (v/n): %.1f%% " + "train recall (v/n): %.1f%% " + "val acc (v/n): %.1f%% " + "val recall (v/n): %.1f%% " + % ( + epoch + 1, + train_metrics["action"]["accuracy"], + train_metrics["action"]["recall"], + val_metrics["action"]["accuracy"], + val_metrics["action"]["recall"], + ) + ) + if rank == 0: + csv_logger.log( + epoch + 1, + train_metrics["action"]["accuracy"], + train_metrics["action"]["recall"], + val_metrics["action"]["accuracy"], + val_metrics["action"]["recall"], + ) + + save_checkpoint(epoch + 1) + + +def train_one_epoch( + action_is_verb_noun, + ipe, + device, + model, + classifiers, + scaler, + optimizer, + scheduler, + wd_scheduler, + data_loader, + use_bfloat16, + noun_classes, + verb_classes, + action_classes, + criterion, +): + _data_loader = iter(data_loader) + for c in classifiers: + c.train(mode=True) + if action_is_verb_noun: + verb_metric_loggers = [ClassMeanRecall(num_classes=len(verb_classes), device=device, k=5) for _ in classifiers] + noun_metric_loggers = [ClassMeanRecall(num_classes=len(noun_classes), device=device, k=5) for _ in classifiers] + action_metric_loggers = [ClassMeanRecall(num_classes=len(action_classes), device=device, k=5) for _ in classifiers] + data_elapsed_time_meter = AverageMeter() + + for itr in range(ipe): + itr_start_time = time.time() + + try: + udata = next(_data_loader) + except Exception: + _data_loader = iter(data_loader) + udata = next(_data_loader) + + [s.step() for s in scheduler] + [wds.step() for wds in wd_scheduler] + + with torch.cuda.amp.autocast(dtype=torch.bfloat16, enabled=use_bfloat16): + + # Format of udata: ("video", "verb", "noun", "anticipation_time_sec") + clips = udata[0].to(device) + anticipation_times = udata[-1].to(device) # [B] + + if action_is_verb_noun: + # Map verb/nouns to unified class labels + _verbs, _nouns = udata[1], udata[2] + verb_labels, noun_labels, action_labels = [], [], [] + for v, n in zip(_verbs, _nouns): + verb_labels.append(verb_classes[int(v)]) + noun_labels.append(noun_classes[int(n)]) + action_labels.append(action_classes[(int(v), int(n))]) + verb_labels = torch.tensor(verb_labels).to(device).to(_verbs.dtype) + noun_labels = torch.tensor(noun_labels).to(device).to(_verbs.dtype) + action_labels = torch.tensor(action_labels).to(device).to(_verbs.dtype) + else: + _actions = udata[1] + action_labels = [action_classes[str(int(a))] for a in _actions] + action_labels = torch.tensor(action_labels).to(device).to(_actions.dtype) + + # -- + data_elapsed_time_ms = (time.time() - itr_start_time) * 1000.0 + data_elapsed_time_meter.update(data_elapsed_time_ms) + + # Forward and prediction + with torch.no_grad(): + outputs = model(clips, anticipation_times) + outputs = [c(outputs) for c in classifiers] + + # Compute loss & update weights + if action_is_verb_noun: + verb_loss = [criterion(o["verb"], verb_labels) for o in outputs] + noun_loss = [criterion(o["noun"], noun_labels) for o in outputs] + action_loss = [criterion(o["action"], action_labels) for o in outputs] + loss = [v + n + a for v, n, a in zip(verb_loss, noun_loss, action_loss)] + else: + loss = [criterion(o["action"], action_labels) for o in outputs] + if use_bfloat16: + [s.scale(l).backward() for s, l in zip(scaler, loss)] + [s.step(o) for s, o in zip(scaler, optimizer)] + [s.update() for s in scaler] + else: + [L.backward() for L in loss] + [o.step() for o in optimizer] + [o.zero_grad() for o in optimizer] + + # Compute metrics for logging (e.g., accuracy and mean class recall) + with torch.no_grad(): + if action_is_verb_noun: + verb_metrics = [m(o["verb"], verb_labels) for o, m in zip(outputs, verb_metric_loggers)] + noun_metrics = [m(o["noun"], noun_labels) for o, m in zip(outputs, noun_metric_loggers)] + action_metrics = [m(o["action"], action_labels) for o, m in zip(outputs, action_metric_loggers)] + + if itr % 10 == 0 or itr == ipe - 1: + if action_is_verb_noun: + logger.info( + "[%5d] " + "acc (v/n): %.1f%% (%.1f%% %.1f%%) " + "recall (v/n): %.1f%% (%.1f%% %.1f%%) " + "[mem: %.2e] " + "[data: %.1f ms]" + % ( + itr, + max([a["accuracy"] for a in action_metrics]), + max([v["accuracy"] for v in verb_metrics]), + max([n["accuracy"] for n in noun_metrics]), + max([a["recall"] for a in action_metrics]), + max([v["recall"] for v in verb_metrics]), + max([n["recall"] for n in noun_metrics]), + torch.cuda.max_memory_allocated() / 1024.0**2, + data_elapsed_time_meter.avg, + ) + ) + else: + logger.info( + "[%5d] " + "acc (v/n): %.1f%% " + "recall (v/n): %.1f%% " + "[mem: %.2e] " + "[data: %.1f ms]" + % ( + itr, + max([a["accuracy"] for a in action_metrics]), + max([a["recall"] for a in action_metrics]), + torch.cuda.max_memory_allocated() / 1024.0**2, + data_elapsed_time_meter.avg, + ) + ) + + del _data_loader + ret = dict( + action=dict( + accuracy=max([a["accuracy"] for a in action_metrics]), + recall=max([a["recall"] for a in action_metrics]), + ), + ) + if action_is_verb_noun: + ret.update( + dict( + verb=dict( + accuracy=max([v["accuracy"] for v in verb_metrics]), + recall=max([v["recall"] for v in verb_metrics]), + ), + noun=dict( + accuracy=max([n["accuracy"] for n in noun_metrics]), + recall=max([n["recall"] for n in noun_metrics]), + ), + ) + ) + return ret + + +@torch.no_grad() +def validate( + action_is_verb_noun, + ipe, + device, + model, + classifiers, + data_loader, + use_bfloat16, + valid_nouns, + valid_verbs, + valid_actions, + noun_classes, + verb_classes, + action_classes, + criterion, +): + logger.info("Running val...") + _data_loader = iter(data_loader) + for c in classifiers: + c.train(mode=False) + if action_is_verb_noun: + verb_metric_loggers = [ClassMeanRecall(num_classes=len(verb_classes), device=device, k=5) for _ in classifiers] + noun_metric_loggers = [ClassMeanRecall(num_classes=len(noun_classes), device=device, k=5) for _ in classifiers] + action_metric_loggers = [ClassMeanRecall(num_classes=len(action_classes), device=device, k=5) for _ in classifiers] + + for itr in range(ipe): + try: + udata = next(_data_loader) + except Exception: + _data_loader = iter(data_loader) + udata = next(_data_loader) + + with torch.cuda.amp.autocast(dtype=torch.bfloat16, enabled=use_bfloat16): + # Format of udata: ("video", "verb", "noun", "anticipation_time_sec") + clips = udata[0].to(device) + anticipation_times = udata[-1].to(device) # [B] + + if action_is_verb_noun: + # Map verb/nouns to unified class labels + _verbs, _nouns = udata[1], udata[2] + verb_labels, noun_labels, action_labels = [], [], [] + for v, n in zip(_verbs, _nouns): + verb_labels.append(verb_classes[int(v)]) + noun_labels.append(noun_classes[int(n)]) + action_labels.append(action_classes[(int(v), int(n))]) + verb_labels = torch.tensor(verb_labels).to(device).to(_verbs.dtype) + noun_labels = torch.tensor(noun_labels).to(device).to(_verbs.dtype) + action_labels = torch.tensor(action_labels).to(device).to(_verbs.dtype) + else: + _actions = udata[1] + action_labels = [action_classes[str(int(a))] for a in _actions] + action_labels = torch.tensor(action_labels).to(device).to(_actions.dtype) + + # Forward and prediction + outputs = model(clips, anticipation_times) + outputs = [c(outputs) for c in classifiers] + + if action_is_verb_noun: + verb_loss = sum([criterion(o["verb"], verb_labels) for o in outputs]) + noun_loss = sum([criterion(o["noun"], noun_labels) for o in outputs]) + action_loss = sum([criterion(o["action"], action_labels) for o in outputs]) + loss = verb_loss + noun_loss + action_loss + else: + loss = sum([criterion(o["action"], action_labels) for o in outputs]) + + action_metrics = [m(o["action"], action_labels) for o, m in zip(outputs, action_metric_loggers)] + if action_is_verb_noun: + verb_metrics = [m(o["verb"], verb_labels) for o, m in zip(outputs, verb_metric_loggers)] + noun_metrics = [m(o["noun"], noun_labels) for o, m in zip(outputs, noun_metric_loggers)] + + if itr % 10 == 0 or itr == ipe - 1: + if action_is_verb_noun: + logger.info( + "[%5d] " + "acc (v/n): %.1f%% (%.1f%% %.1f%%) " + "recall (v/n): %.1f%% (%.1f%% %.1f%%) " + "loss (v/n): %.3f (%.3f %.3f) " + "[mem: %.2e] " + % ( + itr, + max([a["accuracy"] for a in action_metrics]), + max([v["accuracy"] for v in verb_metrics]), + max([n["accuracy"] for n in noun_metrics]), + max([a["recall"] for a in action_metrics]), + max([v["recall"] for v in verb_metrics]), + max([n["recall"] for n in noun_metrics]), + loss, + verb_loss, + noun_loss, + torch.cuda.max_memory_allocated() / 1024.0**2, + ) + ) + else: + logger.info( + "[%5d] " + "acc (v/n): %.1f%% " + "recall (v/n): %.1f%% " + "loss (v/n): %.3f " + "[mem: %.2e] " + % ( + itr, + max([a["accuracy"] for a in action_metrics]), + max([a["recall"] for a in action_metrics]), + loss, + torch.cuda.max_memory_allocated() / 1024.0**2, + ) + ) + + del _data_loader + ret = dict( + action=dict( + accuracy=max([a["accuracy"] for a in action_metrics]), + recall=max([a["recall"] for a in action_metrics]), + ), + ) + if action_is_verb_noun: + ret.update( + dict( + verb=dict( + accuracy=max([v["accuracy"] for v in verb_metrics]), + recall=max([v["recall"] for v in verb_metrics]), + ), + noun=dict( + accuracy=max([n["accuracy"] for n in noun_metrics]), + recall=max([n["recall"] for n in noun_metrics]), + ), + ) + ) + return ret + + +def load_checkpoint(device, r_path, classifiers, opt, scaler, val_only=False): + logger.info(f"read-path: {r_path}") + checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) + + # -- loading encoder + msg = [c.load_state_dict(pd) for c, pd in zip(classifiers, checkpoint["classifiers"])] + + if val_only: + logger.info(f"loaded pretrained classifier from epoch with msg: {msg}") + return classifiers, opt, scaler, 0 + + epoch = checkpoint["epoch"] + logger.info(f"loaded pretrained classifier from epoch {epoch} with msg: {msg}") + + # -- loading optimizer + [o.load_state_dict(c) for o, c in zip(opt, checkpoint["opt"])] + + if scaler is not None: + [s.load_state_dict(c) for s, c in zip(scaler, checkpoint["scaler"])] + logger.info(f"loaded optimizers from epoch {epoch}") + + return classifiers, opt, scaler, epoch diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/losses.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..9e490461f43cfed2e9d3ee9ae8558163feaa5ae9 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/losses.py @@ -0,0 +1,49 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch.nn.functional as F + + +def sigmoid_focal_loss( + inputs, + targets, + alpha=0.25, + gamma=2.0, + reduction="sum", + detach=False, +): + """ + Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. + + :param Tensor inputs: Prediction logits for each sample [B x K] + :param Tensor targets: Class label for each sample [B] (long tensor) + :param float alpha: Weight in range (0,1) to balance pos vs neg samples. + :param float gamma: Exponent of modulating factor (1-p_t) to balance easy vs hard samples. + :param str reduction: 'mean' | 'sum' + """ + B, K = inputs.size() # [batch_size, class logits] + + # convert to one-hot targets + targets = F.one_hot(targets, K).float() # [B, K] + + p = F.sigmoid(inputs) + + ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + p_t = p * targets + (1 - p) * (1 - targets) + loss = ce_loss * ((1 - p_t) ** gamma) + + if alpha >= 0: + alpha_t = alpha * targets + (1 - alpha) * (1 - targets) + loss = alpha_t * loss + + if reduction == "mean": + loss = loss.mean() + elif reduction == "sum": + loss = loss.sum() + + if detach: + loss = loss.detach() + + return loss diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/metrics.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..04c5df47570b4803e144183d74a8402cded1d0c8 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/metrics.py @@ -0,0 +1,58 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.distributed as dist +import torch.nn.functional as F + + +class ClassMeanRecall: + + def __init__(self, num_classes: int, device: torch.device, k=5): + self.num_classes = num_classes + self.TP = torch.zeros(num_classes).to(device) + self.FN = torch.zeros(num_classes).to(device) + self.k = k + + def __call__(self, logits, labels, valid_classes=None, eps=1e-8): + """ + :param logits: Tensors of shape [B, num_classes] + :param labels: Tensors of shape [B] + :param valid_classes: set + """ + k, tp_tensor, fn_tensor = self.k, self.TP, self.FN + logits = F.sigmoid(logits) + + if valid_classes is not None: + _logits = torch.zeros(logits.shape).to(logits.device) + for c in valid_classes: + _logits[:, c] = logits[:, c] + logits = _logits + + preds = logits.topk(k, dim=1).indices + + # Loop over batch and check whether all targets are within top-k logit + # predictions for their respective class, if so TP else FN + for p, gt in zip(preds, labels): + if gt in p: + tp_tensor[gt] += 1 + else: + fn_tensor[gt] += 1 + + # Aggregate TP/FN across all workers, but need to detach so that we + # don't accidentally update tp_tensor and fn_tensor, which + # only track local quantities. + TP, FN = tp_tensor.clone(), fn_tensor.clone() + dist.all_reduce(TP) + dist.all_reduce(FN) + + nch = torch.sum((TP + FN) > 0) # num classes hit; may not have TP/FP data for all classes yet + recall = 100.0 * torch.sum(TP / (TP + FN + eps)) / nch # mean class recall + topk = 100.0 * sum(TP) / int(sum(TP + FN)) # accuracy + + return dict( + recall=recall, + accuracy=topk, + ) diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/modelcustom/vit_encoder_predictor_concat_ar.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/modelcustom/vit_encoder_predictor_concat_ar.py new file mode 100644 index 0000000000000000000000000000000000000000..975a908bfd5746b6b72d129bd692b0cfa7d13f52 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/modelcustom/vit_encoder_predictor_concat_ar.py @@ -0,0 +1,224 @@ +""" +Copyright (c) Meta Platforms, Inc. and affiliates. + +This source code is licensed under the MIT license found in the +LICENSE file in the root directory of this source tree. +------------------------------------------------------------------------------ + +modelcustom API requirements: + +API requirements for Encoder module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) + :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) + +API requirements for Predictor module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) + :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch + (shape=[batch_size]) + :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. +""" + +import logging + +import torch + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +def _get_model_modules(pretrain_kwargs): + """Import encoder/predictor modules based on config.""" + use_v2_1 = pretrain_kwargs.get("use_v2_1", False) + if use_v2_1: + import app.vjepa_2_1.models.predictor as vit_pred + import app.vjepa_2_1.models.vision_transformer as vit + else: + import src.models.predictor as vit_pred + import src.models.vision_transformer as vit + return vit, vit_pred + + +def init_module( + frames_per_clip: int, + frames_per_second: int, + resolution: int, + checkpoint: str, + # -- + model_kwargs: dict, + wrapper_kwargs: dict, + **kwargs, +): + logger.info(f"Loading pretrained model from {checkpoint}") + checkpoint = torch.load(checkpoint, map_location="cpu") + + # ----------------------------------------------------------------------- # + # Initialize Encoder + # ----------------------------------------------------------------------- # + vit, vit_pred = _get_model_modules(model_kwargs) + + enc_kwargs = model_kwargs["encoder"] + enc_ckp_key = enc_kwargs.get("checkpoint_key") + enc_model_name = enc_kwargs.get("model_name") + + encoder = vit.__dict__[enc_model_name](img_size=resolution, num_frames=frames_per_clip, **enc_kwargs) + pretrained_dict = checkpoint[enc_ckp_key] + # -- + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + for k, v in encoder.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info(f'key "{k}" is of different shape in model and loaded state dict') + pretrained_dict[k] = v + msg = encoder.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained model with msg: {msg}") + print(encoder) + + # ----------------------------------------------------------------------- # + # Initialize Predictor + # ----------------------------------------------------------------------- # + prd_kwargs = model_kwargs["predictor"] + prd_ckp_key = prd_kwargs.get("checkpoint_key") + prd_model_name = prd_kwargs.get("model_name") + + teacher_embed_dim = prd_kwargs.get("teacher_embed_dim") + n_output_distillation = prd_kwargs.get("n_output_distillation", 4) + prd_out_embed_dim = teacher_embed_dim // n_output_distillation if teacher_embed_dim is not None else None + print(f"[DEBUG] teacher_embed_dim={teacher_embed_dim}, n_output_distillation={n_output_distillation}, prd_out_embed_dim={prd_out_embed_dim}") + print(f"[DEBUG] vit_pred module: {vit_pred.__name__}") + + predictor = vit_pred.__dict__[prd_model_name]( + img_size=resolution, + embed_dim=encoder.embed_dim, + patch_size=encoder.patch_size, + tubelet_size=encoder.tubelet_size, + out_embed_dim=prd_out_embed_dim, + **prd_kwargs, + ) + print(f"[DEBUG] predictor_proj: {predictor.predictor_proj}") + pretrained_dict = checkpoint[prd_ckp_key] + # -- + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + for k, v in predictor.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info( + f'key "{k}" is of different shape in model and loaded state dict: {pretrained_dict[k].shape} vs {v.shape}' + ) + pretrained_dict[k] = v + msg = predictor.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained predictor with msg: {msg}") + print(predictor) + + # ----------------------------------------------------------------------- # + # Build Wrapper + # ----------------------------------------------------------------------- # + model = AnticipativeWrapper( + encoder=encoder, + predictor=predictor, + frames_per_second=frames_per_second, + crop_size=resolution, + patch_size=encoder.patch_size, + tubelet_size=encoder.tubelet_size, + **wrapper_kwargs, + ) + model.embed_dim = encoder.embed_dim + + # Enable hierarchical feature output for non-distilled predictors + if hasattr(predictor, 'hierarchical_layers') and len(predictor.hierarchical_layers) > 1: + encoder.return_hierarchical = True + + return model + + +class AnticipativeWrapper(torch.nn.Module): + """Use predictor for inference""" + + def __init__( + self, + encoder, + predictor, + frames_per_second=4, + crop_size=224, + patch_size=16, + tubelet_size=2, + # -- wrapper kwargs + no_predictor=False, + num_output_frames=2, + num_steps=1, + no_encoder=False, + ): + super().__init__() + self.encoder = encoder + self.predictor = predictor + self.grid_size = crop_size // patch_size + self.tubelet_size = tubelet_size + self.no_predictor = no_predictor + self.num_output_frames = max(num_output_frames, tubelet_size) + self.frames_per_second = frames_per_second + self.num_steps = num_steps + self.no_encoder = no_encoder + + assert not (self.no_predictor and self.no_encoder), "Anticipative wrapper must use predictor or encoder" + + def forward(self, x, anticipation_times): + """ + :param x: (Tensor) video of shape [B, C, T, H, W] + :param anticipation_time: (Tensor) [B] seconds into the future to predict for each sample in batch + """ + x_full = self.encoder(x) + + if self.no_predictor: + return x_full + + B, N, D_full = x_full.size() + embed_dim = self.encoder.embed_dim + use_hierarchical = D_full > embed_dim + + # For the accumulator/classifier, use last-layer features (embed_dim) + # For the predictor, use full hierarchical features (D_full) + if use_hierarchical: + x = x_full[:, :, -embed_dim:] + else: + x = x_full + + if self.no_encoder: + x_accumulate = torch.rand(B, 0, embed_dim).to(x.device) + else: + x_accumulate = x.clone() + + # Position IDs of the encoder patch tokens [B, N] + ctxt_positions = torch.arange(N).unsqueeze(0).repeat(B, 1).to(x.device) + + # Position IDs of tokens to skip for each sample in batch [B] + anticipation_steps = (anticipation_times * self.frames_per_second / self.tubelet_size).to(torch.int64) + skip_positions = N + int(self.grid_size**2) * anticipation_steps + + # Position IDs of tokens to predict [B, N_pred] + N_pred = int(self.grid_size**2 * (self.num_output_frames // self.tubelet_size)) + tgt_positions = torch.arange(N_pred).unsqueeze(0).repeat(B, 1).to(x.device) + tgt_positions += skip_positions.unsqueeze(1).repeat(1, N_pred) + + x_pred_input = x_full + for _ in range(self.num_steps): + pred_out = self.predictor(x_pred_input, masks_x=ctxt_positions, masks_y=tgt_positions) + x_pred_full = pred_out[0] if isinstance(pred_out, tuple) else pred_out + + if x_pred_full.size(-1) != embed_dim: + x_pred = x_pred_full[:, :, -embed_dim:] + else: + x_pred = x_pred_full + + x_accumulate = torch.cat([x_accumulate, x_pred], dim=1) + x_pred_for_input = x_pred_full if x_pred_full.size(-1) == x_pred_input.size(-1) else x_pred + x_pred_input = torch.cat([x_pred_input[:, N_pred:, :], x_pred_for_input], dim=1) + + return x_accumulate diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/models.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/models.py new file mode 100644 index 0000000000000000000000000000000000000000..ececdfe2565660eaa75e15e42f2cf0e67cf509d2 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/models.py @@ -0,0 +1,136 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import importlib +import logging + +import torch +import torch.nn as nn + +from src.models.attentive_pooler import AttentivePooler + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +class AttentiveClassifier(nn.Module): + + def __init__( + self, + verb_classes: dict, + noun_classes: dict, + action_classes: dict, + embed_dim: int, + num_heads: int, + depth: int, + use_activation_checkpointing: bool, + ): + super().__init__() + self.num_verb_classes = len(verb_classes) + num_noun_classes = len(noun_classes) + num_action_classes = len(action_classes) + self.action_only = self.num_verb_classes == 0 + + self.pooler = AttentivePooler( + num_queries=1 if self.action_only else 3, + embed_dim=embed_dim, + num_heads=num_heads, + depth=depth, + use_activation_checkpointing=use_activation_checkpointing, + ) + if not self.action_only: + self.verb_classifier = nn.Linear(embed_dim, self.num_verb_classes, bias=True) + self.noun_classifier = nn.Linear(embed_dim, num_noun_classes, bias=True) + self.action_classifier = nn.Linear(embed_dim, num_action_classes, bias=True) + + def forward(self, x): + if torch.isnan(x).any(): + print("Nan detected at output of encoder") + exit(1) + + x = self.pooler(x) # [B, 2, D] + if not self.action_only: + x_verb, x_noun, x_action = x[:, 0, :], x[:, 1, :], x[:, 2, :] + x_verb = self.verb_classifier(x_verb) + x_noun = self.noun_classifier(x_noun) + x_action = self.action_classifier(x_action) + return dict( + verb=x_verb, + noun=x_noun, + action=x_action, + ) + else: + x_action = x[:, 0, :] + x_action = self.action_classifier(x_action) + return dict(action=x_action) + + +def init_module( + module_name, + device, + frames_per_clip, + frames_per_second, + resolution, + checkpoint, + model_kwargs, + wrapper_kwargs, +): + """ + Build (frozen) model and initialize from pretrained checkpoint + + API requirements for "model" module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) + :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch + (shape=[batch_size]) + :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) + + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. + """ + model = ( + importlib.import_module(f"{module_name}") + .init_module( + frames_per_clip=frames_per_clip, + frames_per_second=frames_per_second, + resolution=resolution, + checkpoint=checkpoint, + model_kwargs=model_kwargs, + wrapper_kwargs=wrapper_kwargs, + ) + .to(device) + ) + model.eval() + for p in model.parameters(): + p.requires_grad = False + print(model) + return model + + +def init_classifier( + embed_dim: int, + num_heads: int, + num_blocks: int, + device: torch.device, + num_classifiers: int, + action_classes: dict, + verb_classes: dict, + noun_classes: dict, +): + classifiers = [ + AttentiveClassifier( + verb_classes=verb_classes, + noun_classes=noun_classes, + action_classes=action_classes, + embed_dim=embed_dim, + num_heads=num_heads, + depth=num_blocks, + use_activation_checkpointing=True, + ).to(device) + for _ in range(num_classifiers) + ] + print(classifiers[0]) + return classifiers diff --git a/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/utils.py b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..42e159f2466b876c0e2943e755aefe85e45e8664 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/action_anticipation_frozen/utils.py @@ -0,0 +1,85 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import math + +import torch + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +def init_opt(classifiers, iterations_per_epoch, opt_kwargs, num_epochs, use_bfloat16=False): + optimizers, schedulers, wd_schedulers, scalers = [], [], [], [] + for c, kwargs in zip(classifiers, opt_kwargs): + param_groups = [ + { + "params": (p for n, p in c.named_parameters()), + "mc_warmup_steps": int(kwargs.get("warmup") * iterations_per_epoch), + "mc_start_lr": kwargs.get("start_lr"), + "mc_ref_lr": kwargs.get("ref_lr"), + "mc_final_lr": kwargs.get("final_lr"), + "mc_ref_wd": kwargs.get("ref_wd"), + "mc_final_wd": kwargs.get("final_wd"), + } + ] + logger.info("Using AdamW") + optimizers += [torch.optim.AdamW(param_groups)] + schedulers += [WarmupCosineLRSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] + wd_schedulers += [CosineWDSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] + scalers += [torch.cuda.amp.GradScaler() if use_bfloat16 else None] + return optimizers, scalers, schedulers, wd_schedulers + + +class WarmupCosineLRSchedule(object): + + def __init__(self, optimizer, T_max, last_epoch=-1): + self.optimizer = optimizer + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + for group in self.optimizer.param_groups: + ref_lr = group.get("mc_ref_lr") + final_lr = group.get("mc_final_lr") + start_lr = group.get("mc_start_lr") + warmup_steps = group.get("mc_warmup_steps") + T_max = self.T_max - warmup_steps + if self._step < warmup_steps: + progress = float(self._step) / float(max(1, warmup_steps)) + new_lr = start_lr + progress * (ref_lr - start_lr) + else: + # -- progress after warmup + progress = float(self._step - warmup_steps) / float(max(1, T_max)) + new_lr = max( + final_lr, + final_lr + (ref_lr - final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)), + ) + group["lr"] = new_lr + + +class CosineWDSchedule(object): + + def __init__(self, optimizer, T_max): + self.optimizer = optimizer + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + progress = self._step / self.T_max + + for group in self.optimizer.param_groups: + ref_wd = group.get("mc_ref_wd") + final_wd = group.get("mc_final_wd") + new_wd = final_wd + (ref_wd - final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress)) + if final_wd <= ref_wd: + new_wd = max(final_wd, new_wd) + else: + new_wd = min(final_wd, new_wd) + group["weight_decay"] = new_wd diff --git a/starVLA/facebookresearch_vjepa2_main/evals/hub/__init__.py b/starVLA/facebookresearch_vjepa2_main/evals/hub/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/facebookresearch_vjepa2_main/evals/hub/preprocessor.py b/starVLA/facebookresearch_vjepa2_main/evals/hub/preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..42c28a77d152083c6fcb9b4a1a748731f02d34b8 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/hub/preprocessor.py @@ -0,0 +1,15 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + + +def _make_transforms(crop_size=256): + from ..video_classification_frozen.utils import make_transforms + + return make_transforms(crop_size=crop_size, training=False) + + +def vjepa2_preprocessor(*, pretrained: bool = True, **kwargs): + crop_size = kwargs.get("crop_size", 256) + return _make_transforms(crop_size=crop_size) diff --git a/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/eval.py b/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..9017cd256288c795d6052aae9b48ae33a7da98ea --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/eval.py @@ -0,0 +1,471 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os + +# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESS +try: + # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE + # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE + # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE + # -- TO EACH PROCESS + os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"] +except Exception: + pass + +import logging +import math +import pprint + +import numpy as np +import torch +import torch.multiprocessing as mp +import torchvision.transforms as transforms +from timm.data import create_transform as timm_make_transforms +from torch.nn.parallel import DistributedDataParallel + +from evals.image_classification_frozen.models import init_module +from src.datasets.data_manager import init_data +from src.models.attentive_pooler import AttentiveClassifier +from src.models.utils.modules import Block, CrossAttentionBlock +from src.utils.checkpoint_loader import robust_checkpoint_loader +from src.utils.distributed import AllReduce, init_distributed +from src.utils.logging import AverageMeter, CSVLogger + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + +_GLOBAL_SEED = 0 +np.random.seed(_GLOBAL_SEED) +torch.manual_seed(_GLOBAL_SEED) +torch.backends.cudnn.benchmark = True + +pp = pprint.PrettyPrinter(indent=4) + + +def main(args_eval, resume_preempt=False): + + # ----------------------------------------------------------------------- # + # PASSED IN PARAMS FROM CONFIG FILE + # ----------------------------------------------------------------------- # + + # -- VAL ONLY + val_only = args_eval.get("val_only", False) + if val_only: + logger.info("VAL ONLY") + + # -- EXPERIMENT + pretrain_folder = args_eval.get("folder", None) + resume_checkpoint = args_eval.get("resume_checkpoint", False) or resume_preempt + eval_tag = args_eval.get("tag", None) + + # -- PRETRAIN + args_pretrain = args_eval.get("model_kwargs") + checkpoint = args_pretrain.get("checkpoint") + module_name = args_pretrain.get("module_name") + args_model = args_pretrain.get("pretrain_kwargs") + args_wrapper = args_pretrain.get("wrapper_kwargs") + + args_exp = args_eval.get("experiment") + + # -- CLASSIFIER + args_classifier = args_exp.get("classifier") + num_probe_blocks = args_classifier.get("num_probe_blocks", 1) + num_heads = args_classifier.get("num_heads", 16) + + # -- DATA + args_data = args_exp.get("data") + dataset_name = args_data.get("dataset_name") + num_classes = args_data.get("num_classes") + root_path = args_data.get("root_path", None) + resolution = args_data.get("resolution", 224) + normalization = args_data.get("normalization", None) + + # -- OPTIMIZATION + args_opt = args_exp.get("optimization") + batch_size = args_opt.get("batch_size") + num_epochs = args_opt.get("num_epochs") + use_bfloat16 = args_opt.get("use_bfloat16") + opt_kwargs = [ + dict( + ref_wd=kwargs.get("weight_decay"), + final_wd=kwargs.get("final_weight_decay"), + start_lr=kwargs.get("start_lr"), + ref_lr=kwargs.get("lr"), + final_lr=kwargs.get("final_lr"), + warmup=kwargs.get("warmup"), + ) + for kwargs in args_opt.get("multihead_kwargs") + ] + # ----------------------------------------------------------------------- # + + try: + mp.set_start_method("spawn") + except Exception: + pass + + if not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device("cuda:0") + torch.cuda.set_device(device) + + world_size, rank = init_distributed() + logger.info(f"Initialized (rank/world-size) {rank}/{world_size}") + + # -- log/checkpointing paths + folder = os.path.join(pretrain_folder, "image_classification_frozen/") + if eval_tag is not None: + folder = os.path.join(folder, eval_tag) + if not os.path.exists(folder): + os.makedirs(folder, exist_ok=True) + log_file = os.path.join(folder, f"log_r{rank}.csv") + latest_path = os.path.join(folder, "latest.pt") + + # -- make csv_logger + if rank == 0: + csv_logger = CSVLogger(log_file, ("%d", "epoch"), ("%.5f", "loss"), ("%.5f", "acc")) + + # -- init models + encoder = init_module( + module_name=module_name, + resolution=resolution, + checkpoint=checkpoint, + model_kwargs=args_model, + wrapper_kwargs=args_wrapper, + device=device, + ) + # -- init classifier + classifiers = [ + AttentiveClassifier( + embed_dim=encoder.embed_dim, + num_heads=num_heads, + depth=num_probe_blocks, + num_classes=num_classes, + use_activation_checkpointing=True, + ).to(device) + for _ in opt_kwargs + ] + classifiers = [DistributedDataParallel(c, static_graph=True) for c in classifiers] + print(classifiers[0]) + + train_loader, train_sampler = make_dataloader( + dataset_name=dataset_name, + root_path=root_path, + img_size=resolution, + batch_size=batch_size, + world_size=world_size, + rank=rank, + training=True, + normalization=normalization, + ) + val_loader, _ = make_dataloader( + dataset_name=dataset_name, + root_path=root_path, + img_size=resolution, + batch_size=batch_size, + world_size=world_size, + rank=rank, + training=False, + normalization=normalization, + ) + ipe = len(train_loader) + logger.info(f"Dataloader created... iterations per epoch: {ipe}") + + # -- optimizer and scheduler + optimizer, scaler, scheduler, wd_scheduler = init_opt( + classifiers=classifiers, + opt_kwargs=opt_kwargs, + iterations_per_epoch=ipe, + num_epochs=num_epochs, + use_bfloat16=use_bfloat16, + ) + + # -- load training checkpoint + start_epoch = 0 + if resume_checkpoint and os.path.exists(latest_path): + classifiers, optimizer, scaler, start_epoch = load_checkpoint( + device=device, + r_path=latest_path, + classifiers=classifiers, + opt=optimizer, + scaler=scaler, + val_only=val_only, + ) + for _ in range(start_epoch * ipe): + [s.step() for s in scheduler] + [wds.step() for wds in wd_scheduler] + + def save_checkpoint(epoch): + all_classifier_dicts = [c.state_dict() for c in classifiers] + all_opt_dicts = [o.state_dict() for o in optimizer] + + save_dict = { + "classifiers": all_classifier_dicts, + "opt": all_opt_dicts, + "scaler": None if scaler is None else [s.state_dict() for s in scaler], + "epoch": epoch, + "batch_size": batch_size, + "world_size": world_size, + } + if rank == 0: + torch.save(save_dict, latest_path) + + # TRAIN LOOP + for epoch in range(start_epoch, num_epochs): + logger.info("Epoch %d" % (epoch + 1)) + train_sampler.set_epoch(epoch) + if val_only: + train_acc = -1.0 + else: + train_acc = run_one_epoch( + device=device, + training=True, + encoder=encoder, + classifiers=classifiers, + scaler=scaler, + optimizer=optimizer, + scheduler=scheduler, + wd_scheduler=wd_scheduler, + data_loader=train_loader, + use_bfloat16=use_bfloat16, + ) + + val_acc = run_one_epoch( + device=device, + training=False, + encoder=encoder, + classifiers=classifiers, + scaler=scaler, + optimizer=optimizer, + scheduler=scheduler, + wd_scheduler=wd_scheduler, + data_loader=val_loader, + use_bfloat16=use_bfloat16, + ) + + logger.info("[%5d] train: %.3f%% test: %.3f%%" % (epoch + 1, train_acc, val_acc)) + if rank == 0: + csv_logger.log(epoch + 1, train_acc, val_acc) + + if val_only: + return + + save_checkpoint(epoch + 1) + + +def run_one_epoch( + device, + training, + encoder, + classifiers, + scaler, + optimizer, + scheduler, + wd_scheduler, + data_loader, + use_bfloat16, +): + + for c in classifiers: + c.train(mode=training) + + criterion = torch.nn.CrossEntropyLoss() + top1_meters = [AverageMeter() for _ in classifiers] + for itr, data in enumerate(data_loader): + if training: + [s.step() for s in scheduler] + [wds.step() for wds in wd_scheduler] + + with torch.cuda.amp.autocast(dtype=torch.float16, enabled=use_bfloat16): + imgs, labels = data[0].to(device), data[1].to(device) + with torch.no_grad(): + outputs = encoder(imgs) + if not training: + outputs = [c(outputs) for c in classifiers] + if training: + outputs = [c(outputs) for c in classifiers] + + losses = [criterion(o, labels) for o in outputs] + top1_accs = [100.0 * o.max(dim=1).indices.eq(labels).sum() / len(imgs) for o in outputs] + top1_accs = [float(AllReduce.apply(t)) for t in top1_accs] + for t1m, t1a in zip(top1_meters, top1_accs): + t1m.update(t1a) + + if training: + if use_bfloat16: + [s.scale(l).backward() for s, l in zip(scaler, losses)] + [s.step(o) for s, o in zip(scaler, optimizer)] + [s.update() for s in scaler] + else: + [loss.backward() for loss in losses] + [o.step() for o in optimizer] + [o.zero_grad() for o in optimizer] + + _agg_top1 = np.array([t1m.avg for t1m in top1_meters]) + if itr % 20 == 0: + logger.info( + "[%5d] %.3f%% [%.3f%% %.3f%%] [mem: %.2e]" + % ( + itr, + _agg_top1.max(), + _agg_top1.mean(), + _agg_top1.min(), + torch.cuda.max_memory_allocated() / 1024.0**2, + ) + ) + + return _agg_top1.max() + + +def load_checkpoint(device, r_path, classifiers, opt, scaler, val_only=False): + checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) + logger.info(f"read-path: {r_path}") + + # -- loading encoder + msg = [c.load_state_dict(pd) for c, pd in zip(classifiers, checkpoint["classifiers"])] + + if val_only: + logger.info(f"loaded pretrained classifier from epoch with msg: {msg}") + return classifiers, opt, scaler, 0 + + epoch = checkpoint["epoch"] + logger.info(f"loaded pretrained classifier from epoch {epoch} with msg: {msg}") + + # -- loading optimizer + [o.load_state_dict(c) for o, c in zip(opt, checkpoint["opt"])] + + if scaler is not None: + [s.load_state_dict(c) for s, c in zip(scaler, checkpoint["scaler"])] + logger.info(f"loaded optimizers from epoch {epoch}") + + return classifiers, opt, scaler, epoch + + +DEFAULT_NORMALIZATION = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) + + +def make_dataloader( + dataset_name, + root_path, + batch_size, + world_size, + rank, + img_size=224, + training=False, + subset_file=None, + normalization=None, +): + if normalization is None: + normalization = DEFAULT_NORMALIZATION + + if training: + logger.info("implementing auto-augment strategy") + transform = timm_make_transforms( + input_size=img_size, + is_training=training, + auto_augment="original", + interpolation="bicubic", + re_prob=0.25, + re_mode="pixel", + re_count=1, + mean=normalization[0], + std=normalization[1], + ) + else: + transform = transforms.Compose( + [ + transforms.Resize(size=int(img_size * 256 / 224)), + transforms.CenterCrop(size=img_size), + transforms.ToTensor(), + transforms.Normalize(normalization[0], normalization[1]), + ] + ) + + data_loader, data_sampler = init_data( + data=dataset_name, + transform=transform, + batch_size=batch_size, + world_size=world_size, + rank=rank, + root_path=root_path, + training=training, + drop_last=False, + subset_file=subset_file, + ) + return data_loader, data_sampler + + +def init_opt(classifiers, iterations_per_epoch, opt_kwargs, num_epochs, use_bfloat16=False): + optimizers, schedulers, wd_schedulers, scalers = [], [], [], [] + for c, kwargs in zip(classifiers, opt_kwargs): + param_groups = [ + { + "params": (p for n, p in c.named_parameters()), + "mc_warmup_steps": int(kwargs.get("warmup") * iterations_per_epoch), + "mc_start_lr": kwargs.get("start_lr"), + "mc_ref_lr": kwargs.get("ref_lr"), + "mc_final_lr": kwargs.get("final_lr"), + "mc_ref_wd": kwargs.get("ref_wd"), + "mc_final_wd": kwargs.get("final_wd"), + } + ] + logger.info("Using AdamW") + optimizers += [torch.optim.AdamW(param_groups)] + schedulers += [WarmupCosineLRSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] + wd_schedulers += [CosineWDSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] + scalers += [torch.cuda.amp.GradScaler() if use_bfloat16 else None] + return optimizers, scalers, schedulers, wd_schedulers + + +class WarmupCosineLRSchedule(object): + + def __init__(self, optimizer, T_max, last_epoch=-1): + self.optimizer = optimizer + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + for group in self.optimizer.param_groups: + ref_lr = group.get("mc_ref_lr") + final_lr = group.get("mc_final_lr") + start_lr = group.get("mc_start_lr") + warmup_steps = group.get("mc_warmup_steps") + T_max = self.T_max - warmup_steps + if self._step < warmup_steps: + progress = float(self._step) / float(max(1, warmup_steps)) + new_lr = start_lr + progress * (ref_lr - start_lr) + else: + # -- progress after warmup + progress = float(self._step - warmup_steps) / float(max(1, T_max)) + new_lr = max( + final_lr, + final_lr + (ref_lr - final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)), + ) + group["lr"] = new_lr + + +class CosineWDSchedule(object): + + def __init__(self, optimizer, T_max): + self.optimizer = optimizer + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + progress = self._step / self.T_max + + for group in self.optimizer.param_groups: + ref_wd = group.get("mc_ref_wd") + final_wd = group.get("mc_final_wd") + new_wd = final_wd + (ref_wd - final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress)) + if final_wd <= ref_wd: + new_wd = max(final_wd, new_wd) + else: + new_wd = min(final_wd, new_wd) + group["weight_decay"] = new_wd diff --git a/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/modelcustom/vit_encoder.py b/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/modelcustom/vit_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..b72f6d0b25d2da00b7c8e83dd347aba9a544b42b --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/modelcustom/vit_encoder.py @@ -0,0 +1,83 @@ +""" +Copyright (c) Meta Platforms, Inc. and affiliates. + +This source code is licensed under the MIT license found in the +LICENSE file in the root directory of this source tree. +------------------------------------------------------------------------------ + +modelcustom API requirements: + +API requirements for Encoder module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) + :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. + +API requirements for Predictor module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) + :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch + (shape=[batch_size]) + :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. +""" + +import logging + +import torch + +import src.models.vision_transformer as vit + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +def init_module( + resolution: int, + checkpoint: str, + # -- + model_kwargs: dict, + wrapper_kwargs: dict, + **kwargs, +): + logger.info(f"Loading pretrained model from {checkpoint=}") + checkpoint = torch.load(checkpoint, map_location="cpu") + + img_as_video_nframes = wrapper_kwargs.get("img_as_video_nframes") + # -- + enc_kwargs = model_kwargs["encoder"] + enc_ckp_key = enc_kwargs.get("checkpoint_key") + enc_model_name = enc_kwargs.get("model_name") + + model = vit.__dict__[enc_model_name]( + input_size=resolution, + num_frames=img_as_video_nframes, + **enc_kwargs, + ) + + def forward_prehook(module, input): + input = input[0] # [B, C, H, W] + input = input.unsqueeze(2).repeat(1, 1, img_as_video_nframes, 1, 1) + return input + + model.register_forward_pre_hook(forward_prehook) + + pretrained_dict = checkpoint[enc_ckp_key] + # -- + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + for k, v in model.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info(f'key "{k}" is of different shape in model and loaded state dict') + pretrained_dict[k] = v + msg = model.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained model with msg: {msg}") + print(model) + + del checkpoint + return model diff --git a/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/models.py b/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/models.py new file mode 100644 index 0000000000000000000000000000000000000000..128fcc48f43e3ed5add785b9fc7406666b6cbfea --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/image_classification_frozen/models.py @@ -0,0 +1,44 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import importlib +import logging + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +def init_module( + module_name, + device, + resolution, + checkpoint, + model_kwargs, + wrapper_kwargs, +): + """ + Build (frozen) model and initialize from pretrained checkpoint + + API requirements for Encoder module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) + :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) + """ + model = ( + importlib.import_module(f"{module_name}") + .init_module( + resolution=resolution, + checkpoint=checkpoint, + model_kwargs=model_kwargs, + wrapper_kwargs=wrapper_kwargs, + ) + .to(device) + ) + model.eval() + for p in model.parameters(): + p.requires_grad = False + print(model) + return model diff --git a/starVLA/facebookresearch_vjepa2_main/evals/main.py b/starVLA/facebookresearch_vjepa2_main/evals/main.py new file mode 100644 index 0000000000000000000000000000000000000000..3df8d4a9b93b2f79a4b3a5d081d1d6499d8072ef --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/main.py @@ -0,0 +1,112 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import argparse +import multiprocessing as mp +import os +import pprint + +import yaml + +from evals.scaffold import main as eval_main +from src.utils.distributed import init_distributed + +parser = argparse.ArgumentParser() +parser.add_argument("--val_only", action="store_true", help="only run eval", default=False) +parser.add_argument("--fname", type=str, help="name of config file to load", default="configs.yaml") +parser.add_argument( + "--devices", + type=str, + nargs="+", + default=["cuda:0", "cuda:1", "cuda:2", "cuda:3", "cuda:4", "cuda:5", "cuda:6", "cuda:7"], + help="which devices to use on local machine", +) +parser.add_argument( + "--debugmode", + type=bool, + default=False, + help="Setting this to true will not spin up new processes. " + "The main code runs the main process, which makes it easier to debug with checkpointing.", +) +parser.add_argument( + "--folder", + type=str, + help="location to save logs", + default="", +) +parser.add_argument("--override_config_folder", action="store_true") +parser.add_argument("--checkpoint", type=str, help="location of pretrained ckpt") +parser.add_argument("--model_name", type=str, help="Model name") +parser.add_argument("--batch_size", type=int) +parser.add_argument("--use_fsdp", action="store_true") + + +def process_main(args, rank, fname, world_size, devices): + import logging + import os + + os.environ["CUDA_VISIBLE_DEVICES"] = str(devices[rank].split(":")[-1]) + + logging.basicConfig() + logger = logging.getLogger() + if rank == 0: + logger.setLevel(logging.INFO) + else: + logger.setLevel(logging.ERROR) + + logger.info(f"called-params {fname}") + + # Load config + params = None + with open(fname, "r") as y_file: + params = yaml.load(y_file, Loader=yaml.FullLoader) + if args.val_only: + params["val_only"] = True + + if args.checkpoint: + params["model_kwargs"]["checkpoint"] = args.checkpoint + + if args.model_name: + params["model_kwargs"]["pretrain_kwargs"]["encoder"]["model_name"] = args.model_name + + if args.batch_size: + params["experiment"]["optimization"]["batch_size"] = args.batch_size + + if args.override_config_folder: + params["folder"] = args.folder + params["use_fsdp"] = args.use_fsdp + logger.info("loaded params...") + + if rank == 0: + pprint.PrettyPrinter(indent=4).pprint(params) + + # Init distributed (access to comm between GPUS on same machine) + world_size, rank = init_distributed(rank_and_world_size=(rank, world_size)) + logger.info(f"Running... (rank: {rank}/{world_size})") + + # Launch the eval with loaded config + eval_main(params["eval_name"], args_eval=params) + + +if __name__ == "__main__": + args = parser.parse_args() + if args.debugmode: + # FSDP debugging (use torchrun) + if args.use_fsdp: + process_main( + args=args, + rank=int(os.environ["RANK"]), + fname=args.fname, + world_size=int(os.environ["WORLD_SIZE"]), + devices=args.devices, + ) + # Single-GPU debugging + else: + process_main(args=args, rank=0, fname=args.fname, world_size=1, devices=["cuda:0"]) + else: + num_gpus = len(args.devices) + mp.set_start_method("spawn") + for rank in range(num_gpus): + mp.Process(target=process_main, args=(args, rank, args.fname, num_gpus, args.devices)).start() diff --git a/starVLA/facebookresearch_vjepa2_main/evals/main_distributed.py b/starVLA/facebookresearch_vjepa2_main/evals/main_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..328204a17102502a2114fcd6bfe3324814e76d91 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/main_distributed.py @@ -0,0 +1,230 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import argparse +import os +import pprint +import time + +import submitit +import yaml + +from evals.scaffold import main as eval_main +from src.utils.logging import get_logger + +logger = get_logger(force=True) + + +try: + USER = os.getlogin() +except OSError: + USER = "default" + +parser = argparse.ArgumentParser() +parser.add_argument("--val_only", action="store_true", help="only run eval", default=False) +parser.add_argument( + "--folder", + type=str, + help="location to save submitit logs", + default=f"/home/{USER}/submitit/", +) +parser.add_argument("--override_config_folder", action="store_true") +parser.add_argument("--checkpoint", type=str, help="location of pretrained ckpt") +parser.add_argument("--model_name", type=str, help="Model name") +parser.add_argument("--batch_size", type=int) +parser.add_argument("--nodes", type=int) +parser.add_argument("--exclude", type=str, help="nodes to exclude from training", default=None) +parser.add_argument( + "--batch-launch", + action="store_true", + help="whether fname points to a file to batch-launch several config files", +) +parser.add_argument( + "--fname", + type=str, + help="yaml file containing config file names to launch", + default="configs.yaml", +) +parser.add_argument( + "--account", + type=str, + default="jepa", + help="Cluster account to use when submitting jobs", +) +parser.add_argument( + "--partition", + type=str, + default="learn", + help="cluster partition to submit jobs on", +) +parser.add_argument( + "--qos", + type=str, + default="lowest", + help="If specified, qos value to use when submitting jobs", +) +parser.add_argument("--time", type=int, default=4300, help="time in minutes to run job") +parser.add_argument("--use_fsdp", action="store_true") + + +class Trainer: + + def __init__(self, args_eval=None, resume_preempt=None): + self.eval_name = args_eval["eval_name"] + self.args_eval = args_eval + self.resume_preempt = resume_preempt + + def __call__(self): + eval_name = self.eval_name + args_eval = self.args_eval + resume_preempt = self.resume_preempt + logger.info("loaded eval params...") + pp = pprint.PrettyPrinter(indent=4) + pp.pprint(args_eval) + + eval_main(eval_name, args_eval=args_eval, resume_preempt=resume_preempt) + + def checkpoint(self): + fb_trainer = Trainer(self.args_eval, True) + return submitit.helpers.DelayedSubmission( + fb_trainer, + ) + + +def launch_evals_with_parsed_args( + args_for_evals, + submitit_folder, + account="jepa", + partition="learn", + qos=None, + timeout=4300, + nodes=1, + tasks_per_node=1, + mem_per_gpu="210G", + cpus_per_task=32, + delay_seconds=10, + exclude_nodes=None, + save_configs=False, + dependency=None, +): + if not isinstance(args_for_evals, list): + logger.info(f"Passed in eval-args of type {type(args_for_evals)}") + args_for_evals = [args_for_evals] + + time.sleep(delay_seconds) + logger.info("Launching evaluations in separate jobs...") + executor = submitit.AutoExecutor(folder=os.path.join(submitit_folder, "job_%j"), slurm_max_num_timeout=20) + executor.update_parameters( + slurm_partition=partition, + slurm_account=account, + slurm_qos=qos, + slurm_mem_per_gpu=mem_per_gpu, + slurm_array_parallelism=64, + timeout_min=timeout, + nodes=nodes, + tasks_per_node=tasks_per_node, + cpus_per_task=cpus_per_task, + gpus_per_node=tasks_per_node, + dependency=dependency, + ) + + if exclude_nodes is not None: + executor.update_parameters(slurm_exclude=exclude_nodes) + + jobs, trainers = [], [] + with executor.batch(): + for ae in args_for_evals: + fb_trainer = Trainer(ae) + job = executor.submit( + fb_trainer, + ) + trainers.append(fb_trainer) + jobs.append(job) + + for job, ae in zip(jobs, args_for_evals): + logger.info(f"Launched eval job with id {job.job_id}") + if save_configs: + params_path = os.path.join(job._paths.folder, "eval-params.yaml") + if not os.path.exists(params_path): + with open(params_path, "w") as f: + yaml.dump(ae, f) + logger.info(f"Wrote eval config to {params_path}") + + +def launch_evals(): + + # ---------------------------------------------------------------------- # + # 1. Put config file names in a list + # ---------------------------------------------------------------------- # + config_fnames = [args.fname] + + # -- If batch-launch is True, then the args.fname yaml file is not a + # -- config, but actually specifies a list of other config files + # -- to run in a slurm job array + if args.batch_launch: + with open(args.fname, "r") as y_file: + config_fnames = yaml.load(y_file, Loader=yaml.FullLoader) + # ---------------------------------------------------------------------- # + + # ---------------------------------------------------------------------- # + # 2. Parse each yaml config file as a dict and place in list + # ---------------------------------------------------------------------- # + nodes, tasks_per_node = None, None + configs = [] + for f in config_fnames: + with open(f, "r") as y_file: + _params = yaml.load(y_file, Loader=yaml.FullLoader) + + if args.val_only: + _params["val_only"] = True + + if args.checkpoint: + _params["model_kwargs"]["checkpoint"] = args.checkpoint + + if args.model_name: + _params["model_kwargs"]["pretrain_kwargs"]["encoder"]["model_name"] = args.model_name + + if args.batch_size: + _params["experiment"]["optimization"]["batch_size"] = args.batch_size + + if args.nodes: + _params["nodes"] = args.nodes + + if args.override_config_folder: + _params["folder"] = args.folder + _params["use_fsdp"] = args.use_fsdp + + nodes = int(_params.get("nodes")) + tasks_per_node = int(_params.get("tasks_per_node")) + mem_per_gpu = _params.get("mem_per_gpu", "220G") + cpus_per_task = _params.get("cpus_per_task", 32) + configs += [_params] + + logger.info(f"Loaded {len(configs)} config files") + logger.info(f"Running all jobs with {nodes=} / {tasks_per_node=}") + # ---------------------------------------------------------------------- # + + # ---------------------------------------------------------------------- # + # 3. Launch evals with parsed config files + # ---------------------------------------------------------------------- # + launch_evals_with_parsed_args( + args_for_evals=configs, + account=args.account, + submitit_folder=args.folder, + partition=args.partition, + qos=args.qos, + mem_per_gpu=mem_per_gpu, + timeout=args.time, + nodes=nodes, + tasks_per_node=tasks_per_node, + cpus_per_task=cpus_per_task, + exclude_nodes=args.exclude, + ) + # ---------------------------------------------------------------------- # + + +if __name__ == "__main__": + args = parser.parse_args() + launch_evals() diff --git a/starVLA/facebookresearch_vjepa2_main/evals/scaffold.py b/starVLA/facebookresearch_vjepa2_main/evals/scaffold.py new file mode 100644 index 0000000000000000000000000000000000000000..5b81aebf1a0f652d9937b9a0f5c23b69f6270aa6 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/scaffold.py @@ -0,0 +1,19 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import importlib + +from src.utils.logging import get_logger + +logger = get_logger("Eval runner scaffold") + + +def main(eval_name, args_eval, resume_preempt=False): + logger.info(f"Running evaluation: {eval_name}") + if eval_name.startswith("app."): + import_path = f"{eval_name}.eval" + else: + import_path = f"evals.{eval_name}.eval" + return importlib.import_module(import_path).main(args_eval=args_eval, resume_preempt=resume_preempt) diff --git a/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/eval.py b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/eval.py new file mode 100644 index 0000000000000000000000000000000000000000..87151254c1c08f66bd7f50260857c4dd37a7a3d3 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/eval.py @@ -0,0 +1,537 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os + +# -- FOR DISTRIBUTED TRAINING ENSURE ONLY 1 DEVICE VISIBLE PER PROCESS +try: + # -- WARNING: IF DOING DISTRIBUTED TRAINING ON A NON-SLURM CLUSTER, MAKE + # -- SURE TO UPDATE THIS TO GET LOCAL-RANK ON NODE, OR ENSURE + # -- THAT YOUR JOBS ARE LAUNCHED WITH ONLY 1 DEVICE VISIBLE + # -- TO EACH PROCESS + os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["SLURM_LOCALID"] +except Exception: + pass + +import logging +import math +import pprint + +import numpy as np +import torch +import torch.multiprocessing as mp +import torch.nn.functional as F +from torch.nn.parallel import DistributedDataParallel + +from evals.video_classification_frozen.models import init_module +from evals.video_classification_frozen.utils import make_transforms +from src.datasets.data_manager import init_data +from src.models.attentive_pooler import AttentiveClassifier +from src.utils.checkpoint_loader import robust_checkpoint_loader +from src.utils.distributed import AllReduce, init_distributed +from src.utils.logging import AverageMeter, CSVLogger + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + +_GLOBAL_SEED = 0 +np.random.seed(_GLOBAL_SEED) +torch.manual_seed(_GLOBAL_SEED) +torch.backends.cudnn.benchmark = True + +pp = pprint.PrettyPrinter(indent=4) + + +def main(args_eval, resume_preempt=False): + + # ----------------------------------------------------------------------- # + # PASSED IN PARAMS FROM CONFIG FILE + # ----------------------------------------------------------------------- # + + # -- VAL ONLY + val_only = args_eval.get("val_only", False) + if val_only: + logger.info("VAL ONLY") + + # -- EXPERIMENT + pretrain_folder = args_eval.get("folder", None) + resume_checkpoint = args_eval.get("resume_checkpoint", False) or resume_preempt + eval_tag = args_eval.get("tag", None) + num_workers = args_eval.get("num_workers", 12) + + # -- PRETRAIN + args_pretrain = args_eval.get("model_kwargs") + checkpoint = args_pretrain.get("checkpoint") + module_name = args_pretrain.get("module_name") + args_model = args_pretrain.get("pretrain_kwargs") + args_wrapper = args_pretrain.get("wrapper_kwargs") + + args_exp = args_eval.get("experiment") + + # -- CLASSIFIER + args_classifier = args_exp.get("classifier") + num_probe_blocks = args_classifier.get("num_probe_blocks", 1) + num_heads = args_classifier.get("num_heads", 16) + + # -- DATA + args_data = args_exp.get("data") + dataset_type = args_data.get("dataset_type", "VideoDataset") + num_classes = args_data.get("num_classes") + train_data_path = [args_data.get("dataset_train")] + val_data_path = [args_data.get("dataset_val")] + resolution = args_data.get("resolution", 224) + num_segments = args_data.get("num_segments", 1) + frames_per_clip = args_data.get("frames_per_clip", 16) + frame_step = args_data.get("frame_step", 4) + duration = args_data.get("clip_duration", None) + num_views_per_segment = args_data.get("num_views_per_segment", 1) + normalization = args_data.get("normalization", None) + + # -- OPTIMIZATION + args_opt = args_exp.get("optimization") + batch_size = args_opt.get("batch_size") + num_epochs = args_opt.get("num_epochs") + use_bfloat16 = args_opt.get("use_bfloat16") + opt_kwargs = [ + dict( + ref_wd=kwargs.get("weight_decay"), + final_wd=kwargs.get("final_weight_decay"), + start_lr=kwargs.get("start_lr"), + ref_lr=kwargs.get("lr"), + final_lr=kwargs.get("final_lr"), + warmup=kwargs.get("warmup"), + ) + for kwargs in args_opt.get("multihead_kwargs") + ] + # ----------------------------------------------------------------------- # + + try: + mp.set_start_method("spawn") + except Exception: + pass + + if not torch.cuda.is_available(): + device = torch.device("cpu") + else: + device = torch.device("cuda:0") + torch.cuda.set_device(device) + + world_size, rank = init_distributed() + logger.info(f"Initialized (rank/world-size) {rank}/{world_size}") + + # -- log/checkpointing paths + folder = os.path.join(pretrain_folder, "video_classification_frozen/") + if eval_tag is not None: + folder = os.path.join(folder, eval_tag) + if not os.path.exists(folder): + os.makedirs(folder, exist_ok=True) + log_file = os.path.join(folder, f"log_r{rank}.csv") + latest_path = os.path.join(folder, "latest.pt") + + # -- make csv_logger + if rank == 0: + csv_logger = CSVLogger(log_file, ("%d", "epoch"), ("%.5f", "train_acc"), ("%.5f", "val_acc")) + + # Initialize model + + # -- init models + encoder = init_module( + module_name=module_name, + frames_per_clip=frames_per_clip, + resolution=resolution, + checkpoint=checkpoint, + model_kwargs=args_model, + wrapper_kwargs=args_wrapper, + device=device, + ) + # -- init classifier + classifiers = [ + AttentiveClassifier( + embed_dim=encoder.embed_dim, + num_heads=num_heads, + depth=num_probe_blocks, + num_classes=num_classes, + use_activation_checkpointing=True, + ).to(device) + for _ in opt_kwargs + ] + classifiers = [DistributedDataParallel(c, static_graph=True) for c in classifiers] + print(classifiers[0]) + + train_loader, train_sampler = make_dataloader( + dataset_type=dataset_type, + root_path=train_data_path, + img_size=resolution, + frames_per_clip=frames_per_clip, + frame_step=frame_step, + eval_duration=duration, + num_segments=num_segments, + num_views_per_segment=1, + allow_segment_overlap=True, + batch_size=batch_size, + world_size=world_size, + rank=rank, + training=True, + num_workers=num_workers, + normalization=normalization, + ) + val_loader, _ = make_dataloader( + dataset_type=dataset_type, + root_path=val_data_path, + img_size=resolution, + frames_per_clip=frames_per_clip, + frame_step=frame_step, + num_segments=num_segments, + eval_duration=duration, + num_views_per_segment=num_views_per_segment, + allow_segment_overlap=True, + batch_size=batch_size, + world_size=world_size, + rank=rank, + training=False, + num_workers=num_workers, + normalization=normalization, + ) + ipe = len(train_loader) + logger.info(f"Dataloader created... iterations per epoch: {ipe}") + + # -- optimizer and scheduler + optimizer, scaler, scheduler, wd_scheduler = init_opt( + classifiers=classifiers, + opt_kwargs=opt_kwargs, + iterations_per_epoch=ipe, + num_epochs=num_epochs, + use_bfloat16=use_bfloat16, + ) + + # -- load training checkpoint + start_epoch = 0 + if resume_checkpoint and os.path.exists(latest_path): + classifiers, optimizer, scaler, start_epoch = load_checkpoint( + device=device, + r_path=latest_path, + classifiers=classifiers, + opt=optimizer, + scaler=scaler, + val_only=val_only, + ) + for _ in range(start_epoch * ipe): + [s.step() for s in scheduler] + [wds.step() for wds in wd_scheduler] + + def save_checkpoint(epoch): + all_classifier_dicts = [c.state_dict() for c in classifiers] + all_opt_dicts = [o.state_dict() for o in optimizer] + + save_dict = { + "classifiers": all_classifier_dicts, + "opt": all_opt_dicts, + "scaler": None if scaler is None else [s.state_dict() for s in scaler], + "epoch": epoch, + "batch_size": batch_size, + "world_size": world_size, + } + if rank == 0: + torch.save(save_dict, latest_path) + + # TRAIN LOOP + for epoch in range(start_epoch, num_epochs): + logger.info("Epoch %d" % (epoch + 1)) + train_sampler.set_epoch(epoch) + if val_only: + train_acc = -1.0 + else: + train_acc = run_one_epoch( + device=device, + training=True, + encoder=encoder, + classifiers=classifiers, + scaler=scaler, + optimizer=optimizer, + scheduler=scheduler, + wd_scheduler=wd_scheduler, + data_loader=train_loader, + use_bfloat16=use_bfloat16, + ) + + val_acc = run_one_epoch( + device=device, + training=False, + encoder=encoder, + classifiers=classifiers, + scaler=scaler, + optimizer=optimizer, + scheduler=scheduler, + wd_scheduler=wd_scheduler, + data_loader=val_loader, + use_bfloat16=use_bfloat16, + ) + + logger.info("[%5d] train: %.3f%% test: %.3f%%" % (epoch + 1, train_acc, val_acc)) + if rank == 0: + csv_logger.log(epoch + 1, train_acc, val_acc) + + if val_only: + return + + save_checkpoint(epoch + 1) + + +def run_one_epoch( + device, + training, + encoder, + classifiers, + scaler, + optimizer, + scheduler, + wd_scheduler, + data_loader, + use_bfloat16, +): + + for c in classifiers: + c.train(mode=training) + + criterion = torch.nn.CrossEntropyLoss() + top1_meters = [AverageMeter() for _ in classifiers] + for itr, data in enumerate(data_loader): + if training: + [s.step() for s in scheduler] + [wds.step() for wds in wd_scheduler] + + with torch.cuda.amp.autocast(dtype=torch.float16, enabled=use_bfloat16): + # Load data and put on GPU + clips = [ + [dij.to(device, non_blocking=True) for dij in di] # iterate over spatial views of clip + for di in data[0] # iterate over temporal index of clip + ] + clip_indices = [d.to(device, non_blocking=True) for d in data[2]] + labels = data[1].to(device) + batch_size = len(labels) + + # Forward and prediction + with torch.no_grad(): + outputs = encoder(clips, clip_indices) + if not training: + outputs = [[c(o) for o in outputs] for c in classifiers] + if training: + outputs = [[c(o) for o in outputs] for c in classifiers] + + # Compute loss + losses = [[criterion(o, labels) for o in coutputs] for coutputs in outputs] + with torch.no_grad(): + outputs = [sum([F.softmax(o, dim=1) for o in coutputs]) / len(coutputs) for coutputs in outputs] + top1_accs = [100.0 * coutputs.max(dim=1).indices.eq(labels).sum() / batch_size for coutputs in outputs] + top1_accs = [float(AllReduce.apply(t1a)) for t1a in top1_accs] + for t1m, t1a in zip(top1_meters, top1_accs): + t1m.update(t1a) + + if training: + if use_bfloat16: + [[s.scale(lij).backward() for lij in li] for s, li in zip(scaler, losses)] + [s.step(o) for s, o in zip(scaler, optimizer)] + [s.update() for s in scaler] + else: + [[lij.backward() for lij in li] for li in losses] + [o.step() for o in optimizer] + [o.zero_grad() for o in optimizer] + + _agg_top1 = np.array([t1m.avg for t1m in top1_meters]) + if itr % 10 == 0: + logger.info( + "[%5d] %.3f%% [%.3f%% %.3f%%] [mem: %.2e]" + % ( + itr, + _agg_top1.max(), + _agg_top1.mean(), + _agg_top1.min(), + torch.cuda.max_memory_allocated() / 1024.0**2, + ) + ) + + return _agg_top1.max() + + +def load_checkpoint(device, r_path, classifiers, opt, scaler, val_only=False): + checkpoint = robust_checkpoint_loader(r_path, map_location=torch.device("cpu")) + logger.info(f"read-path: {r_path}") + + # -- loading encoder + pretrained_dict = checkpoint["classifiers"] + msg = [c.load_state_dict(pd) for c, pd in zip(classifiers, pretrained_dict)] + + if val_only: + logger.info(f"loaded pretrained classifier from epoch with msg: {msg}") + return classifiers, opt, scaler, 0 + + epoch = checkpoint["epoch"] + logger.info(f"loaded pretrained classifier from epoch {epoch} with msg: {msg}") + + # -- loading optimizer + [o.load_state_dict(pd) for o, pd in zip(opt, checkpoint["opt"])] + + if scaler is not None: + [s.load_state_dict(pd) for s, pd in zip(scaler, checkpoint["scaler"])] + + logger.info(f"loaded optimizers from epoch {epoch}") + + return classifiers, opt, scaler, epoch + + +def load_pretrained(encoder, pretrained, checkpoint_key="target_encoder"): + logger.info(f"Loading pretrained model from {pretrained}") + checkpoint = robust_checkpoint_loader(pretrained, map_location="cpu") + try: + pretrained_dict = checkpoint[checkpoint_key] + except Exception: + pretrained_dict = checkpoint["encoder"] + + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + for k, v in encoder.state_dict().items(): + if k not in pretrained_dict: + logger.info(f"key '{k}' could not be found in loaded state dict") + elif pretrained_dict[k].shape != v.shape: + logger.info(f"{pretrained_dict[k].shape} | {v.shape}") + logger.info(f"key '{k}' is of different shape in model and loaded state dict") + exit(1) + pretrained_dict[k] = v + msg = encoder.load_state_dict(pretrained_dict, strict=False) + print(encoder) + logger.info(f"loaded pretrained model with msg: {msg}") + logger.info(f"loaded pretrained encoder from epoch: {checkpoint['epoch']}\n path: {pretrained}") + del checkpoint + return encoder + + +DEFAULT_NORMALIZATION = ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) + + +def make_dataloader( + root_path, + batch_size, + world_size, + rank, + dataset_type="VideoDataset", + img_size=224, + frames_per_clip=16, + frame_step=4, + num_segments=8, + eval_duration=None, + num_views_per_segment=1, + allow_segment_overlap=True, + training=False, + num_workers=12, + subset_file=None, + normalization=None, +): + if normalization is None: + normalization = DEFAULT_NORMALIZATION + + # Make Video Transforms + transform = make_transforms( + training=training, + num_views_per_clip=num_views_per_segment, + random_horizontal_flip=False, + random_resize_aspect_ratio=(0.75, 4 / 3), + random_resize_scale=(0.08, 1.0), + reprob=0.25, + auto_augment=True, + motion_shift=False, + crop_size=img_size, + normalize=normalization, + ) + + data_loader, data_sampler = init_data( + data=dataset_type, + root_path=root_path, + transform=transform, + batch_size=batch_size, + world_size=world_size, + rank=rank, + clip_len=frames_per_clip, + frame_sample_rate=frame_step, + duration=eval_duration, + num_clips=num_segments, + allow_clip_overlap=allow_segment_overlap, + num_workers=num_workers, + drop_last=False, + subset_file=subset_file, + ) + return data_loader, data_sampler + + +def init_opt(classifiers, iterations_per_epoch, opt_kwargs, num_epochs, use_bfloat16=False): + optimizers, schedulers, wd_schedulers, scalers = [], [], [], [] + for c, kwargs in zip(classifiers, opt_kwargs): + param_groups = [ + { + "params": (p for n, p in c.named_parameters()), + "mc_warmup_steps": int(kwargs.get("warmup") * iterations_per_epoch), + "mc_start_lr": kwargs.get("start_lr"), + "mc_ref_lr": kwargs.get("ref_lr"), + "mc_final_lr": kwargs.get("final_lr"), + "mc_ref_wd": kwargs.get("ref_wd"), + "mc_final_wd": kwargs.get("final_wd"), + } + ] + logger.info("Using AdamW") + optimizers += [torch.optim.AdamW(param_groups)] + schedulers += [WarmupCosineLRSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] + wd_schedulers += [CosineWDSchedule(optimizers[-1], T_max=int(num_epochs * iterations_per_epoch))] + scalers += [torch.cuda.amp.GradScaler() if use_bfloat16 else None] + return optimizers, scalers, schedulers, wd_schedulers + + +class WarmupCosineLRSchedule(object): + + def __init__(self, optimizer, T_max, last_epoch=-1): + self.optimizer = optimizer + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + for group in self.optimizer.param_groups: + ref_lr = group.get("mc_ref_lr") + final_lr = group.get("mc_final_lr") + start_lr = group.get("mc_start_lr") + warmup_steps = group.get("mc_warmup_steps") + T_max = self.T_max - warmup_steps + if self._step < warmup_steps: + progress = float(self._step) / float(max(1, warmup_steps)) + new_lr = start_lr + progress * (ref_lr - start_lr) + else: + # -- progress after warmup + progress = float(self._step - warmup_steps) / float(max(1, T_max)) + new_lr = max( + final_lr, + final_lr + (ref_lr - final_lr) * 0.5 * (1.0 + math.cos(math.pi * progress)), + ) + group["lr"] = new_lr + + +class CosineWDSchedule(object): + + def __init__(self, optimizer, T_max): + self.optimizer = optimizer + self.T_max = T_max + self._step = 0.0 + + def step(self): + self._step += 1 + progress = self._step / self.T_max + + for group in self.optimizer.param_groups: + ref_wd = group.get("mc_ref_wd") + final_wd = group.get("mc_final_wd") + new_wd = final_wd + (ref_wd - final_wd) * 0.5 * (1.0 + math.cos(math.pi * progress)) + if final_wd <= ref_wd: + new_wd = max(final_wd, new_wd) + else: + new_wd = min(final_wd, new_wd) + group["weight_decay"] = new_wd diff --git a/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/modelcustom/vit_encoder_multiclip.py b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/modelcustom/vit_encoder_multiclip.py new file mode 100644 index 0000000000000000000000000000000000000000..bace688ac2c15816d5c35e95a292fd4f3eecb7f7 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/modelcustom/vit_encoder_multiclip.py @@ -0,0 +1,149 @@ +""" +Copyright (c) Meta Platforms, Inc. and affiliates. + +This source code is licensed under the MIT license found in the +LICENSE file in the root directory of this source tree. +------------------------------------------------------------------------------ + +modelcustom API requirements: + +API requirements for Encoder module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) + :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. + +API requirements for Predictor module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) + :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch + (shape=[batch_size]) + :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. +""" + +import logging + +import torch +import torch.nn as nn + +import src.models.vision_transformer as vit +from src.masks.utils import apply_masks +from src.models.utils.pos_embs import get_1d_sincos_pos_embed + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +def init_module( + resolution: int, + frames_per_clip: int, + checkpoint: str, + # -- + model_kwargs: dict, + wrapper_kwargs: dict, +): + logger.info(f"Loading pretrained model from {checkpoint}") + checkpoint = torch.load(checkpoint, map_location="cpu") + + enc_kwargs = model_kwargs["encoder"] + enc_ckp_key = enc_kwargs.get("checkpoint_key") + enc_model_name = enc_kwargs.get("model_name") + + model = vit.__dict__[enc_model_name](img_size=resolution, num_frames=frames_per_clip, **enc_kwargs) + + pretrained_dict = checkpoint[enc_ckp_key] + # -- + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + for k, v in model.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info(f'key "{k}" is of different shape in model and loaded state dict') + pretrained_dict[k] = v + msg = model.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained model with msg: {msg}") + print(model) + + model = ClipAggregation( + model, + tubelet_size=model.tubelet_size, + **wrapper_kwargs, + ) + del checkpoint + return model + + +class ClipAggregation(nn.Module): + """ + Process each clip independently and concatenate all tokens + """ + + def __init__( + self, + model, + tubelet_size=2, + max_frames=128, + use_pos_embed=False, + ): + super().__init__() + self.model = model + self.tubelet_size = tubelet_size + self.embed_dim = embed_dim = model.embed_dim + self.num_heads = model.num_heads + + # 1D-temporal pos-embedding + self.pos_embed = None + if use_pos_embed: + max_T = max_frames // tubelet_size + self.pos_embed = nn.Parameter(torch.zeros(1, max_T, embed_dim), requires_grad=False) + sincos = get_1d_sincos_pos_embed(embed_dim, max_T) + self.pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0)) + + def forward(self, x, clip_indices=None): + + num_clips = len(x) + num_views_per_clip = len(x[0]) + B, C, F, H, W = x[0][0].size() + + # Concatenate all spatial and temporal views along batch dimension + x = [torch.cat(xi, dim=0) for xi in x] + x = torch.cat(x, dim=0) + + outputs = self.model(x) + + def multiviews_postprocess(outputs): + _, N, D = outputs.size() + T = F // self.tubelet_size # num temporal indices + S = N // T # num spatial tokens + + # Unroll outputs into a 2D array [spatial_views x temporal_views] + eff_B = B * num_views_per_clip + all_outputs = [[] for _ in range(num_views_per_clip)] + for i in range(num_clips): + o = outputs[i * eff_B : (i + 1) * eff_B] + for j in range(num_views_per_clip): + all_outputs[j].append(o[j * B : (j + 1) * B]) + + for i, outputs in enumerate(all_outputs): + # Concatenate along temporal dimension + outputs = [o.reshape(B, T, S, D) for o in outputs] + outputs = torch.cat(outputs, dim=1).flatten(1, 2) + # Compute positional embedding + if (self.pos_embed is not None) and (clip_indices is not None): + _indices = [c[:, :: self.tubelet_size] for c in clip_indices] + pos_embed = self.pos_embed.repeat(B, 1, 1) # [B, max_T, D] + pos_embed = apply_masks(pos_embed, _indices, concat=False) # list(Tensor([B, T, D])) + pos_embed = torch.cat(pos_embed, dim=1) # concatenate along temporal dimension + pos_embed = pos_embed.unsqueeze(2).repeat(1, 1, S, 1) # [B, T*num_clips, S, D] + pos_embed = pos_embed.flatten(1, 2) + outputs += pos_embed + all_outputs[i] = outputs + + return all_outputs + + return multiviews_postprocess(outputs) diff --git a/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/modelcustom/vit_encoder_multiclip_multilevel.py b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/modelcustom/vit_encoder_multiclip_multilevel.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5300297bfd477d128e3a4268f343ac6fba2c7d --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/modelcustom/vit_encoder_multiclip_multilevel.py @@ -0,0 +1,155 @@ +""" +Copyright (c) Meta Platforms, Inc. and affiliates. + +This source code is licensed under the MIT license found in the +LICENSE file in the root directory of this source tree. +------------------------------------------------------------------------------ + +modelcustom API requirements: + +API requirements for Encoder module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) + :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. + +API requirements for Predictor module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip tokens (shape=[batch_size x num_encoder_tokens x feature_dim]) + :param anticipation_time: (Tensor) Seconds into the future to predict for each sample in batch + (shape=[batch_size]) + :returns: (Tensor) Representations of future frames (shape=[batch_size x num_output_tokens x feature_dim]) + 2) Needs to have a public attribute called 'embed_dim' (int) describing its + output feature dimension. +""" + +import logging + +import torch +import torch.nn as nn + +import src.models.vision_transformer as vit +from src.masks.utils import apply_masks +from src.models.utils.pos_embs import get_1d_sincos_pos_embed + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +def init_module( + resolution: int, + frames_per_clip: int, + checkpoint: str, + # -- + model_kwargs: dict, + wrapper_kwargs: dict, +): + logger.info(f"Loading pretrained model from {checkpoint}") + checkpoint = torch.load(checkpoint, map_location="cpu") + + enc_kwargs = model_kwargs["encoder"] + enc_ckp_key = enc_kwargs.get("checkpoint_key") + enc_model_name = enc_kwargs.get("model_name") + + out_layers = wrapper_kwargs.get("out_layers") + + model = vit.__dict__[enc_model_name]( + img_size=resolution, num_frames=frames_per_clip, out_layers=out_layers, **enc_kwargs + ) + + pretrained_dict = checkpoint[enc_ckp_key] + # -- + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + for k, v in model.state_dict().items(): + if k not in pretrained_dict: + logger.info(f'key "{k}" could not be found in loaded state dict') + elif pretrained_dict[k].shape != v.shape: + logger.info(f'key "{k}" is of different shape in model and loaded state dict') + pretrained_dict[k] = v + msg = model.load_state_dict(pretrained_dict, strict=False) + logger.info(f"loaded pretrained model with msg: {msg}") + print(model) + + model = ClipAggregation( + model, + tubelet_size=model.tubelet_size, + **wrapper_kwargs, + ) + del checkpoint + return model + + +class ClipAggregation(nn.Module): + """ + Process each clip independently and concatenate all tokens + """ + + def __init__( + self, + model, + tubelet_size=2, + max_frames=128, + use_pos_embed=False, + out_layers=None, + ): + super().__init__() + self.model = model + self.tubelet_size = tubelet_size + self.embed_dim = embed_dim = model.embed_dim + self.num_heads = model.num_heads + + # 1D-temporal pos-embedding + self.pos_embed = None + if use_pos_embed: + max_T = max_frames // tubelet_size + self.pos_embed = nn.Parameter(torch.zeros(1, max_T, embed_dim), requires_grad=False) + sincos = get_1d_sincos_pos_embed(embed_dim, max_T) + self.pos_embed.copy_(torch.from_numpy(sincos).float().unsqueeze(0)) + + def forward(self, x, clip_indices=None): + + num_clips = len(x) + num_views_per_clip = len(x[0]) + B, C, F, H, W = x[0][0].size() + + # Concatenate all spatial and temporal views along batch dimension + x = [torch.cat(xi, dim=0) for xi in x] + x = torch.cat(x, dim=0) + + outputs = self.model(x) + outputs = torch.cat(outputs, dim=1) + + def multiviews_postprocess(outputs): + _, N, D = outputs.size() + T = F // self.tubelet_size # num temporal indices + S = N // T # num spatial tokens + + # Unroll outputs into a 2D array [spatial_views x temporal_views] + eff_B = B * num_views_per_clip + all_outputs = [[] for _ in range(num_views_per_clip)] + for i in range(num_clips): + o = outputs[i * eff_B : (i + 1) * eff_B] + for j in range(num_views_per_clip): + all_outputs[j].append(o[j * B : (j + 1) * B]) + + for i, outputs in enumerate(all_outputs): + # Concatenate along temporal dimension + outputs = [o.reshape(B, T, S, D) for o in outputs] + outputs = torch.cat(outputs, dim=1).flatten(1, 2) + # Compute positional embedding + if (self.pos_embed is not None) and (clip_indices is not None): + _indices = [c[:, :: self.tubelet_size] for c in clip_indices] + pos_embed = self.pos_embed.repeat(B, 1, 1) # [B, max_T, D] + pos_embed = apply_masks(pos_embed, _indices, concat=False) # list(Tensor([B, T, D])) + pos_embed = torch.cat(pos_embed, dim=1) # concatenate along temporal dimension + pos_embed = pos_embed.unsqueeze(2).repeat(1, 1, S, 1) # [B, T*num_clips, S, D] + pos_embed = pos_embed.flatten(1, 2) + outputs += pos_embed + all_outputs[i] = outputs + + return all_outputs + + return multiviews_postprocess(outputs) diff --git a/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/models.py b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/models.py new file mode 100644 index 0000000000000000000000000000000000000000..aaeaefdea958c05ab0ee8b4e43fdb6645958f655 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/models.py @@ -0,0 +1,46 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import importlib +import logging + +logging.basicConfig() +logger = logging.getLogger() +logger.setLevel(logging.INFO) + + +def init_module( + module_name, + device, + frames_per_clip, + resolution, + checkpoint, + model_kwargs, + wrapper_kwargs, +): + """ + Build (frozen) model and initialize from pretrained checkpoint + + API requirements for Encoder module: + 1) Needs to be a pytorch module with 'forward()' function protocol: + :param x: (Tensor) Video clip (shape=[batch_size x num_channels x num_frames x height x width]) + :returns: (Tensor) Representations of video clip (shape=[batch_size x num_encoder_tokens x feature_dim]) + """ + model = ( + importlib.import_module(f"{module_name}") + .init_module( + frames_per_clip=frames_per_clip, + resolution=resolution, + checkpoint=checkpoint, + model_kwargs=model_kwargs, + wrapper_kwargs=wrapper_kwargs, + ) + .to(device) + ) + model.eval() + for p in model.parameters(): + p.requires_grad = False + print(model) + return model diff --git a/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/utils.py b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..91b29a22f69f0aaee8a9b66065c7eeb224951046 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/evals/video_classification_frozen/utils.py @@ -0,0 +1,198 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +import torchvision.transforms as transforms + +import src.datasets.utils.video.transforms as video_transforms +import src.datasets.utils.video.volume_transforms as volume_transforms +from src.datasets.utils.video.randerase import RandomErasing + + +def make_transforms( + training=True, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + num_views_per_clip=1, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), +): + + if not training and num_views_per_clip > 1: + print("Making EvalVideoTransform, multi-view") + _frames_augmentation = EvalVideoTransform( + num_views_per_clip=num_views_per_clip, + short_side_size=crop_size, + normalize=normalize, + ) + + else: + _frames_augmentation = VideoTransform( + training=training, + random_horizontal_flip=random_horizontal_flip, + random_resize_aspect_ratio=random_resize_aspect_ratio, + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + crop_size=crop_size, + normalize=normalize, + ) + return _frames_augmentation + + +class VideoTransform(object): + + def __init__( + self, + training=True, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + ): + + self.training = training + + short_side_size = int(crop_size * 256 / 224) + self.eval_transform = video_transforms.Compose( + [ + video_transforms.Resize(short_side_size, interpolation="bilinear"), + video_transforms.CenterCrop(size=(crop_size, crop_size)), + volume_transforms.ClipToTensor(), + video_transforms.Normalize(mean=normalize[0], std=normalize[1]), + ] + ) + + self.random_horizontal_flip = random_horizontal_flip + self.random_resize_aspect_ratio = random_resize_aspect_ratio + self.random_resize_scale = random_resize_scale + self.auto_augment = auto_augment + self.motion_shift = motion_shift + self.crop_size = crop_size + self.normalize = torch.tensor(normalize) + + self.autoaug_transform = video_transforms.create_random_augment( + input_size=(crop_size, crop_size), + auto_augment="rand-m7-n4-mstd0.5-inc1", + interpolation="bicubic", + ) + + self.spatial_transform = ( + video_transforms.random_resized_crop_with_shift if motion_shift else video_transforms.random_resized_crop + ) + + self.reprob = reprob + self.erase_transform = RandomErasing( + reprob, + mode="pixel", + max_count=1, + num_splits=1, + device="cpu", + ) + + def __call__(self, buffer): + + if not self.training: + return [self.eval_transform(buffer)] + + buffer = [transforms.ToPILImage()(frame) for frame in buffer] + + if self.auto_augment: + buffer = self.autoaug_transform(buffer) + + buffer = [transforms.ToTensor()(img) for img in buffer] + buffer = torch.stack(buffer) # T C H W + buffer = buffer.permute(0, 2, 3, 1) # T H W C + + buffer = tensor_normalize(buffer, self.normalize[0], self.normalize[1]) + buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W + + buffer = self.spatial_transform( + images=buffer, + target_height=self.crop_size, + target_width=self.crop_size, + scale=self.random_resize_scale, + ratio=self.random_resize_aspect_ratio, + ) + if self.random_horizontal_flip: + buffer, _ = video_transforms.horizontal_flip(0.5, buffer) + + if self.reprob > 0: + buffer = buffer.permute(1, 0, 2, 3) + buffer = self.erase_transform(buffer) + buffer = buffer.permute(1, 0, 2, 3) + + return [buffer] + + +class EvalVideoTransform(object): + + def __init__( + self, + num_views_per_clip=1, + short_side_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + ): + self.views_per_clip = num_views_per_clip + self.short_side_size = short_side_size + self.spatial_resize = video_transforms.Resize(short_side_size, interpolation="bilinear") + self.to_tensor = video_transforms.Compose( + [ + volume_transforms.ClipToTensor(), + video_transforms.Normalize(mean=normalize[0], std=normalize[1]), + ] + ) + + def __call__(self, buffer): + + # Sample several spatial views of each clip + buffer = np.array(self.spatial_resize(buffer)) + T, H, W, C = buffer.shape + + num_views = self.views_per_clip + side_len = self.short_side_size + spatial_step = (max(H, W) - side_len) // (num_views - 1) + + all_views = [] + for i in range(num_views): + start = i * spatial_step + if H > W: + view = buffer[:, start : start + side_len, :, :] + else: + view = buffer[:, :, start : start + side_len, :] + view = self.to_tensor(view) + all_views.append(view) + + return all_views + + +def tensor_normalize(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize. + mean (tensor or list): mean value to subtract. + std (tensor or list): std to divide. + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + tensor = tensor / 255.0 + if isinstance(mean, list): + mean = torch.tensor(mean) + if isinstance(std, list): + std = torch.tensor(std) + tensor = tensor - mean + tensor = tensor / std + return tensor diff --git a/starVLA/facebookresearch_vjepa2_main/hubconf.py b/starVLA/facebookresearch_vjepa2_main/hubconf.py new file mode 100644 index 0000000000000000000000000000000000000000..39f303d5d8a87cc754593e951b9d6c5bd910b938 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/hubconf.py @@ -0,0 +1,19 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from evals.hub.preprocessor import vjepa2_preprocessor +from src.hub.backbones import ( + vjepa2_ac_vit_giant, + vjepa2_vit_giant, + vjepa2_vit_giant_384, + vjepa2_vit_huge, + vjepa2_vit_large, + vjepa2_1_vit_base_384, + vjepa2_1_vit_large_384, + vjepa2_1_vit_giant_384, + vjepa2_1_vit_gigantic_384, +) + +dependencies = ["torch", "timm", "einops"] diff --git a/starVLA/facebookresearch_vjepa2_main/notebooks/utils/mpc_utils.py b/starVLA/facebookresearch_vjepa2_main/notebooks/utils/mpc_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3314d720bc862cf32ec802e20b9d30b023872e0c --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/notebooks/utils/mpc_utils.py @@ -0,0 +1,226 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import numpy as np +import torch +from scipy.spatial.transform import Rotation +from tqdm import tqdm + +from src.utils.logging import get_logger + +logger = get_logger(__name__, force=True) + + +def l1(a, b): + return torch.mean(torch.abs(a - b), dim=-1) + + +def round_small_elements(tensor, threshold): + mask = torch.abs(tensor) < threshold + new_tensor = tensor.clone() + new_tensor[mask] = 0 + return new_tensor + + +def cem( + context_frame, + context_pose, + goal_frame, + world_model, + rollout=1, + cem_steps=100, + momentum_mean=0.25, + momentum_std=0.95, + momentum_mean_gripper=0.15, + momentum_std_gripper=0.15, + samples=100, + topk=10, + verbose=False, + maxnorm=0.05, + axis={}, + objective=l1, + close_gripper=None, +): + """ + :param context_frame: [B=1, T=1, HW, D] + :param goal_frame: [B=1, T=1, HW, D] + :param world_model: f(context_frame, action) -> next_frame [B, 1, HW, D] + :return: [B=1, rollout, 7] an action trajectory over rollout horizon + + Cross-Entropy Method + ----------------------- + 1. for rollout horizon: + 1.1. sample several actions + 1.2. compute next states using WM + 3. compute similarity of final states to goal_frames + 4. select topk samples and update mean and std using topk action trajs + 5. choose final action to be mean of distribution + """ + context_frame = context_frame.repeat(samples, 1, 1, 1) # Reshape to [S, 1, HW, D] + goal_frame = goal_frame.repeat(samples, 1, 1, 1) # Reshape to [S, 1, HW, D] + context_pose = context_pose.repeat(samples, 1, 1) # Reshape to [S, 1, 7] + + # Current estimate of the mean/std of distribution over action trajectories + mean = torch.cat( + [ + torch.zeros((rollout, 3), device=context_frame.device), + torch.zeros((rollout, 1), device=context_frame.device), + ], + dim=-1, + ) + + std = torch.cat( + [ + torch.ones((rollout, 3), device=context_frame.device) * maxnorm, + torch.ones((rollout, 1), device=context_frame.device), + ], + dim=-1, + ) + + for ax in axis.keys(): + mean[:, ax] = axis[ax] + + def sample_action_traj(): + """Sample several action trajectories""" + action_traj, frame_traj, pose_traj = None, context_frame, context_pose + + for h in range(rollout): + + # -- sample new action + action_samples = torch.randn(samples, mean.size(1), device=mean.device) * std[h] + mean[h] + action_samples[:, :3] = torch.clip(action_samples[:, :3], min=-maxnorm, max=maxnorm) + action_samples[:, -1:] = torch.clip(action_samples[:, -1:], min=-0.75, max=0.75) + for ax in axis.keys(): + action_samples[:, ax] = axis[ax] + action_samples = torch.cat( + [ + action_samples[:, :3], + torch.zeros((len(action_samples), 3), device=mean.device), + action_samples[:, -1:], + ], + dim=-1, + )[:, None] + if close_gripper is not None and h >= close_gripper: + action_samples[:, :, -1] = 1.0 + + action_traj = ( + torch.cat([action_traj, action_samples], dim=1) if action_traj is not None else action_samples + ) + + # -- compute next state + next_frame, next_pose = world_model(frame_traj, action_traj, pose_traj) + frame_traj = torch.cat([frame_traj, next_frame], dim=1) + pose_traj = torch.cat([pose_traj, next_pose], dim=1) + + return action_traj, frame_traj + + def select_topk_action_traj(final_state, goal_state, actions): + """Get the topk action trajectories that bring us closest to goal""" + sims = objective(final_state.flatten(1), goal_state.flatten(1)) + indices = sims.topk(topk, largest=False).indices + selected_actions = actions[indices] + return selected_actions + + for step in tqdm(range(cem_steps), disable=True): + action_traj, frame_traj = sample_action_traj() + selected_actions = select_topk_action_traj( + final_state=frame_traj[:, -1], goal_state=goal_frame, actions=action_traj + ) + mean_selected_actions = selected_actions.mean(dim=0) + std_selected_actions = selected_actions.std(dim=0) + + # -- Update new sampling mean and std based on the top-k samples + mean = torch.cat( + [ + mean_selected_actions[..., :3] * (1.0 - momentum_mean) + mean[..., :3] * momentum_mean, + mean_selected_actions[..., -1:] * (1.0 - momentum_mean_gripper) + + mean[..., -1:] * momentum_mean_gripper, + ], + dim=-1, + ) + std = torch.cat( + [ + std_selected_actions[..., :3] * (1.0 - momentum_std) + std[..., :3] * momentum_std, + std_selected_actions[..., -1:] * (1.0 - momentum_std_gripper) + std[..., -1:] * momentum_std_gripper, + ], + dim=-1, + ) + + logger.info(f"new mean: {mean.sum(dim=0)} {std.sum(dim=0)}") + + new_action = torch.cat( + [ + mean[..., :3], + torch.zeros((rollout, 3), device=mean.device), + round_small_elements(mean[..., -1:], 0.25), + ], + dim=-1, + )[None, :] + + return new_action + + +def compute_new_pose(pose, action): + """ + :param pose: [B, T=1, 7] + :param action: [B, T=1, 7] + :returns: [B, T=1, 7] + """ + device, dtype = pose.device, pose.dtype + pose = pose[:, 0].cpu().numpy() + action = action[:, 0].cpu().numpy() + # -- compute delta xyz + new_xyz = pose[:, :3] + action[:, :3] + # -- compute delta theta + thetas = pose[:, 3:6] + delta_thetas = action[:, 3:6] + matrices = [Rotation.from_euler("xyz", theta, degrees=False).as_matrix() for theta in thetas] + delta_matrices = [Rotation.from_euler("xyz", theta, degrees=False).as_matrix() for theta in delta_thetas] + angle_diff = [delta_matrices[t] @ matrices[t] for t in range(len(matrices))] + angle_diff = [Rotation.from_matrix(mat).as_euler("xyz", degrees=False) for mat in angle_diff] + new_angle = np.stack([d for d in angle_diff], axis=0) # [B, 7] + # -- compute delta gripper + new_closedness = pose[:, -1:] + action[:, -1:] + new_closedness = np.clip(new_closedness, 0, 1) + # -- new pose + new_pose = np.concatenate([new_xyz, new_angle, new_closedness], axis=-1) + return torch.from_numpy(new_pose).to(device).to(dtype)[:, None] + + +def poses_to_diff(start, end): + """ + :param start: [7] + :param end: [7] + """ + try: + start = start.numpy() + end = end.numpy() + except Exception: + pass + + # -- + + s_xyz = start[:3] + e_xyz = end[:3] + xyz_diff = e_xyz - s_xyz + + # -- + + s_thetas = start[3:6] + e_thetas = end[3:6] + s_rotation = Rotation.from_euler("xyz", s_thetas, degrees=False).as_matrix() + e_rotation = Rotation.from_euler("xyz", e_thetas, degrees=False).as_matrix() + rotation_diff = e_rotation @ s_rotation.T + theta_diff = Rotation.from_matrix(rotation_diff).as_euler("xyz", degrees=False) + + # -- + + s_gripper = start[-1:] + e_gripper = end[-1:] + gripper_diff = e_gripper - s_gripper + + action = np.concatenate([xyz_diff, theta_diff, gripper_diff], axis=0) + return torch.from_numpy(action) diff --git a/starVLA/facebookresearch_vjepa2_main/notebooks/utils/world_model_wrapper.py b/starVLA/facebookresearch_vjepa2_main/notebooks/utils/world_model_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0a79e9f53bff741e17160b107dfb8a3348042d --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/notebooks/utils/world_model_wrapper.py @@ -0,0 +1,75 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch.nn.functional as F + +from .mpc_utils import cem, compute_new_pose + + +class WorldModel(object): + + def __init__( + self, + encoder, + predictor, + tokens_per_frame, + transform, + mpc_args={ + "rollout": 2, + "samples": 400, + "topk": 10, + "cem_steps": 10, + "momentum_mean": 0.15, + "momentum_std": 0.15, + "maxnorm": 0.05, + "verbose": True, + }, + normalize_reps=True, + device="cuda:0", + ): + super().__init__() + self.encoder = encoder + self.predictor = predictor + self.normalize_reps = normalize_reps + self.transform = transform + self.tokens_per_frame = tokens_per_frame + self.device = device + self.mpc_args = mpc_args + + def encode(self, image): + clip = np.expand_dims(image, axis=0) + clip = self.transform(clip)[None, :] + B, C, T, H, W = clip.size() + clip = clip.permute(0, 2, 1, 3, 4).flatten(0, 1).unsqueeze(2).repeat(1, 1, 2, 1, 1) + clip = clip.to(self.device, non_blocking=True) + h = self.encoder(clip) + h = h.view(B, T, -1, h.size(-1)).flatten(1, 2) + if self.normalize_reps: + h = F.layer_norm(h, (h.size(-1),)) + return h + + def infer_next_action(self, rep, pose, goal_rep, close_gripper=None): + + def step_predictor(reps, actions, poses): + B, T, N_T, D = reps.size() + reps = reps.flatten(1, 2) + next_rep = self.predictor(reps, actions, poses)[:, -self.tokens_per_frame :] + if self.normalize_reps: + next_rep = F.layer_norm(next_rep, (next_rep.size(-1),)) + next_rep = next_rep.view(B, 1, N_T, D) + next_pose = compute_new_pose(poses[:, -1:], actions[:, -1:]) + return next_rep, next_pose + + mpc_action = cem( + context_frame=rep, + context_pose=pose, + goal_frame=goal_rep, + world_model=step_predictor, + close_gripper=close_gripper, + **self.mpc_args, + )[0] + + return mpc_action diff --git a/starVLA/facebookresearch_vjepa2_main/notebooks/vjepa2_demo.py b/starVLA/facebookresearch_vjepa2_main/notebooks/vjepa2_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..625c71125893e8ce02b2d3fd1dfe41d8f64cf3dc --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/notebooks/vjepa2_demo.py @@ -0,0 +1,171 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import json +import os +import subprocess + +import numpy as np +import torch +import torch.nn.functional as F +from decord import VideoReader +from transformers import AutoModel, AutoVideoProcessor + +import src.datasets.utils.video.transforms as video_transforms +import src.datasets.utils.video.volume_transforms as volume_transforms +from src.models.attentive_pooler import AttentiveClassifier +from src.models.vision_transformer import vit_giant_xformers_rope + +IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) +IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225) + + +def load_pretrained_vjepa_pt_weights(model, pretrained_weights): + # Load weights of the VJEPA2 encoder + # The PyTorch state_dict is already preprocessed to have the right key names + pretrained_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu")["encoder"] + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()} + msg = model.load_state_dict(pretrained_dict, strict=False) + print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) + + +def load_pretrained_vjepa_classifier_weights(model, pretrained_weights): + # Load weights of the VJEPA2 classifier + # The PyTorch state_dict is already preprocessed to have the right key names + pretrained_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu")["classifiers"][0] + pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()} + msg = model.load_state_dict(pretrained_dict, strict=False) + print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg)) + + +def build_pt_video_transform(img_size): + short_side_size = int(256.0 / 224 * img_size) + # Eval transform has no random cropping nor flip + eval_transform = video_transforms.Compose( + [ + video_transforms.Resize(short_side_size, interpolation="bilinear"), + video_transforms.CenterCrop(size=(img_size, img_size)), + volume_transforms.ClipToTensor(), + video_transforms.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), + ] + ) + return eval_transform + + +def get_video(): + vr = VideoReader("sample_video.mp4") + # choosing some frames here, you can define more complex sampling strategy + frame_idx = np.arange(0, 128, 2) + video = vr.get_batch(frame_idx).asnumpy() + return video + + +def forward_vjepa_video(model_hf, model_pt, hf_transform, pt_transform): + # Run a sample inference with VJEPA + with torch.inference_mode(): + # Read and pre-process the image + video = get_video() # T x H x W x C + video = torch.from_numpy(video).permute(0, 3, 1, 2) # T x C x H x W + x_pt = pt_transform(video).cuda().unsqueeze(0) + x_hf = hf_transform(video, return_tensors="pt")["pixel_values_videos"].to("cuda") + # Extract the patch-wise features from the last layer + out_patch_features_pt = model_pt(x_pt) + out_patch_features_hf = model_hf.get_vision_features(x_hf) + + return out_patch_features_hf, out_patch_features_pt + + +def get_vjepa_video_classification_results(classifier, out_patch_features_pt): + SOMETHING_SOMETHING_V2_CLASSES = json.load(open("ssv2_classes.json", "r")) + + with torch.inference_mode(): + out_classifier = classifier(out_patch_features_pt) + + print(f"Classifier output shape: {out_classifier.shape}") + + print("Top 5 predicted class names:") + top5_indices = out_classifier.topk(5).indices[0] + top5_probs = F.softmax(out_classifier.topk(5).values[0]) * 100.0 # convert to percentage + for idx, prob in zip(top5_indices, top5_probs): + str_idx = str(idx.item()) + print(f"{SOMETHING_SOMETHING_V2_CLASSES[str_idx]} ({prob}%)") + + return + + +def run_sample_inference(): + # HuggingFace model repo name + hf_model_name = ( + "facebook/vjepa2-vitg-fpc64-384" # Replace with your favored model, e.g. facebook/vjepa2-vitg-fpc64-384 + ) + # Path to local PyTorch weights + pt_model_path = "YOUR_MODEL_PATH" + + sample_video_path = "sample_video.mp4" + # Download the video if not yet downloaded to local path + if not os.path.exists(sample_video_path): + video_url = "https://huggingface.co/datasets/nateraw/kinetics-mini/resolve/main/val/bowling/-WH-lxmGJVY_000005_000015.mp4" + command = ["wget", video_url, "-O", sample_video_path] + subprocess.run(command) + print("Downloading video") + + # Initialize the HuggingFace model, load pretrained weights + model_hf = AutoModel.from_pretrained(hf_model_name) + model_hf.cuda().eval() + + # Build HuggingFace preprocessing transform + hf_transform = AutoVideoProcessor.from_pretrained(hf_model_name) + img_size = hf_transform.crop_size["height"] # E.g. 384, 256, etc. + + # Initialize the PyTorch model, load pretrained weights + model_pt = vit_giant_xformers_rope(img_size=(img_size, img_size), num_frames=64) + model_pt.cuda().eval() + load_pretrained_vjepa_pt_weights(model_pt, pt_model_path) + + # Build PyTorch preprocessing transform + pt_video_transform = build_pt_video_transform(img_size=img_size) + + # Inference on video + out_patch_features_hf, out_patch_features_pt = forward_vjepa_video( + model_hf, model_pt, hf_transform, pt_video_transform + ) + + print( + f""" + Inference results on video: + HuggingFace output shape: {out_patch_features_hf.shape} + PyTorch output shape: {out_patch_features_pt.shape} + Absolute difference sum: {torch.abs(out_patch_features_pt - out_patch_features_hf).sum():.6f} + Close: {torch.allclose(out_patch_features_pt, out_patch_features_hf, atol=1e-3, rtol=1e-3)} + """ + ) + + # Initialize the classifier + classifier_model_path = "YOUR_ATTENTIVE_PROBE_PATH" + classifier = ( + AttentiveClassifier(embed_dim=model_pt.embed_dim, num_heads=16, depth=4, num_classes=174).cuda().eval() + ) + load_pretrained_vjepa_classifier_weights(classifier, classifier_model_path) + + # Download SSV2 classes if not already present + ssv2_classes_path = "ssv2_classes.json" + if not os.path.exists(ssv2_classes_path): + command = [ + "wget", + "https://huggingface.co/datasets/huggingface/label-files/resolve/d79675f2d50a7b1ecf98923d42c30526a51818e2/" + "something-something-v2-id2label.json", + "-O", + "ssv2_classes.json", + ] + subprocess.run(command) + print("Downloading SSV2 classes") + + get_vjepa_video_classification_results(classifier, out_patch_features_pt) + + +if __name__ == "__main__": + # Run with: `python -m notebooks.vjepa2_demo` + run_sample_inference() diff --git a/starVLA/facebookresearch_vjepa2_main/pyproject.toml b/starVLA/facebookresearch_vjepa2_main/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..5019837b40c520d90867f848c8473eb5b3a179dc --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/pyproject.toml @@ -0,0 +1,6 @@ +[tool.isort] +profile="black" +line_length=119 + +[tool.black] +line-length = 119 diff --git a/starVLA/facebookresearch_vjepa2_main/requirements-test.txt b/starVLA/facebookresearch_vjepa2_main/requirements-test.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb6592b4f7a11f03b83cb6bb7df318570dcf352a --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/requirements-test.txt @@ -0,0 +1,4 @@ +# Tools for static checking. +black == 26.3.1 +flake8 == 7.0.0 +isort == 5.13.2 \ No newline at end of file diff --git a/starVLA/facebookresearch_vjepa2_main/requirements.txt b/starVLA/facebookresearch_vjepa2_main/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d24b0b351dee9fbe273d40598feedaadbb9aa7ab --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/requirements.txt @@ -0,0 +1,25 @@ +torch>=2 +torchvision +tensorboard +wandb +iopath +pyyaml +numpy +opencv-python +submitit +braceexpand +webdataset +timm +transformers +peft +decord +pandas +einops +beartype +psutil +h5py +fire +python-box +scikit-image +ftfy +jupyter diff --git a/starVLA/facebookresearch_vjepa2_main/setup.py b/starVLA/facebookresearch_vjepa2_main/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..da9c84c1d147a27eae1c89072be793f44bcc1e32 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/setup.py @@ -0,0 +1,28 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from setuptools import setup + +NAME = "vjepa2" +VERSION = "0.0.2" +DESCRIPTION = "PyTorch code and models for V-JEPA 2." +URL = "https://github.com/facebookresearch/vjepa2" + + +def get_requirements(): + with open("./requirements.txt") as reqsf: + reqs = reqsf.readlines() + return reqs + + +if __name__ == "__main__": + setup( + name=NAME, + version=VERSION, + description=DESCRIPTION, + url=URL, + python_requires=">=3.11", + install_requires=get_requirements(), + ) diff --git a/starVLA/facebookresearch_vjepa2_main/src/__init__.py b/starVLA/facebookresearch_vjepa2_main/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/data_manager.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/data_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..d4e1a53478aa051bf4989ec524055fd64e37f6f3 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/data_manager.py @@ -0,0 +1,88 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from logging import getLogger + +_GLOBAL_SEED = 0 +logger = getLogger() + + +def init_data( + batch_size, + transform=None, + shared_transform=None, + data="ImageNet", + collator=None, + pin_mem=True, + num_workers=8, + world_size=1, + rank=0, + root_path=None, + training=True, + drop_last=True, + subset_file=None, + clip_len=None, + dataset_fpcs=None, + frame_sample_rate=None, + duration=None, + fps=None, + num_clips=1, + random_clip_sampling=True, + allow_clip_overlap=False, + filter_short_videos=False, + filter_long_videos=int(1e9), + datasets_weights=None, + persistent_workers=False, + deterministic=True, + log_dir=None, +): + if data.lower() == "imagenet": + from src.datasets.imagenet1k import make_imagenet1k + + dataset, data_loader, dist_sampler = make_imagenet1k( + transform=transform, + batch_size=batch_size, + collator=collator, + pin_mem=pin_mem, + training=training, + num_workers=num_workers, + world_size=world_size, + rank=rank, + root_path=root_path, + persistent_workers=persistent_workers, + drop_last=drop_last, + subset_file=subset_file, + ) + + elif data.lower() == "videodataset": + from src.datasets.video_dataset import make_videodataset + + dataset, data_loader, dist_sampler = make_videodataset( + data_paths=root_path, + batch_size=batch_size, + frames_per_clip=clip_len, + dataset_fpcs=dataset_fpcs, + frame_step=frame_sample_rate, + duration=duration, + fps=fps, + num_clips=num_clips, + random_clip_sampling=random_clip_sampling, + allow_clip_overlap=allow_clip_overlap, + filter_short_videos=filter_short_videos, + filter_long_videos=filter_long_videos, + shared_transform=shared_transform, + transform=transform, + datasets_weights=datasets_weights, + collator=collator, + num_workers=num_workers, + pin_mem=pin_mem, + persistent_workers=persistent_workers, + world_size=world_size, + rank=rank, + deterministic=deterministic, + log_dir=log_dir, + ) + + return (data_loader, dist_sampler) diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/imagenet1k.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/imagenet1k.py new file mode 100644 index 0000000000000000000000000000000000000000..55603632af17f0228c5717ff73472b8d3df5a544 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/imagenet1k.py @@ -0,0 +1,150 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import os +import subprocess +import time +from logging import getLogger + +import numpy as np +import torch +import torchvision + +_GLOBAL_SEED = 0 +logger = getLogger() + + +class ImageNet(torchvision.datasets.ImageFolder): + + def __init__( + self, + root, + tar_file="imagenet_full_size-061417.tar.gz", + transform=None, + train=True, + job_id=None, + local_rank=None, + index_targets=False, + ): + """ + ImageNet + + Dataset wrapper + + :param root: root network directory for ImageNet data + :param tar_file: zipped image_folder inside root network directory + :param train: whether to load train data (or validation) + :param job_id: scheduler job-id used to create dir on local machine + :param index_targets: whether to index the id of each labeled image + """ + + suffix = "train/" if train else "val/" + data_path = os.path.join(root, suffix) + logger.info(f"data-path {data_path}") + + super(ImageNet, self).__init__(root=data_path, transform=transform) + logger.info("Initialized ImageNet") + + if index_targets: + self.targets = [] + for sample in self.samples: + self.targets.append(sample[1]) + self.targets = np.array(self.targets) + self.samples = np.array(self.samples) + + mint = None + self.target_indices = [] + for t in range(len(self.classes)): + indices = np.squeeze(np.argwhere(self.targets == t)).tolist() + self.target_indices.append(indices) + mint = len(indices) if mint is None else min(mint, len(indices)) + logger.debug(f"num-labeled target {t} {len(indices)}") + logger.info(f"min. labeled indices {mint}") + + +class ImageNetSubset(object): + + def __init__(self, dataset, subset_file): + """ + ImageNetSubset + + :param dataset: ImageNet dataset object + :param subset_file: '.txt' file containing IDs of IN1K images to keep + """ + self.dataset = dataset + self.subset_file = subset_file + self.filter_dataset_(subset_file) + + def filter_dataset_(self, subset_file): + """Filter self.dataset to a subset""" + root = self.dataset.root + class_to_idx = self.dataset.class_to_idx + # -- update samples to subset of IN1k targets/samples + new_samples = [] + logger.info(f"Using {subset_file}") + with open(subset_file, "r") as rfile: + for line in rfile: + class_name = line.split("_")[0] + target = class_to_idx[class_name] + img = line.split("\n")[0] + new_samples.append((os.path.join(root, class_name, img), target)) + self.samples = new_samples + + @property + def classes(self): + return self.dataset.classes + + def __len__(self): + return len(self.samples) + + def __getitem__(self, index): + path, target = self.samples[index] + img = self.dataset.loader(path) + if self.dataset.transform is not None: + img = self.dataset.transform(img) + if self.dataset.target_transform is not None: + target = self.dataset.target_transform(target) + return img, target + + +def make_imagenet1k( + transform, + batch_size, + collator=None, + pin_mem=True, + num_workers=8, + world_size=1, + rank=0, + root_path=None, + training=True, + drop_last=True, + persistent_workers=False, + subset_file=None, +): + dataset = ImageNet( + root=root_path, + transform=transform, + train=training, + index_targets=False, + ) + if subset_file is not None: + dataset = ImageNetSubset(dataset, subset_file) + logger.info("ImageNet dataset created") + dist_sampler = torch.utils.data.distributed.DistributedSampler( + dataset=dataset, num_replicas=world_size, rank=rank + ) + data_loader = torch.utils.data.DataLoader( + dataset, + collate_fn=collator, + sampler=dist_sampler, + batch_size=batch_size, + drop_last=drop_last, + pin_memory=pin_mem, + num_workers=num_workers, + persistent_workers=persistent_workers, + ) + logger.info("ImageNet unsupervised data loader created") + + return dataset, data_loader, dist_sampler diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/dataloader.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..846f9795d6b24dc043be4477ccec292677b297fc --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/dataloader.py @@ -0,0 +1,234 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import bisect +import csv +import io +import time + +import numpy as np +import torch +from torch.utils.data import _utils +from torch.utils.data.dataloader import ExceptionWrapper, _DatasetKind, _MultiProcessingDataLoaderIter + +from src.utils.monitoring import ResourceMonitoringThread + + +class ConcatIndices: + """Helper to map indices of concatenated/mixed datasets to the sample index for the corresponding dataset.""" + + cumulative_sizes: np.ndarray + + def __init__(self, sizes): + self.cumulative_sizes = np.cumsum(sizes) + + def __len__(self): + return self.cumulative_sizes[-1] + + def __getitem__(self, idx): + # Returns a pair (dataset_idx, sample_idx) + if idx < 0 or idx >= len(self): + raise ValueError(f"index must be between 0 and the total size ({len(self)})") + dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) + if dataset_idx == 0: + return dataset_idx, idx + return dataset_idx, idx - self.cumulative_sizes[dataset_idx - 1] + + +class CSVLogger(object): + """An append-to CSV abstraction. File I/O requires a flush.""" + + def __init__(self, fname, header): + """Write header to internal buffers.""" + self.fname = fname + self.buffer = io.StringIO() + self.writer = csv.writer(self.buffer, quoting=csv.QUOTE_NONNUMERIC) + self.writer.writerow(header) + self.initialized = False + + def writerow(self, row) -> None: + """Write row to internal buffers.""" + self.writer.writerow(row) + + def flush(self) -> None: + """Flush buffer to file.""" + # Overwrite old file + mode = "a+" if self.initialized else "w" + + with open(self.fname, mode, newline="") as f: + f.write(self.buffer.getvalue()) + + self.buffer = io.StringIO() + self.writer = csv.writer(self.buffer, quoting=csv.QUOTE_NONNUMERIC) + self.initialized = True + + +class MonitoredDataset(torch.utils.data.Dataset): + """Implement resource monitoring on a per-worker basis. + + The sampling occurs every monitor_interval seconds and writes the log + every log_interval seconds to a file specified by log_filename, which + maps a worker id to a file using the '%w' placeholder. + + Warning: Do not call this dataset before it is consumed in the DataLoader. + """ + + def __init__( + self, dataset: torch.utils.data.Dataset, log_filename: str, log_interval: float, monitor_interval: float + ): + self.dataset = dataset + self.log_filename = str(log_filename) + self.log_interval = log_interval + self.monitor_interval = monitor_interval + self._csv_log = None + self._monitoring_thread = None + self._last_log_time = None + # Patch getitems dynamically + if hasattr(self.dataset, "__getitems__") and self.dataset.__getitems__: + + def __getitems__(self, index): + self.maybe_start_resource_monitoring() + return self.dataset.__getitems__(index) + + self.__getitems__ = __getitems__ + + def __del__(self): + self.stop_resource_monitoring() + + def __getitem__(self, index): + self.maybe_start_resource_monitoring() + return self.dataset.__getitem__(index) + + def __len__(self): + return len(self.dataset) + + def _elapsed_log_time(self): + if self._last_log_time is None: + return float("inf") + else: + return time.perf_counter() - self._last_log_time + + def _update_log_time(self): + self._last_log_time = time.perf_counter() + + def maybe_start_resource_monitoring(self): + if self._monitoring_thread is None: + + def callback_fn(resource_sample): + worker_info = torch.utils.data.get_worker_info() + worker_id = worker_info.id + + if self._csv_log is None: + header = [f.name for f in resource_sample.fields()] + log_filename = self.log_filename.replace("%w", str(worker_id)) + self._csv_log = CSVLogger(log_filename, header) + row_values = resource_sample.as_tuple() + self._csv_log.writerow(row_values) + + if self._elapsed_log_time() > self.log_interval: + self._csv_log.flush() + self._update_log_time() + + self._monitoring_thread = ResourceMonitoringThread( + None, self.monitor_interval, stats_callback_fn=callback_fn + ) + self._monitoring_thread.start() + + def stop_resource_monitoring(self): + if self._monitoring_thread: + self._monitoring_thread.stop() + + +class NondeterministicDataLoader(torch.utils.data.DataLoader): + """Override torch dataloader to return out of order.""" + + def __init__(self, *args, **kwargs): + """Pass through constructor.""" + super().__init__(*args, **kwargs) + + def _get_iterator(self): + if self.num_workers: + self.check_worker_number_rationality() + return _SloppyMultiProcessingDataLoaderIter(self) + else: + return super()._get_iterator() + + +class _SloppyMultiProcessingDataLoaderIter(_MultiProcessingDataLoaderIter): + + def __init__(self, *args, **kwargs): + """Pass through constructor.""" + super().__init__(*args, **kwargs) + + def _next_data(self): + """Adds out of order returns.""" + while True: + # If the worker responsible for `self._rcvd_idx` has already ended + # and was unable to fulfill this task (due to exhausting an `IterableDataset`), + # we try to advance `self._rcvd_idx` to find the next valid index. + # + # This part needs to run in the loop because both the `self._get_data()` + # call and `_IterableDatasetStopIteration` check below can mark + # extra worker(s) as dead. + while self._rcvd_idx < self._send_idx: + info = self._task_info[self._rcvd_idx] + if info is None: + # Found a reordered tombstone + del self._task_info[self._rcvd_idx] + self._rcvd_idx += 1 + self._try_put_index() + else: + worker_id = info[0] + # has data or is still active + if len(info) == 2 or self._workers_status[worker_id]: + break + del self._task_info[self._rcvd_idx] + self._rcvd_idx += 1 + else: + # no valid `self._rcvd_idx` is found (i.e., didn't break) + if not self._persistent_workers: + self._shutdown_workers() + raise StopIteration + + # Now `self._rcvd_idx` is the batch index we want to fetch + + # Check if the next sample has already been generated + if len(self._task_info[self._rcvd_idx]) == 2: + data = self._task_info.pop(self._rcvd_idx)[1] + return self._process_data(data) + + assert not self._shutdown and self._tasks_outstanding > 0 + idx, data = self._get_data() + self._tasks_outstanding -= 1 + if self._dataset_kind == _DatasetKind.Iterable: + # Check for _IterableDatasetStopIteration + if isinstance(data, _utils.worker._IterableDatasetStopIteration): + if self._persistent_workers: + self._workers_status[data.worker_id] = False + else: + self._mark_worker_as_unavailable(data.worker_id) + self._try_put_index() + continue + + if idx != self._rcvd_idx: + # Tombstone to receive later + self._task_info[idx] = None + if isinstance(data, ExceptionWrapper): + data.reraise() + return data + else: + del self._task_info[idx] + return self._process_data(data) + + +def get_worker_info(): + worker_info = torch.utils.data.get_worker_info() + if worker_info is None: + num_workers = 1 + worker_id = 0 + else: + num_workers = worker_info.num_workers + worker_id = worker_info.id + return num_workers, worker_id diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/utils.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f967c2b087eb3fed0c2b1ef621b0203e668edbbb --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/utils.py @@ -0,0 +1,21 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from src.utils.cluster import dataset_paths +from src.utils.logging import get_logger + +logger = get_logger("Datasets utils") + + +def get_dataset_paths(datasets: list[str]): + paths = [] + for d in datasets: + try: + path = dataset_paths().get(d) + except Exception: + raise Exception(f"Unknown dataset: {d}") + paths.append(path) + logger.info(f"Datapaths {paths}") + return paths diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/functional.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..9c7358760dfc2dc8a5e3f1b233b0cf6583348329 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/functional.py @@ -0,0 +1,110 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import numbers + +import cv2 +import numpy as np +import PIL +import torch +from torchvision.transforms import functional as tvf + + +def _is_tensor_clip(clip): + return torch.is_tensor(clip) and clip.ndimension() == 4 + + +def crop_clip(clip, min_h, min_w, h, w): + if isinstance(clip[0], np.ndarray) or isinstance(clip[0], torch.Tensor): + if clip[0].shape[-1] == 3: + cropped = [img[min_h : min_h + h, min_w : min_w + w, :] for img in clip] + else: + assert clip[0].shape[0] == 3 + cropped = [img[:, min_h : min_h + h, min_w : min_w + w] for img in clip] + + elif isinstance(clip[0], PIL.Image.Image): + cropped = [img.crop((min_w, min_h, min_w + w, min_h + h)) for img in clip] + + else: + raise TypeError( + "Expected numpy.ndarray or PIL.Image or torch.Tensor):" + "but got list of {0}".format(type(clip[0])) + ) + return cropped + + +def resize_clip(clip, size, interpolation="bilinear"): + if isinstance(clip[0], np.ndarray) or isinstance(clip[0], torch.Tensor): + if isinstance(size, numbers.Number): + if clip[0].shape[-1] == 3: + im_h, im_w, im_c = clip[0].shape + else: + assert clip[0].shape[0] == 3 + im_c, im_h, im_w = clip[0].shape + # Min spatial dim already matches minimal size + if (im_w <= im_h and im_w == size) or (im_h <= im_w and im_h == size): + return clip + new_h, new_w = get_resize_sizes(im_h, im_w, size) + size = (new_w, new_h) + else: + size = size[0], size[1] + + if isinstance(clip[0], np.ndarray): + if interpolation == "bilinear": + np_inter = cv2.INTER_LINEAR + else: + np_inter = cv2.INTER_NEAREST + scaled = [cv2.resize(img, size, interpolation=np_inter) for img in clip] + else: # isinstance(clip[0], torch.Tensor) + if interpolation == "bilinear": + np_inter = tvf.InterpolationMode.BILINEAR + else: + np_inter = tvf.InterpolationMode.NEAREST + size = (size[1], size[0]) # torchvision transformers expect the size in (h, w) order. + scaled = [tvf.resize(img, size, interpolation=np_inter) for img in clip] + elif isinstance(clip[0], PIL.Image.Image): + if isinstance(size, numbers.Number): + im_w, im_h = clip[0].size + # Min spatial dim already matches minimal size + if (im_w <= im_h and im_w == size) or (im_h <= im_w and im_h == size): + return clip + new_h, new_w = get_resize_sizes(im_h, im_w, size) + size = (new_w, new_h) + else: + size = size[1], size[0] + if interpolation == "bilinear": + pil_inter = PIL.Image.BILINEAR + else: + pil_inter = PIL.Image.NEAREST + scaled = [img.resize(size, pil_inter) for img in clip] + else: + raise TypeError( + "Expected numpy.ndarray or PIL.Image or torch.Tensor" + "but got list of {0}".format(type(clip[0])) + ) + return scaled + + +def get_resize_sizes(im_h, im_w, size): + if im_w < im_h: + ow = size + oh = int(size * im_h / im_w) + else: + oh = size + ow = int(size * im_w / im_h) + return oh, ow + + +def normalize(clip, mean, std, inplace=False): + if not _is_tensor_clip(clip): + raise TypeError("tensor is not a torch clip.") + + if not inplace: + clip = clip.clone() + + dtype = clip.dtype + mean = torch.as_tensor(mean, dtype=dtype, device=clip.device) + std = torch.as_tensor(std, dtype=dtype, device=clip.device) + clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None]) + + return clip diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/randaugment.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/randaugment.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb536372c2ebe0d62425636228eccfbdbc86184 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/randaugment.py @@ -0,0 +1,536 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. + +# Copyright 2020 Ross Wightman + +# 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. + +# This implementation is based on +# https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/auto_augment.py +# published under an Apache License 2.0. + +# COMMENT FROM ORIGINAL: +# AutoAugment, RandAugment, and AugMix for PyTorch +# This code implements the searched ImageNet policies with various tweaks and +# improvements and does not include any of the search code. AA and RA +# Implementation adapted from: +# https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py +# AugMix adapted from: +# https://github.com/google-research/augmix +# Papers: +# AutoAugment: Learning Augmentation Policies from Data +# https://arxiv.org/abs/1805.09501 +# Learning Data Augmentation Strategies for Object Detection +# https://arxiv.org/abs/1906.11172 +# RandAugment: Practical automated data augmentation... +# https://arxiv.org/abs/1909.13719 +# AugMix: A Simple Data Processing Method to Improve Robustness and +# Uncertainty https://arxiv.org/abs/1912.02781 + +import math +import random +import re + +import numpy as np +import PIL +from PIL import Image, ImageEnhance, ImageOps + +_PIL_VER = tuple([int(x) for x in PIL.__version__.split(".")[:2]]) + +_FILL = (128, 128, 128) + +# This signifies the max integer that the controller RNN could predict for the +# augmentation scheme. +_MAX_LEVEL = 10.0 + +_HPARAMS_DEFAULT = { + "translate_const": 250, + "img_mean": _FILL, +} + +_RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC) + + +def _interpolation(kwargs): + interpolation = kwargs.pop("resample", Image.BILINEAR) + if isinstance(interpolation, (list, tuple)): + return random.choice(interpolation) + else: + return interpolation + + +def _check_args_tf(kwargs): + if "fillcolor" in kwargs and _PIL_VER < (5, 0): + kwargs.pop("fillcolor") + kwargs["resample"] = _interpolation(kwargs) + + +def shear_x(img, factor, **kwargs): + _check_args_tf(kwargs) + return img.transform(img.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), **kwargs) + + +def shear_y(img, factor, **kwargs): + _check_args_tf(kwargs) + return img.transform(img.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), **kwargs) + + +def translate_x_rel(img, pct, **kwargs): + pixels = pct * img.size[0] + _check_args_tf(kwargs) + return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs) + + +def translate_y_rel(img, pct, **kwargs): + pixels = pct * img.size[1] + _check_args_tf(kwargs) + return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs) + + +def translate_x_abs(img, pixels, **kwargs): + _check_args_tf(kwargs) + return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs) + + +def translate_y_abs(img, pixels, **kwargs): + _check_args_tf(kwargs) + return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs) + + +def rotate(img, degrees, **kwargs): + _check_args_tf(kwargs) + if _PIL_VER >= (5, 2): + return img.rotate(degrees, **kwargs) + elif _PIL_VER >= (5, 0): + w, h = img.size + post_trans = (0, 0) + rotn_center = (w / 2.0, h / 2.0) + angle = -math.radians(degrees) + matrix = [ + round(math.cos(angle), 15), + round(math.sin(angle), 15), + 0.0, + round(-math.sin(angle), 15), + round(math.cos(angle), 15), + 0.0, + ] + + def transform(x, y, matrix): + (a, b, c, d, e, f) = matrix + return a * x + b * y + c, d * x + e * y + f + + matrix[2], matrix[5] = transform( + -rotn_center[0] - post_trans[0], + -rotn_center[1] - post_trans[1], + matrix, + ) + matrix[2] += rotn_center[0] + matrix[5] += rotn_center[1] + return img.transform(img.size, Image.AFFINE, matrix, **kwargs) + else: + return img.rotate(degrees, resample=kwargs["resample"]) + + +def auto_contrast(img, **__): + return ImageOps.autocontrast(img) + + +def invert(img, **__): + return ImageOps.invert(img) + + +def equalize(img, **__): + return ImageOps.equalize(img) + + +def solarize(img, thresh, **__): + return ImageOps.solarize(img, thresh) + + +def solarize_add(img, add, thresh=128, **__): + lut = [] + for i in range(256): + if i < thresh: + lut.append(min(255, i + add)) + else: + lut.append(i) + if img.mode in ("L", "RGB"): + if img.mode == "RGB" and len(lut) == 256: + lut = lut + lut + lut + return img.point(lut) + else: + return img + + +def posterize(img, bits_to_keep, **__): + if bits_to_keep >= 8: + return img + return ImageOps.posterize(img, bits_to_keep) + + +def contrast(img, factor, **__): + return ImageEnhance.Contrast(img).enhance(factor) + + +def color(img, factor, **__): + return ImageEnhance.Color(img).enhance(factor) + + +def brightness(img, factor, **__): + return ImageEnhance.Brightness(img).enhance(factor) + + +def sharpness(img, factor, **__): + return ImageEnhance.Sharpness(img).enhance(factor) + + +def _randomly_negate(v): + """With 50% prob, negate the value""" + return -v if random.random() > 0.5 else v + + +def _rotate_level_to_arg(level, _hparams): + # range [-30, 30] + level = (level / _MAX_LEVEL) * 30.0 + level = _randomly_negate(level) + return (level,) + + +def _enhance_level_to_arg(level, _hparams): + # range [0.1, 1.9] + return ((level / _MAX_LEVEL) * 1.8 + 0.1,) + + +def _enhance_increasing_level_to_arg(level, _hparams): + # the 'no change' level is 1.0, moving away from that towards 0. or 2.0 increases the enhancement blend + # range [0.1, 1.9] + level = (level / _MAX_LEVEL) * 0.9 + level = 1.0 + _randomly_negate(level) + return (level,) + + +def _shear_level_to_arg(level, _hparams): + # range [-0.3, 0.3] + level = (level / _MAX_LEVEL) * 0.3 + level = _randomly_negate(level) + return (level,) + + +def _translate_abs_level_to_arg(level, hparams): + translate_const = hparams["translate_const"] + level = (level / _MAX_LEVEL) * float(translate_const) + level = _randomly_negate(level) + return (level,) + + +def _translate_rel_level_to_arg(level, hparams): + # default range [-0.45, 0.45] + translate_pct = hparams.get("translate_pct", 0.45) + level = (level / _MAX_LEVEL) * translate_pct + level = _randomly_negate(level) + return (level,) + + +def _posterize_level_to_arg(level, _hparams): + # As per Tensorflow TPU EfficientNet impl + # range [0, 4], 'keep 0 up to 4 MSB of original image' + # intensity/severity of augmentation decreases with level + return (int((level / _MAX_LEVEL) * 4),) + + +def _posterize_increasing_level_to_arg(level, hparams): + # As per Tensorflow models research and UDA impl + # range [4, 0], 'keep 4 down to 0 MSB of original image', + # intensity/severity of augmentation increases with level + return (4 - _posterize_level_to_arg(level, hparams)[0],) + + +def _posterize_original_level_to_arg(level, _hparams): + # As per original AutoAugment paper description + # range [4, 8], 'keep 4 up to 8 MSB of image' + # intensity/severity of augmentation decreases with level + return (int((level / _MAX_LEVEL) * 4) + 4,) + + +def _solarize_level_to_arg(level, _hparams): + # range [0, 256] + # intensity/severity of augmentation decreases with level + return (int((level / _MAX_LEVEL) * 256),) + + +def _solarize_increasing_level_to_arg(level, _hparams): + # range [0, 256] + # intensity/severity of augmentation increases with level + return (256 - _solarize_level_to_arg(level, _hparams)[0],) + + +def _solarize_add_level_to_arg(level, _hparams): + # range [0, 110] + return (int((level / _MAX_LEVEL) * 110),) + + +LEVEL_TO_ARG = { + "AutoContrast": None, + "Equalize": None, + "Invert": None, + "Rotate": _rotate_level_to_arg, + # There are several variations of the posterize level scaling in various Tensorflow/Google repositories/papers + "Posterize": _posterize_level_to_arg, + "PosterizeIncreasing": _posterize_increasing_level_to_arg, + "PosterizeOriginal": _posterize_original_level_to_arg, + "Solarize": _solarize_level_to_arg, + "SolarizeIncreasing": _solarize_increasing_level_to_arg, + "SolarizeAdd": _solarize_add_level_to_arg, + "Color": _enhance_level_to_arg, + "ColorIncreasing": _enhance_increasing_level_to_arg, + "Contrast": _enhance_level_to_arg, + "ContrastIncreasing": _enhance_increasing_level_to_arg, + "Brightness": _enhance_level_to_arg, + "BrightnessIncreasing": _enhance_increasing_level_to_arg, + "Sharpness": _enhance_level_to_arg, + "SharpnessIncreasing": _enhance_increasing_level_to_arg, + "ShearX": _shear_level_to_arg, + "ShearY": _shear_level_to_arg, + "TranslateX": _translate_abs_level_to_arg, + "TranslateY": _translate_abs_level_to_arg, + "TranslateXRel": _translate_rel_level_to_arg, + "TranslateYRel": _translate_rel_level_to_arg, +} + + +NAME_TO_OP = { + "AutoContrast": auto_contrast, + "Equalize": equalize, + "Invert": invert, + "Rotate": rotate, + "Posterize": posterize, + "PosterizeIncreasing": posterize, + "PosterizeOriginal": posterize, + "Solarize": solarize, + "SolarizeIncreasing": solarize, + "SolarizeAdd": solarize_add, + "Color": color, + "ColorIncreasing": color, + "Contrast": contrast, + "ContrastIncreasing": contrast, + "Brightness": brightness, + "BrightnessIncreasing": brightness, + "Sharpness": sharpness, + "SharpnessIncreasing": sharpness, + "ShearX": shear_x, + "ShearY": shear_y, + "TranslateX": translate_x_abs, + "TranslateY": translate_y_abs, + "TranslateXRel": translate_x_rel, + "TranslateYRel": translate_y_rel, +} + + +class AugmentOp: + """ + Apply for video. + """ + + def __init__(self, name, prob=0.5, magnitude=10, hparams=None): + hparams = hparams or _HPARAMS_DEFAULT + self.aug_fn = NAME_TO_OP[name] + self.level_fn = LEVEL_TO_ARG[name] + self.prob = prob + self.magnitude = magnitude + self.hparams = hparams.copy() + self.kwargs = { + "fillcolor": hparams["img_mean"] if "img_mean" in hparams else _FILL, + "resample": hparams["interpolation"] if "interpolation" in hparams else _RANDOM_INTERPOLATION, + } + + # If magnitude_std is > 0, we introduce some randomness + # in the usually fixed policy and sample magnitude from a normal distribution + # with mean `magnitude` and std-dev of `magnitude_std`. + # NOTE This is my own hack, being tested, not in papers or reference impls. + self.magnitude_std = self.hparams.get("magnitude_std", 0) + + def __call__(self, img_list): + if self.prob < 1.0 and random.random() > self.prob: + return img_list + magnitude = self.magnitude + if self.magnitude_std and self.magnitude_std > 0: + magnitude = random.gauss(magnitude, self.magnitude_std) + magnitude = min(_MAX_LEVEL, max(0, magnitude)) # clip to valid range + level_args = self.level_fn(magnitude, self.hparams) if self.level_fn is not None else () + + if isinstance(img_list, list): + return [self.aug_fn(img, *level_args, **self.kwargs) for img in img_list] + else: + return self.aug_fn(img_list, *level_args, **self.kwargs) + + +_RAND_TRANSFORMS = [ + "AutoContrast", + "Equalize", + "Invert", + "Rotate", + "Posterize", + "Solarize", + "SolarizeAdd", + "Color", + "Contrast", + "Brightness", + "Sharpness", + "ShearX", + "ShearY", + "TranslateXRel", + "TranslateYRel", +] + + +_RAND_INCREASING_TRANSFORMS = [ + "AutoContrast", + "Equalize", + "Invert", + "Rotate", + "PosterizeIncreasing", + "SolarizeIncreasing", + "SolarizeAdd", + "ColorIncreasing", + "ContrastIncreasing", + "BrightnessIncreasing", + "SharpnessIncreasing", + "ShearX", + "ShearY", + "TranslateXRel", + "TranslateYRel", +] + + +# These experimental weights are based loosely on the relative improvements mentioned in paper. +# They may not result in increased performance, but could likely be tuned to so. +_RAND_CHOICE_WEIGHTS_0 = { + "Rotate": 0.3, + "ShearX": 0.2, + "ShearY": 0.2, + "TranslateXRel": 0.1, + "TranslateYRel": 0.1, + "Color": 0.025, + "Sharpness": 0.025, + "AutoContrast": 0.025, + "Solarize": 0.005, + "SolarizeAdd": 0.005, + "Contrast": 0.005, + "Brightness": 0.005, + "Equalize": 0.005, + "Posterize": 0, + "Invert": 0, +} + +_RAND_CHOICE_WEIGHTS_1 = { + "Rotate": 0.0, + "ShearX": 0.0, + "ShearY": 0.0, + "TranslateXRel": 0.0, + "TranslateYRel": 0.0, + "Color": 0.25, + "Sharpness": 0.25, + "AutoContrast": 0.25, + "Solarize": 0.05, + "SolarizeAdd": 0.05, + "Contrast": 0.05, + "Brightness": 0.05, + "Equalize": 0.05, + "Posterize": 0, + "Invert": 0, +} + + +def _select_rand_weights(weight_idx=0, transforms=None): + transforms = transforms or _RAND_TRANSFORMS + assert weight_idx == 0 or weight_idx == 1 # only two sets of weights currently + if weight_idx == 0: + rand_weights = _RAND_CHOICE_WEIGHTS_0 + elif weight_idx == 1: + rand_weights = _RAND_CHOICE_WEIGHTS_1 + probs = [rand_weights[k] for k in transforms] + probs /= np.sum(probs) + return probs + + +def rand_augment_ops(magnitude=10, hparams=None, transforms=None): + hparams = hparams or _HPARAMS_DEFAULT + transforms = transforms or _RAND_TRANSFORMS + return [AugmentOp(name, prob=0.5, magnitude=magnitude, hparams=hparams) for name in transforms] + + +class RandAugment: + def __init__(self, ops, num_layers=2, choice_weights=None): + self.ops = ops + self.num_layers = num_layers + self.choice_weights = choice_weights + + def __call__(self, img): + # no replacement when using weighted choice + ops = np.random.choice( + self.ops, + self.num_layers, + replace=self.choice_weights is None, + p=self.choice_weights, + ) + for op in ops: + img = op(img) + return img + + +def rand_augment_transform(config_str, hparams): + """ + RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719 + + Create a RandAugment transform + :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by + dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining + sections, not order specific determine + 'm' - integer magnitude of rand augment + 'n' - integer num layers (number of transform ops selected per image) + 'w' - integer probability weight index (index of a set of weights to influence choice of op) + 'mstd' - float std deviation of magnitude noise applied + 'inc' - integer (bool), use augmentations that increase in severity with magnitude (default: 0) + Ex 'rand-m9-n3-mstd0.5' results in RandAugment with magnitude 9, num_layers 3, magnitude_std 0.5 + 'rand-mstd1-w0' results in magnitude_std 1.0, weights 0, default magnitude of 10 and num_layers 2 + :param hparams: Other hparams (kwargs) for the RandAugmentation scheme + :return: A PyTorch compatible Transform + """ + magnitude = _MAX_LEVEL # default to _MAX_LEVEL for magnitude (currently 10) + num_layers = 2 # default to 2 ops per image + weight_idx = None # default to no probability weights for op choice + transforms = _RAND_TRANSFORMS + config = config_str.split("-") + assert config[0] == "rand" + config = config[1:] + for c in config: + cs = re.split(r"(\d.*)", c) + if len(cs) < 2: + continue + key, val = cs[:2] + if key == "mstd": + # noise param injected via hparams for now + hparams.setdefault("magnitude_std", float(val)) + elif key == "inc": + if bool(val): + transforms = _RAND_INCREASING_TRANSFORMS + elif key == "m": + magnitude = int(val) + elif key == "n": + num_layers = int(val) + elif key == "w": + weight_idx = int(val) + else: + assert NotImplementedError + ra_ops = rand_augment_ops(magnitude=magnitude, hparams=hparams, transforms=transforms) + choice_weights = None if weight_idx is None else _select_rand_weights(weight_idx) + return RandAugment(ra_ops, num_layers, choice_weights=choice_weights) diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/randerase.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/randerase.py new file mode 100644 index 0000000000000000000000000000000000000000..13226caff18b54f2f2969eb9d98b0866b5d7026e --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/randerase.py @@ -0,0 +1,170 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. + +# Copyright 2020 Ross Wightman + +# 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. + +# This implementation is based on +# https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/random_erasing.py +# published under an Apache License 2.0. + + +import math +import random + +import torch + + +def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device="cuda"): + # NOTE I've seen CUDA illegal memory access errors being caused by the normal_() + # paths, flip the order so normal is run on CPU if this becomes a problem + # Issue has been fixed in master https://github.com/pytorch/pytorch/issues/19508 + if per_pixel: + return torch.empty(patch_size, dtype=dtype, device=device).normal_() + elif rand_color: + return torch.empty((patch_size[0], 1, 1), dtype=dtype, device=device).normal_() + else: + return torch.zeros((patch_size[0], 1, 1), dtype=dtype, device=device) + + +class RandomErasing: + """Randomly selects a rectangle region in an image and erases its pixels. + 'Random Erasing Data Augmentation' by Zhong et al. + See https://arxiv.org/pdf/1708.04896.pdf + This variant of RandomErasing is intended to be applied to either a batch + or single image tensor after it has been normalized by dataset mean and std. + Args: + probability: Probability that the Random Erasing operation will be performed. + min_area: Minimum percentage of erased area wrt input image area. + max_area: Maximum percentage of erased area wrt input image area. + min_aspect: Minimum aspect ratio of erased area. + mode: pixel color mode, one of 'const', 'rand', or 'pixel' + 'const' - erase block is constant color of 0 for all channels + 'rand' - erase block is same per-channel random (normal) color + 'pixel' - erase block is per-pixel random (normal) color + max_count: maximum number of erasing blocks per image, area per box is scaled by count. + per-image count is randomly chosen between 1 and this value. + """ + + def __init__( + self, + probability=0.5, + min_area=0.02, + max_area=1 / 3, + min_aspect=0.3, + max_aspect=None, + mode="const", + min_count=1, + max_count=None, + num_splits=0, + device="cuda", + cube=True, + ): + self.probability = probability + self.min_area = min_area + self.max_area = max_area + max_aspect = max_aspect or 1 / min_aspect + self.log_aspect_ratio = (math.log(min_aspect), math.log(max_aspect)) + self.min_count = min_count + self.max_count = max_count or min_count + self.num_splits = num_splits + mode = mode.lower() + self.rand_color = False + self.per_pixel = False + self.cube = cube + if mode == "rand": + self.rand_color = True # per block random normal + elif mode == "pixel": + self.per_pixel = True # per pixel random normal + else: + assert not mode or mode == "const" + self.device = device + + def _erase(self, img, chan, img_h, img_w, dtype): + if random.random() > self.probability: + return + area = img_h * img_w + count = self.min_count if self.min_count == self.max_count else random.randint(self.min_count, self.max_count) + for _ in range(count): + for _ in range(10): + target_area = random.uniform(self.min_area, self.max_area) * area / count + aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio)) + h = int(round(math.sqrt(target_area * aspect_ratio))) + w = int(round(math.sqrt(target_area / aspect_ratio))) + if w < img_w and h < img_h: + top = random.randint(0, img_h - h) + left = random.randint(0, img_w - w) + img[:, top : top + h, left : left + w] = _get_pixels( + self.per_pixel, + self.rand_color, + (chan, h, w), + dtype=dtype, + device=self.device, + ) + break + + def _erase_cube( + self, + img, + batch_start, + batch_size, + chan, + img_h, + img_w, + dtype, + ): + if random.random() > self.probability: + return + area = img_h * img_w + count = self.min_count if self.min_count == self.max_count else random.randint(self.min_count, self.max_count) + for _ in range(count): + for _ in range(100): + target_area = random.uniform(self.min_area, self.max_area) * area / count + aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio)) + h = int(round(math.sqrt(target_area * aspect_ratio))) + w = int(round(math.sqrt(target_area / aspect_ratio))) + if w < img_w and h < img_h: + top = random.randint(0, img_h - h) + left = random.randint(0, img_w - w) + for i in range(batch_start, batch_size): + img_instance = img[i] + img_instance[:, top : top + h, left : left + w] = _get_pixels( + self.per_pixel, + self.rand_color, + (chan, h, w), + dtype=dtype, + device=self.device, + ) + break + + def __call__(self, input): + if len(input.size()) == 3: + self._erase(input, *input.size(), input.dtype) + else: + batch_size, chan, img_h, img_w = input.size() + # skip first slice of batch if num_splits is set (for clean portion of samples) + batch_start = batch_size // self.num_splits if self.num_splits > 1 else 0 + if self.cube: + self._erase_cube( + input, + batch_start, + batch_size, + chan, + img_h, + img_w, + input.dtype, + ) + else: + for i in range(batch_start, batch_size): + self._erase(input[i], chan, img_h, img_w, input.dtype) + return input diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/transforms.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..c2ce8ef7641686ae715c1fa9cfb8f4aaec2f41b1 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/transforms.py @@ -0,0 +1,1161 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +import numbers +import random + +import numpy as np +import PIL +import torch +import torchvision +import torchvision.transforms.functional as F +from PIL import Image +from torch import Tensor +from torchvision import transforms + +import src.datasets.utils.video.functional as FF +from src.datasets.utils.video.randaugment import rand_augment_transform + +_pil_interpolation_to_str = { + Image.NEAREST: "PIL.Image.NEAREST", + Image.BILINEAR: "PIL.Image.BILINEAR", + Image.BICUBIC: "PIL.Image.BICUBIC", + Image.LANCZOS: "PIL.Image.LANCZOS", + Image.HAMMING: "PIL.Image.HAMMING", + Image.BOX: "PIL.Image.BOX", +} + + +_RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC) +PAD_FRAME_METHODS = ["circulant"] + + +def _pil_interp(method): + if method == "bicubic": + return Image.BICUBIC + elif method == "lanczos": + return Image.LANCZOS + elif method == "hamming": + return Image.HAMMING + else: + return Image.BILINEAR + + +def random_short_side_scale_jitter(images, min_size, max_size, boxes=None, inverse_uniform_sampling=False): + """ + Perform a spatial short scale jittering on the given images and + corresponding boxes. + Args: + images (tensor): images to perform scale jitter. Dimension is + `num frames` x `channel` x `height` x `width`. + min_size (int): the minimal size to scale the frames. + max_size (int): the maximal size to scale the frames. + boxes (ndarray): optional. Corresponding boxes to images. + Dimension is `num boxes` x 4. + inverse_uniform_sampling (bool): if True, sample uniformly in + [1 / max_scale, 1 / min_scale] and take a reciprocal to get the + scale. If False, take a uniform sample from [min_scale, max_scale]. + Returns: + (tensor): the scaled images with dimension of + `num frames` x `channel` x `new height` x `new width`. + (ndarray or None): the scaled boxes with dimension of + `num boxes` x 4. + """ + if inverse_uniform_sampling: + size = int(round(1.0 / np.random.uniform(1.0 / max_size, 1.0 / min_size))) + else: + size = int(round(np.random.uniform(min_size, max_size))) + + height = images.shape[2] + width = images.shape[3] + if (width <= height and width == size) or (height <= width and height == size): + return images, boxes + new_width = size + new_height = size + if width < height: + new_height = int(math.floor((float(height) / width) * size)) + if boxes is not None: + boxes = boxes * float(new_height) / height + else: + new_width = int(math.floor((float(width) / height) * size)) + if boxes is not None: + boxes = boxes * float(new_width) / width + + return ( + torch.nn.functional.interpolate( + images, + size=(new_height, new_width), + mode="bilinear", + align_corners=False, + ), + boxes, + ) + + +def crop_boxes(boxes, x_offset, y_offset): + """ + Perform crop on the bounding boxes given the offsets. + Args: + boxes (ndarray or None): bounding boxes to perform crop. The dimension + is `num boxes` x 4. + x_offset (int): cropping offset in the x axis. + y_offset (int): cropping offset in the y axis. + Returns: + cropped_boxes (ndarray or None): the cropped boxes with dimension of + `num boxes` x 4. + """ + cropped_boxes = boxes.copy() + cropped_boxes[:, [0, 2]] = boxes[:, [0, 2]] - x_offset + cropped_boxes[:, [1, 3]] = boxes[:, [1, 3]] - y_offset + + return cropped_boxes + + +def random_crop(images, size, boxes=None): + """ + Perform random spatial crop on the given images and corresponding boxes. + Args: + images (tensor): images to perform random crop. The dimension is + `num frames` x `channel` x `height` x `width`. + size (int): the size of height and width to crop on the image. + boxes (ndarray or None): optional. Corresponding boxes to images. + Dimension is `num boxes` x 4. + Returns: + cropped (tensor): cropped images with dimension of + `num frames` x `channel` x `size` x `size`. + cropped_boxes (ndarray or None): the cropped boxes with dimension of + `num boxes` x 4. + """ + if images.shape[2] == size and images.shape[3] == size: + return images + height = images.shape[2] + width = images.shape[3] + y_offset = 0 + if height > size: + y_offset = int(np.random.randint(0, height - size)) + x_offset = 0 + if width > size: + x_offset = int(np.random.randint(0, width - size)) + cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size] + + cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None + + return cropped, cropped_boxes + + +def horizontal_flip(prob, images, boxes=None): + """ + Perform horizontal flip on the given images and corresponding boxes. + Args: + prob (float): probability to flip the images. + images (tensor): images to perform horizontal flip, the dimension is + `num frames` x `channel` x `height` x `width`. + boxes (ndarray or None): optional. Corresponding boxes to images. + Dimension is `num boxes` x 4. + Returns: + images (tensor): images with dimension of + `num frames` x `channel` x `height` x `width`. + flipped_boxes (ndarray or None): the flipped boxes with dimension of + `num boxes` x 4. + """ + if boxes is None: + flipped_boxes = None + else: + flipped_boxes = boxes.copy() + + if np.random.uniform() < prob: + images = images.flip((-1)) + + if len(images.shape) == 3: + width = images.shape[2] + elif len(images.shape) == 4: + width = images.shape[3] + else: + raise NotImplementedError("Dimension does not supported") + if boxes is not None: + flipped_boxes[:, [0, 2]] = width - boxes[:, [2, 0]] - 1 + + return images, flipped_boxes + + +def uniform_crop(images, size, spatial_idx, boxes=None, scale_size=None): + """ + Perform uniform spatial sampling on the images and corresponding boxes. + Args: + images (tensor): images to perform uniform crop. The dimension is + `num frames` x `channel` x `height` x `width`. + size (int): size of height and weight to crop the images. + spatial_idx (int): 0, 1, or 2 for left, center, and right crop if width + is larger than height. Or 0, 1, or 2 for top, center, and bottom + crop if height is larger than width. + boxes (ndarray or None): optional. Corresponding boxes to images. + Dimension is `num boxes` x 4. + scale_size (int): optimal. If not None, resize the images to scale_size before + performing any crop. + Returns: + cropped (tensor): images with dimension of + `num frames` x `channel` x `size` x `size`. + cropped_boxes (ndarray or None): the cropped boxes with dimension of + `num boxes` x 4. + """ + assert spatial_idx in [0, 1, 2] + ndim = len(images.shape) + if ndim == 3: + images = images.unsqueeze(0) + height = images.shape[2] + width = images.shape[3] + + if scale_size is not None: + if width <= height: + width, height = scale_size, int(height / width * scale_size) + else: + width, height = int(width / height * scale_size), scale_size + images = torch.nn.functional.interpolate( + images, + size=(height, width), + mode="bilinear", + align_corners=False, + ) + + y_offset = int(math.ceil((height - size) / 2)) + x_offset = int(math.ceil((width - size) / 2)) + + if height > width: + if spatial_idx == 0: + y_offset = 0 + elif spatial_idx == 2: + y_offset = height - size + else: + if spatial_idx == 0: + x_offset = 0 + elif spatial_idx == 2: + x_offset = width - size + cropped = images[:, :, y_offset : y_offset + size, x_offset : x_offset + size] + cropped_boxes = crop_boxes(boxes, x_offset, y_offset) if boxes is not None else None + if ndim == 3: + cropped = cropped.squeeze(0) + return cropped, cropped_boxes + + +def clip_boxes_to_image(boxes, height, width): + """ + Clip an array of boxes to an image with the given height and width. + Args: + boxes (ndarray): bounding boxes to perform clipping. + Dimension is `num boxes` x 4. + height (int): given image height. + width (int): given image width. + Returns: + clipped_boxes (ndarray): the clipped boxes with dimension of + `num boxes` x 4. + """ + clipped_boxes = boxes.copy() + clipped_boxes[:, [0, 2]] = np.minimum(width - 1.0, np.maximum(0.0, boxes[:, [0, 2]])) + clipped_boxes[:, [1, 3]] = np.minimum(height - 1.0, np.maximum(0.0, boxes[:, [1, 3]])) + return clipped_boxes + + +def blend(images1, images2, alpha): + """ + Blend two images with a given weight alpha. + Args: + images1 (tensor): the first images to be blended, the dimension is + `num frames` x `channel` x `height` x `width`. + images2 (tensor): the second images to be blended, the dimension is + `num frames` x `channel` x `height` x `width`. + alpha (float): the blending weight. + Returns: + (tensor): blended images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + return images1 * alpha + images2 * (1 - alpha) + + +def grayscale(images): + """ + Get the grayscale for the input images. The channels of images should be + in order BGR. + Args: + images (tensor): the input images for getting grayscale. Dimension is + `num frames` x `channel` x `height` x `width`. + Returns: + img_gray (tensor): blended images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + # R -> 0.299, G -> 0.587, B -> 0.114. + img_gray = torch.tensor(images) + gray_channel = 0.299 * images[:, 2] + 0.587 * images[:, 1] + 0.114 * images[:, 0] + img_gray[:, 0] = gray_channel + img_gray[:, 1] = gray_channel + img_gray[:, 2] = gray_channel + return img_gray + + +def color_jitter(images, img_brightness=0, img_contrast=0, img_saturation=0): + """ + Perform a color jittering on the input images. The channels of images + should be in order BGR. + Args: + images (tensor): images to perform color jitter. Dimension is + `num frames` x `channel` x `height` x `width`. + img_brightness (float): jitter ratio for brightness. + img_contrast (float): jitter ratio for contrast. + img_saturation (float): jitter ratio for saturation. + Returns: + images (tensor): the jittered images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + + jitter = [] + if img_brightness != 0: + jitter.append("brightness") + if img_contrast != 0: + jitter.append("contrast") + if img_saturation != 0: + jitter.append("saturation") + + if len(jitter) > 0: + order = np.random.permutation(np.arange(len(jitter))) + for idx in range(0, len(jitter)): + if jitter[order[idx]] == "brightness": + images = brightness_jitter(img_brightness, images) + elif jitter[order[idx]] == "contrast": + images = contrast_jitter(img_contrast, images) + elif jitter[order[idx]] == "saturation": + images = saturation_jitter(img_saturation, images) + return images + + +def brightness_jitter(var, images): + """ + Perform brightness jittering on the input images. The channels of images + should be in order BGR. + Args: + var (float): jitter ratio for brightness. + images (tensor): images to perform color jitter. Dimension is + `num frames` x `channel` x `height` x `width`. + Returns: + images (tensor): the jittered images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + alpha = 1.0 + np.random.uniform(-var, var) + + img_bright = torch.zeros(images.shape) + images = blend(images, img_bright, alpha) + return images + + +def contrast_jitter(var, images): + """ + Perform contrast jittering on the input images. The channels of images + should be in order BGR. + Args: + var (float): jitter ratio for contrast. + images (tensor): images to perform color jitter. Dimension is + `num frames` x `channel` x `height` x `width`. + Returns: + images (tensor): the jittered images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + alpha = 1.0 + np.random.uniform(-var, var) + + img_gray = grayscale(images) + img_gray[:] = torch.mean(img_gray, dim=(1, 2, 3), keepdim=True) + images = blend(images, img_gray, alpha) + return images + + +def saturation_jitter(var, images): + """ + Perform saturation jittering on the input images. The channels of images + should be in order BGR. + Args: + var (float): jitter ratio for saturation. + images (tensor): images to perform color jitter. Dimension is + `num frames` x `channel` x `height` x `width`. + Returns: + images (tensor): the jittered images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + alpha = 1.0 + np.random.uniform(-var, var) + img_gray = grayscale(images) + images = blend(images, img_gray, alpha) + + return images + + +def lighting_jitter(images, alphastd, eigval, eigvec): + """ + Perform AlexNet-style PCA jitter on the given images. + Args: + images (tensor): images to perform lighting jitter. Dimension is + `num frames` x `channel` x `height` x `width`. + alphastd (float): jitter ratio for PCA jitter. + eigval (list): eigenvalues for PCA jitter. + eigvec (list[list]): eigenvectors for PCA jitter. + Returns: + out_images (tensor): the jittered images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + if alphastd == 0: + return images + # generate alpha1, alpha2, alpha3. + alpha = np.random.normal(0, alphastd, size=(1, 3)) + eig_vec = np.array(eigvec) + eig_val = np.reshape(eigval, (1, 3)) + rgb = np.sum( + eig_vec * np.repeat(alpha, 3, axis=0) * np.repeat(eig_val, 3, axis=0), + axis=1, + ) + out_images = torch.zeros_like(images) + if len(images.shape) == 3: + # C H W + channel_dim = 0 + elif len(images.shape) == 4: + # T C H W + channel_dim = 1 + else: + raise NotImplementedError(f"Unsupported dimension {len(images.shape)}") + + for idx in range(images.shape[channel_dim]): + # C H W + if len(images.shape) == 3: + out_images[idx] = images[idx] + rgb[2 - idx] + # T C H W + elif len(images.shape) == 4: + out_images[:, idx] = images[:, idx] + rgb[2 - idx] + else: + raise NotImplementedError(f"Unsupported dimension {len(images.shape)}") + + return out_images + + +def color_normalization(images, mean, stddev): + """ + Perform color normation on the given images. + Args: + images (tensor): images to perform color normalization. Dimension is + `num frames` x `channel` x `height` x `width`. + mean (list): mean values for normalization. + stddev (list): standard deviations for normalization. + + Returns: + out_images (tensor): the normalized images, the dimension is + `num frames` x `channel` x `height` x `width`. + """ + if len(images.shape) == 3: + assert len(mean) == images.shape[0], "channel mean not computed properly" + assert len(stddev) == images.shape[0], "channel stddev not computed properly" + elif len(images.shape) == 4: + assert len(mean) == images.shape[1], "channel mean not computed properly" + assert len(stddev) == images.shape[1], "channel stddev not computed properly" + else: + raise NotImplementedError(f"Unsupported dimension {len(images.shape)}") + + out_images = torch.zeros_like(images) + for idx in range(len(mean)): + # C H W + if len(images.shape) == 3: + out_images[idx] = (images[idx] - mean[idx]) / stddev[idx] + elif len(images.shape) == 4: + out_images[:, idx] = (images[:, idx] - mean[idx]) / stddev[idx] + else: + raise NotImplementedError(f"Unsupported dimension {len(images.shape)}") + return out_images + + +def _get_param_spatial_crop(scale, ratio, height, width, num_repeat=10, log_scale=True, switch_hw=False): + """ + Given scale, ratio, height and width, return sampled coordinates of the videos. + """ + for _ in range(num_repeat): + area = height * width + target_area = random.uniform(*scale) * area + if log_scale: + log_ratio = (math.log(ratio[0]), math.log(ratio[1])) + aspect_ratio = math.exp(random.uniform(*log_ratio)) + else: + aspect_ratio = random.uniform(*ratio) + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + if np.random.uniform() < 0.5 and switch_hw: + w, h = h, w + + if 0 < w <= width and 0 < h <= height: + i = random.randint(0, height - h) + j = random.randint(0, width - w) + return i, j, h, w + + # Fallback to central crop + in_ratio = float(width) / float(height) + if in_ratio < min(ratio): + w = width + h = int(round(w / min(ratio))) + elif in_ratio > max(ratio): + h = height + w = int(round(h * max(ratio))) + else: # whole image + w = width + h = height + i = (height - h) // 2 + j = (width - w) // 2 + return i, j, h, w + + +def random_resized_crop( + images, + target_height, + target_width, + scale=(0.8, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), +): + """ + Crop the given images to random size and aspect ratio. A crop of random + size (default: of 0.08 to 1.0) of the original size and a random aspect + ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This + crop is finally resized to given size. This is popularly used to train the + Inception networks. + + Args: + images: Images to perform resizing and cropping. + target_height: Desired height after cropping. + target_width: Desired width after cropping. + scale: Scale range of Inception-style area based random resizing. + ratio: Aspect ratio range of Inception-style area based random resizing. + """ + + height = images.shape[2] + width = images.shape[3] + + i, j, h, w = _get_param_spatial_crop(scale, ratio, height, width) + cropped = images[:, :, i : i + h, j : j + w] + return torch.nn.functional.interpolate( + cropped, + size=(target_height, target_width), + mode="bilinear", + align_corners=False, + ) + + +def random_resized_crop_with_shift( + images, + target_height, + target_width, + scale=(0.8, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), +): + """ + This is similar to random_resized_crop. However, it samples two different + boxes (for cropping) for the first and last frame. It then linearly + interpolates the two boxes for other frames. + + Args: + images: Images to perform resizing and cropping. + target_height: Desired height after cropping. + target_width: Desired width after cropping. + scale: Scale range of Inception-style area based random resizing. + ratio: Aspect ratio range of Inception-style area based random resizing. + """ + t = images.shape[1] + height = images.shape[2] + width = images.shape[3] + + i, j, h, w = _get_param_spatial_crop(scale, ratio, height, width) + i_, j_, h_, w_ = _get_param_spatial_crop(scale, ratio, height, width) + i_s = [int(i) for i in torch.linspace(i, i_, steps=t).tolist()] + j_s = [int(i) for i in torch.linspace(j, j_, steps=t).tolist()] + h_s = [int(i) for i in torch.linspace(h, h_, steps=t).tolist()] + w_s = [int(i) for i in torch.linspace(w, w_, steps=t).tolist()] + out = torch.zeros((3, t, target_height, target_width)) + for ind in range(t): + out[:, ind : ind + 1, :, :] = torch.nn.functional.interpolate( + images[ + :, + ind : ind + 1, + i_s[ind] : i_s[ind] + h_s[ind], + j_s[ind] : j_s[ind] + w_s[ind], + ], + size=(target_height, target_width), + mode="bilinear", + align_corners=False, + ) + return out + + +def create_random_augment( + input_size, + auto_augment=None, + interpolation="bilinear", +): + """ + Get video randaug transform. + + Args: + input_size: The size of the input video in tuple. + auto_augment: Parameters for randaug. An example: + "rand-m7-n4-mstd0.5-inc1" (m is the magnitude and n is the number + of operations to apply). + interpolation: Interpolation method. + """ + if isinstance(input_size, tuple): + img_size = input_size[-2:] + else: + img_size = input_size + + if auto_augment: + assert isinstance(auto_augment, str) + if isinstance(img_size, tuple): + img_size_min = min(img_size) + else: + img_size_min = img_size + aa_params = {"translate_const": int(img_size_min * 0.45)} + if interpolation and interpolation != "random": + aa_params["interpolation"] = _pil_interp(interpolation) + if auto_augment.startswith("rand"): + return transforms.Compose([rand_augment_transform(auto_augment, aa_params)]) + raise NotImplementedError + + +def random_sized_crop_img( + im, + size, + jitter_scale=(0.08, 1.0), + jitter_aspect=(3.0 / 4.0, 4.0 / 3.0), + max_iter=10, +): + """ + Performs Inception-style cropping (used for training). + """ + assert len(im.shape) == 3, "Currently only support image for random_sized_crop" + h, w = im.shape[1:3] + i, j, h, w = _get_param_spatial_crop( + scale=jitter_scale, + ratio=jitter_aspect, + height=h, + width=w, + num_repeat=max_iter, + log_scale=False, + switch_hw=True, + ) + cropped = im[:, i : i + h, j : j + w] + return torch.nn.functional.interpolate( + cropped.unsqueeze(0), + size=(size, size), + mode="bilinear", + align_corners=False, + ).squeeze(0) + + +def circulant_frame_padding(video: Tensor, total_frames: int) -> Tensor: + """ + Applies circulant frame padding (repeating the video) to a specified size. + + Args: + video: The input video to be padded. Expected (C, T, H, W) + total_frames: The number of frames after padding. + + Returns + The video padded to total_frames. + """ + start_frames = video.shape[1] + if start_frames == total_frames: + return video + + num_repeats = total_frames // start_frames + (total_frames % start_frames > 0) + + return video.repeat((1, num_repeats) + (1,) * (video.ndim - 2))[:, :total_frames] + + +def frame_pad(video: Tensor, total_frames: int, pad_frame_method: str) -> Tensor: + if pad_frame_method not in PAD_FRAME_METHODS: + raise ValueError(f"Unrecognized pad_frame_method {pad_frame_method}") + + if pad_frame_method == "circulant": + return circulant_frame_padding(video, total_frames) + + return None + + +# The following code are modified based on timm lib, we will replace the following +# contents with dependency from PyTorchVideo. +# https://github.com/facebookresearch/pytorchvideo +class RandomResizedCropAndInterpolation: + """Crop the given PIL Image to random size and aspect ratio with random interpolation. + A crop of random size (default: of 0.08 to 1.0) of the original size and a random + aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop + is finally resized to given size. + This is popularly used to train the Inception networks. + Args: + size: expected output size of each edge + scale: range of size of the origin size cropped + ratio: range of aspect ratio of the origin aspect ratio cropped + interpolation: Default: PIL.Image.BILINEAR + """ + + def __init__( + self, + size, + scale=(0.08, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), + interpolation="bilinear", + ): + if isinstance(size, tuple): + self.size = size + else: + self.size = (size, size) + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + print("range should be of kind (min, max)") + + if interpolation == "random": + self.interpolation = _RANDOM_INTERPOLATION + else: + self.interpolation = _pil_interp(interpolation) + self.scale = scale + self.ratio = ratio + + @staticmethod + def get_params(img, scale, ratio): + """Get parameters for ``crop`` for a random sized crop. + Args: + img (PIL Image): Image to be cropped. + scale (tuple): range of size of the origin size cropped + ratio (tuple): range of aspect ratio of the origin aspect ratio cropped + Returns: + tuple: params (i, j, h, w) to be passed to ``crop`` for a random + sized crop. + """ + area = img.size[0] * img.size[1] + + for _ in range(10): + target_area = random.uniform(*scale) * area + log_ratio = (math.log(ratio[0]), math.log(ratio[1])) + aspect_ratio = math.exp(random.uniform(*log_ratio)) + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + if w <= img.size[0] and h <= img.size[1]: + i = random.randint(0, img.size[1] - h) + j = random.randint(0, img.size[0] - w) + return i, j, h, w + + # Fallback to central crop + in_ratio = img.size[0] / img.size[1] + if in_ratio < min(ratio): + w = img.size[0] + h = int(round(w / min(ratio))) + elif in_ratio > max(ratio): + h = img.size[1] + w = int(round(h * max(ratio))) + else: # whole image + w = img.size[0] + h = img.size[1] + i = (img.size[1] - h) // 2 + j = (img.size[0] - w) // 2 + return i, j, h, w + + def __call__(self, img): + """ + Args: + img (PIL Image): Image to be cropped and resized. + Returns: + PIL Image: Randomly cropped and resized image. + """ + i, j, h, w = self.get_params(img, self.scale, self.ratio) + if isinstance(self.interpolation, (tuple, list)): + interpolation = random.choice(self.interpolation) + else: + interpolation = self.interpolation + return F.resized_crop(img, i, j, h, w, self.size, interpolation) + + def __repr__(self): + if isinstance(self.interpolation, (tuple, list)): + interpolate_str = " ".join([_pil_interpolation_to_str[x] for x in self.interpolation]) + else: + interpolate_str = _pil_interpolation_to_str[self.interpolation] + format_string = self.__class__.__name__ + "(size={0}".format(self.size) + format_string += ", scale={0}".format(tuple(round(s, 4) for s in self.scale)) + format_string += ", ratio={0}".format(tuple(round(r, 4) for r in self.ratio)) + format_string += ", interpolation={0})".format(interpolate_str) + return format_string + + +class Compose(object): + """Composes several transforms + Args: + transforms (list of ``Transform`` objects): list of transforms + to compose + """ + + def __init__(self, transforms): + self.transforms = transforms + + def __call__(self, clip): + for t in self.transforms: + clip = t(clip) + return clip + + +class RandomHorizontalFlip(object): + """Horizontally flip the list of given images randomly + with a probability 0.5 + """ + + def __call__(self, clip): + """ + Args: + img (PIL.Image or numpy.ndarray): List of images to be cropped + in format (h, w, c) in numpy.ndarray + Returns: + PIL.Image or numpy.ndarray: Randomly flipped clip + """ + if random.random() < 0.5: + if isinstance(clip[0], np.ndarray): + return [np.fliplr(img) for img in clip] + elif isinstance(clip[0], PIL.Image.Image): + return [img.transpose(PIL.Image.FLIP_LEFT_RIGHT) for img in clip] + else: + raise TypeError("Expected numpy.ndarray or PIL.Image" + " but got list of {0}".format(type(clip[0]))) + return clip + + +class RandomResize(object): + """Resizes a list of (H x W x C) numpy.ndarray to the final size + The larger the original image is, the more times it takes to + interpolate + Args: + interpolation (str): Can be one of 'nearest', 'bilinear' + defaults to nearest + size (tuple): (width, height) + """ + + def __init__(self, ratio=(3.0 / 4.0, 4.0 / 3.0), interpolation="nearest"): + self.ratio = ratio + self.interpolation = interpolation + + def __call__(self, clip): + scaling_factor = random.uniform(self.ratio[0], self.ratio[1]) + + if isinstance(clip[0], np.ndarray): + im_h, im_w, im_c = clip[0].shape + elif isinstance(clip[0], PIL.Image.Image): + im_w, im_h = clip[0].size + + new_w = int(im_w * scaling_factor) + new_h = int(im_h * scaling_factor) + new_size = (new_w, new_h) + resized = FF.resize_clip(clip, new_size, interpolation=self.interpolation) + return resized + + +class Resize(object): + """Resizes a list of (H x W x C) numpy.ndarray to the final size + The larger the original image is, the more times it takes to + interpolate + Args: + interpolation (str): Can be one of 'nearest', 'bilinear' + defaults to nearest + size (tuple): (width, height) + """ + + def __init__(self, size, interpolation="nearest"): + self.size = size + self.interpolation = interpolation + + def __call__(self, clip): + resized = FF.resize_clip(clip, self.size, interpolation=self.interpolation) + return resized + + +class RandomCrop(object): + """Extract random crop at the same location for a list of images + Args: + size (sequence or int): Desired output size for the + crop in format (h, w) + """ + + def __init__(self, size): + if isinstance(size, numbers.Number): + size = (size, size) + + self.size = size + + def __call__(self, clip): + """ + Args: + img (PIL.Image or numpy.ndarray): List of images to be cropped + in format (h, w, c) in numpy.ndarray + Returns: + PIL.Image or numpy.ndarray: Cropped list of images + """ + h, w = self.size + if isinstance(clip[0], np.ndarray): + im_h, im_w, im_c = clip[0].shape + elif isinstance(clip[0], PIL.Image.Image): + im_w, im_h = clip[0].size + else: + raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0]))) + if w > im_w or h > im_h: + error_msg = ( + "Initial image size should be larger then " + "cropped size but got cropped sizes : ({w}, {h}) while " + "initial image is ({im_w}, {im_h})".format(im_w=im_w, im_h=im_h, w=w, h=h) + ) + raise ValueError(error_msg) + + x1 = random.randint(0, im_w - w) + y1 = random.randint(0, im_h - h) + cropped = FF.crop_clip(clip, y1, x1, h, w) + + return cropped + + +class ThreeCrop(object): + """Extract random crop at the same location for a list of images + Args: + size (sequence or int): Desired output size for the + crop in format (h, w) + """ + + def __init__(self, size): + if isinstance(size, numbers.Number): + size = (size, size) + + self.size = size + + def __call__(self, clip): + """ + Args: + img (PIL.Image or numpy.ndarray): List of images to be cropped + in format (h, w, c) in numpy.ndarray + Returns: + PIL.Image or numpy.ndarray: Cropped list of images + """ + h, w = self.size + if isinstance(clip[0], np.ndarray): + im_h, im_w, im_c = clip[0].shape + elif isinstance(clip[0], PIL.Image.Image): + im_w, im_h = clip[0].size + else: + raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0]))) + if w != im_w and h != im_h: + clip = FF.resize_clip(clip, self.size, interpolation="bilinear") + im_h, im_w, im_c = clip[0].shape + + step = np.max((np.max((im_w, im_h)) - self.size[0]) // 2, 0) + cropped = [] + for i in range(3): + if im_h > self.size[0]: + x1 = 0 + y1 = i * step + cropped.extend(FF.crop_clip(clip, y1, x1, h, w)) + else: + x1 = i * step + y1 = 0 + cropped.extend(FF.crop_clip(clip, y1, x1, h, w)) + return cropped + + +class RandomRotation(object): + """Rotate entire clip randomly by a random angle within + given bounds + Args: + degrees (sequence or int): Range of degrees to select from + If degrees is a number instead of sequence like (min, max), + the range of degrees, will be (-degrees, +degrees). + """ + + def __init__(self, degrees): + if isinstance(degrees, numbers.Number): + if degrees < 0: + raise ValueError("If degrees is a single number," "must be positive") + degrees = (-degrees, degrees) + else: + if len(degrees) != 2: + raise ValueError("If degrees is a sequence," "it must be of len 2.") + + self.degrees = degrees + + def __call__(self, clip): + """ + Args: + img (PIL.Image or numpy.ndarray): List of images to be cropped + in format (h, w, c) in numpy.ndarray + Returns: + PIL.Image or numpy.ndarray: Cropped list of images + """ + import skimage + + angle = random.uniform(self.degrees[0], self.degrees[1]) + if isinstance(clip[0], np.ndarray): + rotated = [skimage.transform.rotate(img, angle) for img in clip] + elif isinstance(clip[0], PIL.Image.Image): + rotated = [img.rotate(angle) for img in clip] + else: + raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0]))) + + return rotated + + +class CenterCrop(object): + """Extract center crop at the same location for a list of images + Args: + size (sequence or int): Desired output size for the + crop in format (h, w) + """ + + def __init__(self, size): + if isinstance(size, numbers.Number): + size = (size, size) + + self.size = size + + def __call__(self, clip): + """ + Args: + img (PIL.Image or numpy.ndarray): List of images to be cropped + in format (h, w, c) in numpy.ndarray + Returns: + PIL.Image or numpy.ndarray: Cropped list of images + """ + h, w = self.size + if isinstance(clip[0], np.ndarray) or isinstance(clip[0], torch.Tensor): + if clip[0].shape[-1] == 3: + im_h, im_w, im_c = clip[0].shape + else: + assert clip[0].shape[0] == 3 + im_c, im_h, im_w = clip[0].shape + elif isinstance(clip[0], PIL.Image.Image): + im_w, im_h = clip[0].size + else: + raise TypeError( + "Expected numpy.ndarray or PIL.Image or torch.Tensor" + "but got list of {0}".format(type(clip[0])) + ) + if w > im_w or h > im_h: + error_msg = ( + "Initial image size should be larger then " + "cropped size but got cropped sizes : ({w}, {h}) while " + "initial image is ({im_w}, {im_h})".format(im_w=im_w, im_h=im_h, w=w, h=h) + ) + raise ValueError(error_msg) + + x1 = int(round((im_w - w) / 2.0)) + y1 = int(round((im_h - h) / 2.0)) + cropped = FF.crop_clip(clip, y1, x1, h, w) + + return cropped + + +class ColorJitter(object): + """ + Randomly change the brightness, contrast and saturation and hue of the clip + + Args: + brightness (float): How much to jitter brightness. brightness_factor + is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. + contrast (float): How much to jitter contrast. contrast_factor + is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. + saturation (float): How much to jitter saturation. saturation_factor + is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. + hue(float): How much to jitter hue. hue_factor is chosen uniformly from + [-hue, hue]. Should be >=0 and <= 0.5. + """ + + def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): + self.brightness = brightness + self.contrast = contrast + self.saturation = saturation + self.hue = hue + + def get_params(self, brightness, contrast, saturation, hue): + if brightness > 0: + brightness_factor = random.uniform(max(0, 1 - brightness), 1 + brightness) + else: + brightness_factor = None + + if contrast > 0: + contrast_factor = random.uniform(max(0, 1 - contrast), 1 + contrast) + else: + contrast_factor = None + + if saturation > 0: + saturation_factor = random.uniform(max(0, 1 - saturation), 1 + saturation) + else: + saturation_factor = None + + if hue > 0: + hue_factor = random.uniform(-hue, hue) + else: + hue_factor = None + return brightness_factor, contrast_factor, saturation_factor, hue_factor + + def __call__(self, clip): + """ + Args: + clip (list): list of PIL.Image + Returns: + list PIL.Image : list of transformed PIL.Image + """ + if isinstance(clip[0], np.ndarray): + raise TypeError("Color jitter not yet implemented for numpy arrays") + elif isinstance(clip[0], PIL.Image.Image): + brightness, contrast, saturation, hue = self.get_params( + self.brightness, self.contrast, self.saturation, self.hue + ) + + # Create img transform function sequence + img_transforms = [] + if brightness is not None: + img_transforms.append(lambda img: torchvision.transforms.functional.adjust_brightness(img, brightness)) + if saturation is not None: + img_transforms.append(lambda img: torchvision.transforms.functional.adjust_saturation(img, saturation)) + if hue is not None: + img_transforms.append(lambda img: torchvision.transforms.functional.adjust_hue(img, hue)) + if contrast is not None: + img_transforms.append(lambda img: torchvision.transforms.functional.adjust_contrast(img, contrast)) + random.shuffle(img_transforms) + + # Apply to all images + jittered_clip = [] + for img in clip: + for func in img_transforms: + jittered_img = func(img) + jittered_clip.append(jittered_img) + + else: + raise TypeError("Expected numpy.ndarray or PIL.Image" + "but got list of {0}".format(type(clip[0]))) + return jittered_clip + + +class Normalize(object): + """Normalize a clip with mean and standard deviation. + Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform + will normalize each channel of the input ``torch.*Tensor`` i.e. + ``input[channel] = (input[channel] - mean[channel]) / std[channel]`` + .. note:: + This transform acts out of place, i.e., it does not mutate the input tensor. + Args: + mean (sequence): Sequence of means for each channel. + std (sequence): Sequence of standard deviations for each channel. + """ + + def __init__(self, mean, std): + self.mean = mean + self.std = std + + def __call__(self, clip): + """ + Args: + clip (Tensor): Tensor clip of size (T, C, H, W) to be normalized. + Returns: + Tensor: Normalized Tensor clip. + """ + return FF.normalize(clip, self.mean, self.std) + + def __repr__(self): + return self.__class__.__name__ + "(mean={0}, std={1})".format(self.mean, self.std) diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/transforms_builder.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/transforms_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..be745d27c277edced6e84add4037115ad2071979 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/transforms_builder.py @@ -0,0 +1,165 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +import torchvision.transforms as transforms + +import src.datasets.utils.video.transforms as video_transforms +from src.datasets.utils.video.randerase import RandomErasing + + +def make_transforms( + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + pad_frame_count: Optional[int] = None, + pad_frame_method: str = "circulant", +): + _frames_augmentation = VideoTransform( + random_horizontal_flip=random_horizontal_flip, + random_resize_aspect_ratio=random_resize_aspect_ratio, + random_resize_scale=random_resize_scale, + reprob=reprob, + auto_augment=auto_augment, + motion_shift=motion_shift, + crop_size=crop_size, + normalize=normalize, + pad_frame_count=pad_frame_count, + pad_frame_method=pad_frame_method, + ) + return _frames_augmentation + + +class VideoTransform(object): + + def __init__( + self, + random_horizontal_flip=True, + random_resize_aspect_ratio=(3 / 4, 4 / 3), + random_resize_scale=(0.3, 1.0), + reprob=0.0, + auto_augment=False, + motion_shift=False, + crop_size=224, + normalize=((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + pad_frame_count: Optional[int] = None, + pad_frame_method: str = "circulant", + ): + self.random_horizontal_flip = random_horizontal_flip + self.random_resize_aspect_ratio = random_resize_aspect_ratio + self.random_resize_scale = random_resize_scale + self.auto_augment = auto_augment + self.motion_shift = motion_shift + self.crop_size = crop_size + self.mean = torch.tensor(normalize[0], dtype=torch.float32) + self.std = torch.tensor(normalize[1], dtype=torch.float32) + self.pad_frame_count = pad_frame_count + self.pad_frame_method = pad_frame_method + + if not self.auto_augment: + # Without auto-augment, PIL and tensor conversions simply scale uint8 space by 255. + self.mean *= 255.0 + self.std *= 255.0 + + self.autoaug_transform = video_transforms.create_random_augment( + input_size=(crop_size, crop_size), + auto_augment="rand-m7-n4-mstd0.5-inc1", + interpolation="bicubic", + ) + + self.spatial_transform = ( + video_transforms.random_resized_crop_with_shift if motion_shift else video_transforms.random_resized_crop + ) + + self.reprob = reprob + self.erase_transform = RandomErasing( + reprob, + mode="pixel", + max_count=1, + num_splits=1, + device="cpu", + ) + + def __call__(self, buffer): + + if self.auto_augment: + buffer = [transforms.ToPILImage()(frame) for frame in buffer] + buffer = self.autoaug_transform(buffer) + buffer = [transforms.ToTensor()(img) for img in buffer] + buffer = torch.stack(buffer) # T C H W + buffer = buffer.permute(0, 2, 3, 1) # T H W C + elif torch.is_tensor(buffer): + # TODO: ensure input is always a tensor? + buffer = buffer.to(torch.float32) + else: + buffer = torch.tensor(buffer, dtype=torch.float32) + + buffer = buffer.permute(3, 0, 1, 2) # T H W C -> C T H W + + buffer = self.spatial_transform( + images=buffer, + target_height=self.crop_size, + target_width=self.crop_size, + scale=self.random_resize_scale, + ratio=self.random_resize_aspect_ratio, + ) + if self.random_horizontal_flip: + buffer, _ = video_transforms.horizontal_flip(0.5, buffer) + + buffer = _tensor_normalize_inplace(buffer, self.mean, self.std) + if self.reprob > 0: + buffer = buffer.permute(1, 0, 2, 3) + buffer = self.erase_transform(buffer) + buffer = buffer.permute(1, 0, 2, 3) + + if self.pad_frame_count is not None: + buffer = video_transforms.frame_pad(buffer, self.pad_frame_count, self.pad_frame_method) + + return buffer + + +def tensor_normalize(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize. + mean (tensor or list): mean value to subtract. + std (tensor or list): std to divide. + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + tensor = tensor / 255.0 + if isinstance(mean, list): + mean = torch.tensor(mean) + if isinstance(std, list): + std = torch.tensor(std) + tensor = tensor - mean + tensor = tensor / std + return tensor + + +def _tensor_normalize_inplace(tensor, mean, std): + """ + Normalize a given tensor by subtracting the mean and dividing the std. + Args: + tensor (tensor): tensor to normalize (with dimensions C, T, H, W). + mean (tensor): mean value to subtract (in 0 to 255 floats). + std (tensor): std to divide (in 0 to 255 floats). + """ + if tensor.dtype == torch.uint8: + tensor = tensor.float() + + C, T, H, W = tensor.shape + tensor = tensor.view(C, -1).permute(1, 0) # Make C the last dimension + tensor.sub_(mean).div_(std) + tensor = tensor.permute(1, 0).view(C, T, H, W) # Put C back in front + return tensor diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/volume_transforms.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/volume_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..208d34c44ab399d25bb938e69125348faed38248 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/video/volume_transforms.py @@ -0,0 +1,159 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from PIL import Image + + +def convert_img(img): + """Converts (H, W, C) numpy.ndarray to (C, W, H) format""" + if len(img.shape) == 3: + img = img.transpose(2, 0, 1) + if len(img.shape) == 2: + img = np.expand_dims(img, 0) + return img + + +class ClipToTensor(object): + """Convert a list of m (H x W x C) numpy.ndarrays in the range [0, 255] + to a torch.FloatTensor of shape (C x m x H x W) in the range [0, 1.0] + """ + + def __init__(self, channel_nb=3, div_255=True, numpy=False): + self.channel_nb = channel_nb + self.div_255 = div_255 + self.numpy = numpy + + def __call__(self, clip): + """ + Args: clip (list of numpy.ndarray): clip (list of images) + to be converted to tensor. + """ + # Retrieve shape + if isinstance(clip[0], np.ndarray): + h, w, ch = clip[0].shape + assert ch == self.channel_nb, "Got {0} instead of 3 channels".format(ch) + elif isinstance(clip[0], Image.Image): + w, h = clip[0].size + elif isinstance(clip[0], torch.Tensor): + tensor_clip = torch.stack(clip) + # Converting (T, C, H, W) -> (C, T, H, W) to match what `convert_img` followed by + # `np_clip[:, img_idx, :, :] = img` does for other data types. + tensor_clip = tensor_clip.permute(1, 0, 2, 3) + if not isinstance(tensor_clip, torch.FloatTensor): + tensor_clip = tensor_clip.float() + if self.div_255: + tensor_clip = torch.div(tensor_clip, 255) + return tensor_clip + else: + raise TypeError( + "Expected numpy.ndarray or PIL.Image or torch.Tensor\ + but got list of {0}".format( + type(clip[0]) + ) + ) + + np_clip = np.zeros([self.channel_nb, len(clip), int(h), int(w)]) + + # Convert + for img_idx, img in enumerate(clip): + if isinstance(img, np.ndarray): + pass + elif isinstance(img, Image.Image): + img = np.array(img, copy=False) + else: + raise TypeError( + "Expected numpy.ndarray or PIL.Image\ + but got list of {0}".format( + type(clip[0]) + ) + ) + img = convert_img(img) + np_clip[:, img_idx, :, :] = img + + if self.numpy: + if self.div_255: + np_clip = np_clip / 255.0 + return np_clip + + else: + tensor_clip = torch.from_numpy(np_clip) + + if not isinstance(tensor_clip, torch.FloatTensor): + tensor_clip = tensor_clip.float() + if self.div_255: + tensor_clip = torch.div(tensor_clip, 255) + return tensor_clip + + +# Note this norms data to -1/1 +class ClipToTensor_K(object): + """Convert a list of m (H x W x C) numpy.ndarrays in the range [0, 255] + to a torch.FloatTensor of shape (C x m x H x W) in the range [0, 1.0] + """ + + def __init__(self, channel_nb=3, div_255=True, numpy=False): + self.channel_nb = channel_nb + self.div_255 = div_255 + self.numpy = numpy + + def __call__(self, clip): + """ + Args: clip (list of numpy.ndarray): clip (list of images) + to be converted to tensor. + """ + # Retrieve shape + if isinstance(clip[0], np.ndarray): + h, w, ch = clip[0].shape + assert ch == self.channel_nb, "Got {0} instead of 3 channels".format(ch) + elif isinstance(clip[0], Image.Image): + w, h = clip[0].size + else: + raise TypeError( + "Expected numpy.ndarray or PIL.Image\ + but got list of {0}".format( + type(clip[0]) + ) + ) + + np_clip = np.zeros([self.channel_nb, len(clip), int(h), int(w)]) + + # Convert + for img_idx, img in enumerate(clip): + if isinstance(img, np.ndarray): + pass + elif isinstance(img, Image.Image): + img = np.array(img, copy=False) + else: + raise TypeError( + "Expected numpy.ndarray or PIL.Image\ + but got list of {0}".format( + type(clip[0]) + ) + ) + img = convert_img(img) + np_clip[:, img_idx, :, :] = img + if self.numpy: + if self.div_255: + np_clip = (np_clip - 127.5) / 127.5 + return np_clip + + else: + tensor_clip = torch.from_numpy(np_clip) + + if not isinstance(tensor_clip, torch.FloatTensor): + tensor_clip = tensor_clip.float() + if self.div_255: + tensor_clip = torch.div(torch.sub(tensor_clip, 127.5), 127.5) + return tensor_clip + + +class ToTensor(object): + """Converts numpy array to tensor""" + + def __call__(self, array): + tensor = torch.from_numpy(array) + return tensor diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/weighted_sampler.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/weighted_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..63a67b4e1f9eea0d2752f87e458c330d659c43d0 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/weighted_sampler.py @@ -0,0 +1,366 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Iterator, Optional + +import numpy as np +import torch + +from src.utils.logging import get_logger +from torch.utils.data import DistributedSampler, RandomSampler + +logger = get_logger("WeightedSampler") + + +class DistributedWeightedSampler(DistributedSampler): + """ + This class implements a weighted sampler for distributed training. + See https://pytorch.org/docs/stable/_modules/torch/utils/data/distributed.html#DistributedSampler for more details. + + It shares the same interface as `torch.utils.data.DistributedSampler`. + The effective change is replacing `DistributedSampler`'s `torch.randperm` for generating the sequence + of indices with `numpy.random.Generator.choice`, with replacement. This allows weighted sampling and + avoiding issue with `torch.randperm` when the number of samples is larger than 2^24 samples. + """ + + def __init__( + self, + dataset, + num_replicas: Optional[int] = None, + rank: Optional[int] = None, + shuffle: bool = True, + seed: int = 0, + drop_last: bool = False, + ): + logger.info( + f"Using DistributedWeightedSampler with rank {rank} / {num_replicas}" + ) + assert hasattr( + dataset, "sample_weights" + ), "Dataset must have sample_weights property for using DistributedWeightedSampler" + super().__init__( + dataset, + num_replicas=num_replicas, + rank=rank, + shuffle=shuffle, + seed=seed, + drop_last=drop_last, + ) + + @property + def sample_probabilities(self) -> np.ndarray: + sample_weights = self.dataset.sample_weights + if isinstance(sample_weights, torch.Tensor): + sample_weights = sample_weights.cpu().numpy() + elif isinstance(sample_weights, list): + sample_weights = np.array(sample_weights) + assert isinstance( + sample_weights, np.ndarray + ), f"sample_weights must be a numpy array, torch.Tensor, or python list; got {type(sample_weights)}" + return sample_weights / np.sum(sample_weights) + + def __iter__(self) -> Iterator: + n = len(self.dataset) + + # deterministically shuffle based on epoch and seed + rng = np.random.default_rng(self.seed + self.epoch) + indices = rng.choice( + range(0, n), + size=self.total_size, + p=self.sample_probabilities, + replace=True, + ).tolist() + + if not self.drop_last: + # add extra samples to make it evenly divisible + padding_size = self.total_size - len(indices) + if padding_size <= len(indices): + indices += indices[:padding_size] + else: + indices += (indices * math.ceil(padding_size / len(indices)))[ + :padding_size + ] + else: + # remove tail of data to make it evenly divisible + indices = indices[: self.total_size] + assert len(indices) == self.total_size + + # subsample + indices = indices[self.rank : self.total_size : self.num_replicas] + assert len(indices) == self.num_samples + + return iter(indices) + + +class MemoryEfficientDistributedWeightedSampler(DistributedSampler): + """ + This class implements a memory efficient version of `DistributedWeightedSampler`. + It shares the same interface as `DistributedWeightedSampler`. + The effective change is just-in-time sampling of the indices, instead of pre-computing them. + """ + + def __init__( + self, + dataset, + num_replicas: Optional[int] = None, + rank: Optional[int] = None, + shuffle: bool = True, + seed: int = 0, + ): + logger.info( + f"Using MemoryEfficientDistributedWeightedSampler with rank {rank} / {num_replicas}" + ) + assert hasattr( + dataset, "dataset_weights" + ), "Dataset must have dataset_weights property for using MemoryEfficientDistributedWeightedSampler" + super().__init__( + dataset, + num_replicas=num_replicas, + rank=rank, + shuffle=shuffle, + seed=seed, + ) + + self.dataset_weights = dataset.dataset_weights + self.dataset_sizes = [len(d) for d in dataset.datasets] + if len(self.dataset_sizes) != len(self.dataset_weights): + raise ValueError( + f"Number of datasets ({len(self.dataset_sizes)}) " + f"does not match number of dataset weights ({len(self.dataset_weights)})" + ) + + if self.shuffle: + self.rng = np.random.default_rng(self.seed + self.rank + self.epoch) + total_weights = sum(self.dataset_weights) + self.dataset_probablities = np.array( + [w / total_weights for w in self.dataset_weights] + ) + else: + if any([not isinstance(w, int) for w in self.dataset_weights]): + raise ValueError( + "Dataset weights must be integers when shuffle is False" + ) + + self.dataset_orders = [] + for i, w in enumerate(self.dataset_weights): + self.dataset_orders.extend([i] * w) + + self.drawn_samples = 0 + + def __iter__(self) -> Iterator: + return self + + def __next__(self) -> int: + if self.shuffle: + selected_dataset_idx = self.rng.choice( + range(len(self.dataset_weights)), p=self.dataset_probablities + ) + + # In order to avoid sampling the same example multiple times between the ranks, + # we limit each rank to a subset of the total number of samples in the dataset. + # For example if our dataset is [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], and we have 2 ranks, + # then rank 0 will ONLY sample from [0, 2, 4, 6, 8], and rank 1 from [1, 3, 5, 7, 9]. + # In each iteration we first produce `in_rank_sample` which is the sample index in the rank, + # based on the size of the subset which that rank can sample from. + # Then we compute `sample_idx_in_dataset` for the index of the sample in the whole dataset. + # For the above example if we are sampling for rank 1, we have `self.rng.integers(5)`. + # Let's assume the result is 2, then `in_rank_sample` is 2 (number "5" in the subset), + # so the sample index in the whole dataset is + # `in_rank_sample * self.num_replicas + self.rank`: 2 * 2 + 1 = 5. + + selected_dataset_size = self.dataset_sizes[selected_dataset_idx] + # 1) Getting sample index in the rank. + # NOTE: this may effectively drop the last batch, + # but given the sample sizes that we use this sampler with, it should not be an issue. + num_samples_in_rank = selected_dataset_size // self.num_replicas + in_rank_sample = self.rng.integers(num_samples_in_rank) + + # 2) Getting sample index in the dataset. + sample_idx_in_dataset = in_rank_sample * self.num_replicas + self.rank + + else: + # Iterate through the dataset orders in a round-robin fashion, offset by the rank + dataset_orders_idx = (self.rank + self.drawn_samples) % len( + self.dataset_orders + ) + selected_dataset_idx = self.dataset_orders[dataset_orders_idx] + # Get the sample index in the selected dataset by skipping with the num_replicas * drawn_samples + sample_idx_in_dataset = ( + self.drawn_samples * self.num_replicas + self.rank + ) % self.dataset_sizes[selected_dataset_idx] + self.drawn_samples += 1 + + # Getting the index of the sample in the whole dataset + # For example if the total dataset has 4 datasets with sizes [10, 20, 30, 5]. + # and our selected_dataset_idx=3 and sample_idx_in_dataset=5 + # then the index of the sample in the whole dataset is + # 10 (for dataset 1) + 20 (for dataset 1) + 5 (for sample_idx_in_dataset) = 35 + # This is because the first 10 samples are from the first dataset, the next 20 are from the second dataset, + # then we reach at the 3rd dataset which is the selected dataset, and the 5th sample in the 3rd dataset. + sample_idx = 0 + for i, d in enumerate(self.dataset_sizes): + if selected_dataset_idx == i: + break + sample_idx += d + sample_idx += sample_idx_in_dataset + + return sample_idx + + +def safe_next(iterator): + try: + return next(iterator) + except StopIteration: + return None + + +class MemoryEfficientDistributedWeightedSamplerLessRepeat(DistributedSampler): + """ + This class implements a memory efficient version of `DistributedWeightedSampler`. + It shares the same interface as `DistributedWeightedSampler`. + The effective change is pre-computing the permutations of indices over a subset of total indices. + This subset is the selected with picking the indices in a dataset with steps sizes equal to the world size. + For example, if world size is 12 and rank is 2, for a dataset of size N, + this sampler only permutes the indices in range(2, n, 12) + + Compared with MemoryEfficientDistributedWeightedSampler, this will reduce the effective number of repeat. + See discussions here: https://github.com/fairinternal/jepa-internal/pull/254 + """ + + def __init__( + self, + dataset, + num_replicas: Optional[int] = None, + rank: Optional[int] = None, + shuffle: bool = True, + seed: int = 0, + ): + logger.info( + f"Using MemoryEfficientDistributedWeightedSamplerLessRepeat with rank {rank} / {num_replicas}" + ) + assert hasattr( + dataset, "dataset_weights" + ), "Dataset must have dataset_weights property for using MemoryEfficientDistributedWeightedSamplerLessRepeat" + super().__init__( + dataset, + num_replicas=num_replicas, + rank=rank, + shuffle=shuffle, + seed=seed, + ) + + self._generator = torch.Generator() + self._generator.manual_seed(seed) + + self.dataset_weights = dataset.dataset_weights + self.dataset_sizes = [len(d) for d in dataset.datasets] + if len(self.dataset_sizes) != len(self.dataset_weights): + raise ValueError( + f"Number of datasets ({len(self.dataset_sizes)}) " + f"does not match number of dataset weights ({len(self.dataset_weights)})" + ) + + if self.shuffle: + self.rng = np.random.default_rng(self.seed + self.rank + self.epoch) + total_weights = sum(self.dataset_weights) + self.dataset_probablities = np.array( + [w / total_weights for w in self.dataset_weights] + ) + + # For each dataset we generate a permutation of the indices that will be processed by that rank. + # This is going to be the subset of indices, selected by the steps sizes of the world size. + logger.info( + f"Generating dataset indices for rank {self.rank} / {self.num_replicas}" + ) + + # Getting a RandomSampler for indices assigned to each dataset. + self.individual_dataset_sampler = [] + for ids, ds in enumerate(self.dataset_sizes): + + # NOTE: this may effectively drop the last batch, + # but given the sample sizes that we use this sampler with, it should not be an issue. + num_samples_in_rank = ds // self.num_replicas + self.individual_dataset_sampler.append( + self._new_sampler(num_samples_in_rank) + ) + + else: + if any([not isinstance(w, int) for w in self.dataset_weights]): + raise ValueError( + "Dataset weights must be integers when shuffle is False" + ) + + self.dataset_orders = [] + for i, w in enumerate(self.dataset_weights): + self.dataset_orders.extend([i] * w) + + self.drawn_samples = 0 + + def __iter__(self) -> Iterator: + return self + + def _new_sampler(self, sample_size: int) -> RandomSampler: + assert self.shuffle + + return iter( + RandomSampler( + range(sample_size), + generator=self._generator, + ) + ) + + def _in_rank_next_index_for_dataset(self, dataset_idx: int) -> int: + assert self.shuffle + + next_sampler_idx = safe_next(self.individual_dataset_sampler[dataset_idx]) + if next_sampler_idx is None: + # We have reached the end of the dataset, we need to reset the sampler. + num_samples_in_rank = self.dataset_sizes[dataset_idx] // self.num_replicas + self.individual_dataset_sampler[dataset_idx] = self._new_sampler( + num_samples_in_rank + ) + next_sampler_idx = safe_next(self.individual_dataset_sampler[dataset_idx]) + assert next_sampler_idx is not None + + return next_sampler_idx + + def __next__(self) -> int: + if self.shuffle: + selected_dataset_idx = self.rng.choice( + range(len(self.dataset_weights)), p=self.dataset_probablities + ) + in_rank_sample = self._in_rank_next_index_for_dataset(selected_dataset_idx) + + # 2) Getting sample index in the dataset. + sample_idx_in_dataset = in_rank_sample * self.num_replicas + self.rank + + else: + # Iterate through the dataset orders in a round-robin fashion, offset by the rank + dataset_orders_idx = (self.rank + self.drawn_samples) % len( + self.dataset_orders + ) + selected_dataset_idx = self.dataset_orders[dataset_orders_idx] + # Get the sample index in the selected dataset by skipping with the num_replicas * drawn_samples + sample_idx_in_dataset = ( + self.drawn_samples * self.num_replicas + self.rank + ) % self.dataset_sizes[selected_dataset_idx] + self.drawn_samples += 1 + + # Getting the index of the sample in the whole dataset + # For example if the total dataset has 4 datasets with sizes [10, 20, 30, 5]. + # and our selected_dataset_idx=3 and sample_idx_in_dataset=5 + # then the index of the sample in the whole dataset is + # 10 (for dataset 1) + 20 (for dataset 1) + 5 (for sample_idx_in_dataset) = 35 + # This is because the first 10 samples are from the first dataset, the next 20 are from the second dataset, + # then we reach at the 3rd dataset which is the selected dataset, and the 5th sample in the 3rd dataset. + sample_idx = 0 + for i, d in enumerate(self.dataset_sizes): + if selected_dataset_idx == i: + break + sample_idx += d + sample_idx += sample_idx_in_dataset + + return sample_idx diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/worker_init_fn.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/worker_init_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..32c93e91b42a21469d3e31b19c368da5927fd0a3 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/utils/worker_init_fn.py @@ -0,0 +1,76 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. + +# Copyright The Lightning AI team. + +# 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. + +# This code originally comes from PyTorch Lighting with some light modifications: +# https://github.com/Lightning-AI/pytorch-lightning/blob/a944e7744e57a5a2c13f3c73b9735edf2f71e329/src/lightning/fabric/utilities/seed.py + + +import os +import random +from typing import Optional + +import numpy as np +import torch + +from src.utils.logging import get_logger + +logger = get_logger("worker_init_fn") + + +def _generate_seed_sequence(base_seed: int, worker_id: int, global_rank: int, count: int) -> list[int]: + """Generates a sequence of seeds from a base seed, worker id and rank using the linear congruential generator (LCG) + algorithm.""" + # Combine base seed, worker id and rank into a unique 64-bit number + combined_seed = (base_seed << 32) | (worker_id << 16) | global_rank + seeds = [] + for _ in range(count): + # x_(n+1) = (a * x_n + c) mod m. With c=1, m=2^64 and a is D. Knuth's constant + combined_seed = (combined_seed * 6364136223846793005 + 1) & ((1 << 64) - 1) + seeds.append(combined_seed) + return seeds + + +def pl_worker_init_function(worker_id: int, rank: Optional[int] = None) -> None: # pragma: no cover + r"""The worker_init_fn that Lightning automatically adds to your dataloader if you previously set the seed with + ``seed_everything(seed, workers=True)``. + + See also the PyTorch documentation on + `randomness in DataLoaders `_. + + """ + # implementation notes: https://github.com/pytorch/pytorch/issues/5059#issuecomment-817392562 + if rank is None: + procid = os.environ.get("SLURM_PROCID") + if procid is None: + logger.warning("SLURM_PROCID is not set, setting rank to 0") + rank = 0 + else: + rank = int(procid) + + process_seed = torch.initial_seed() + # back out the base seed so we can use all the bits + base_seed = process_seed - worker_id + logger.debug( + f"Initializing random number generators of process {rank} worker {worker_id} with base seed {base_seed}" + ) + seed_sequence = _generate_seed_sequence(base_seed, worker_id, rank, count=4) + torch.manual_seed(seed_sequence[0]) # torch takes a 64-bit seed + random.seed((seed_sequence[1] << 32) | seed_sequence[2]) # combine two 64-bit seeds + + ss = np.random.SeedSequence([base_seed, worker_id, rank]) + np_rng_seed = ss.generate_state(4) + + np.random.seed(np_rng_seed) diff --git a/starVLA/facebookresearch_vjepa2_main/src/datasets/video_dataset.py b/starVLA/facebookresearch_vjepa2_main/src/datasets/video_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..05ec2a38ec55b6a817559d232397aabfcd32eec5 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/datasets/video_dataset.py @@ -0,0 +1,389 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +import os +import pathlib +import warnings +from logging import getLogger + +import numpy as np +import pandas as pd +import torch +import torchvision +from decord import cpu, VideoReader + +from src.datasets.utils.dataloader import ( + ConcatIndices, + MonitoredDataset, + NondeterministicDataLoader, +) +from src.datasets.utils.weighted_sampler import DistributedWeightedSampler + +_GLOBAL_SEED = 0 +logger = getLogger() + + +def make_videodataset( + data_paths, + batch_size, + frames_per_clip=8, + dataset_fpcs=None, + frame_step=4, + duration=None, + fps=None, + num_clips=1, + random_clip_sampling=True, + allow_clip_overlap=False, + filter_short_videos=False, + filter_long_videos=int(10**9), + transform=None, + shared_transform=None, + rank=0, + world_size=1, + datasets_weights=None, + collator=None, + drop_last=True, + num_workers=10, + pin_mem=True, + persistent_workers=True, + deterministic=True, + log_dir=None, +): + dataset = VideoDataset( + data_paths=data_paths, + datasets_weights=datasets_weights, + frames_per_clip=frames_per_clip, + dataset_fpcs=dataset_fpcs, + duration=duration, + fps=fps, + frame_step=frame_step, + num_clips=num_clips, + random_clip_sampling=random_clip_sampling, + allow_clip_overlap=allow_clip_overlap, + filter_short_videos=filter_short_videos, + filter_long_videos=filter_long_videos, + shared_transform=shared_transform, + transform=transform, + ) + + log_dir = pathlib.Path(log_dir) if log_dir else None + if log_dir: + log_dir.mkdir(parents=True, exist_ok=True) + # Worker ID will replace '%w' + resource_log_filename = log_dir / f"resource_file_{rank}_%w.csv" + dataset = MonitoredDataset( + dataset=dataset, + log_filename=str(resource_log_filename), + log_interval=10.0, + monitor_interval=5.0, + ) + + logger.info("VideoDataset dataset created") + if datasets_weights is not None: + dist_sampler = DistributedWeightedSampler( + dataset, num_replicas=world_size, rank=rank, shuffle=True + ) + else: + dist_sampler = torch.utils.data.distributed.DistributedSampler( + dataset, num_replicas=world_size, rank=rank, shuffle=True + ) + + if deterministic: + data_loader = torch.utils.data.DataLoader( + dataset, + collate_fn=collator, + sampler=dist_sampler, + batch_size=batch_size, + drop_last=drop_last, + pin_memory=pin_mem, + num_workers=num_workers, + persistent_workers=(num_workers > 0) and persistent_workers, + ) + else: + data_loader = NondeterministicDataLoader( + dataset, + collate_fn=collator, + sampler=dist_sampler, + batch_size=batch_size, + drop_last=drop_last, + pin_memory=pin_mem, + num_workers=num_workers, + persistent_workers=(num_workers > 0) and persistent_workers, + ) + logger.info("VideoDataset unsupervised data loader created") + + return dataset, data_loader, dist_sampler + + +class VideoDataset(torch.utils.data.Dataset): + """Video classification dataset.""" + + def __init__( + self, + data_paths, + datasets_weights=None, + frames_per_clip=16, + fps=None, + dataset_fpcs=None, + frame_step=4, + num_clips=1, + transform=None, + shared_transform=None, + random_clip_sampling=True, + allow_clip_overlap=False, + filter_short_videos=False, + filter_long_videos=int(10**9), + duration=None, # duration in seconds + ): + self.data_paths = data_paths + self.datasets_weights = datasets_weights + self.frame_step = frame_step + self.num_clips = num_clips + self.transform = transform + self.shared_transform = shared_transform + self.random_clip_sampling = random_clip_sampling + self.allow_clip_overlap = allow_clip_overlap + self.filter_short_videos = filter_short_videos + self.filter_long_videos = filter_long_videos + self.duration = duration + self.fps = fps + + if sum([v is not None for v in (fps, duration, frame_step)]) != 1: + raise ValueError( + f"Must specify exactly one of either {fps=}, {duration=}, or {frame_step=}." + ) + + if isinstance(data_paths, str): + data_paths = [data_paths] + + if dataset_fpcs is None: + self.dataset_fpcs = [frames_per_clip for _ in data_paths] + else: + if len(dataset_fpcs) != len(data_paths): + raise ValueError( + "Frames per clip not properly specified for NFS data paths" + ) + self.dataset_fpcs = dataset_fpcs + + if VideoReader is None: + raise ImportError( + 'Unable to import "decord" which is required to read videos.' + ) + + # Load video paths and labels + samples, labels = [], [] + self.num_samples_per_dataset = [] + for data_path in self.data_paths: + + if data_path[-4:] == ".csv": + try: + data = pd.read_csv(data_path, header=None, delimiter=" ") + except pd.errors.ParserError: + # In image captioning datasets where we have space, we use :: as delimiter. + data = pd.read_csv(data_path, header=None, delimiter="::") + samples += list(data.values[:, 0]) + labels += list(data.values[:, 1]) + num_samples = len(data) + self.num_samples_per_dataset.append(num_samples) + + elif data_path[-4:] == ".npy": + data = np.load(data_path, allow_pickle=True) + data = list(map(lambda x: repr(x)[1:-1], data)) + samples += data + labels += [0] * len(data) + num_samples = len(data) + self.num_samples_per_dataset.append(len(data)) + + self.per_dataset_indices = ConcatIndices(self.num_samples_per_dataset) + + # [Optional] Weights for each sample to be used by downstream + # weighted video sampler + self.sample_weights = None + if self.datasets_weights is not None: + self.sample_weights = [] + for dw, ns in zip(self.datasets_weights, self.num_samples_per_dataset): + self.sample_weights += [dw / ns] * ns + + self.samples = samples + self.labels = labels + + def __getitem__(self, index): + sample = self.samples[index] + loaded_sample = False + # Keep trying to load videos until you find a valid sample + while not loaded_sample: + if not isinstance(sample, str): + logger.warning("Invalid sample.") + else: + if sample.split(".")[-1].lower() in ("jpg", "png", "jpeg"): + loaded_sample = self.get_item_image(index) + else: + loaded_sample = self.get_item_video(index) + + if not loaded_sample: + index = np.random.randint(self.__len__()) + sample = self.samples[index] + + return loaded_sample + + def get_item_video(self, index): + sample = self.samples[index] + dataset_idx, _ = self.per_dataset_indices[index] + frames_per_clip = self.dataset_fpcs[dataset_idx] + + buffer, clip_indices = self.loadvideo_decord( + sample, frames_per_clip + ) # [T H W 3] + loaded_video = len(buffer) > 0 + if not loaded_video: + return + + # Label/annotations for video + label = self.labels[index] + + def split_into_clips(video): + """Split video into a list of clips""" + fpc = frames_per_clip + nc = self.num_clips + return [video[i * fpc : (i + 1) * fpc] for i in range(nc)] + + # Parse video into frames & apply data augmentations + if self.shared_transform is not None: + buffer = self.shared_transform(buffer) + buffer = split_into_clips(buffer) + if self.transform is not None: + buffer = [self.transform(clip) for clip in buffer] + + return buffer, label, clip_indices + + def get_item_image(self, index): + sample = self.samples[index] + dataset_idx, _ = self.per_dataset_indices[index] + fpc = self.dataset_fpcs[dataset_idx] + + try: + image_tensor = torchvision.io.read_image( + path=sample, mode=torchvision.io.ImageReadMode.RGB + ) + except Exception: + return + label = self.labels[index] + clip_indices = [np.arange(start=0, stop=fpc, dtype=np.int32)] + + # Expanding the input image [3, H, W] ==> [T, 3, H, W] + buffer = image_tensor.unsqueeze(dim=0).repeat((fpc, 1, 1, 1)) + buffer = buffer.permute((0, 2, 3, 1)) # [T, 3, H, W] ==> [T H W 3] + + if self.shared_transform is not None: + # Technically we can have only transform, doing this just for the sake of consistency with videos. + buffer = self.shared_transform(buffer) + + if self.transform is not None: + buffer = [self.transform(buffer)] + + return buffer, label, clip_indices + + def loadvideo_decord(self, sample, fpc): + """Load video content using Decord""" + + fname = sample + if not os.path.exists(fname): + warnings.warn(f"video path not found {fname=}") + return [], None + + _fsize = os.path.getsize(fname) + if _fsize > self.filter_long_videos: + warnings.warn(f"skipping long video of size {_fsize=} (bytes)") + return [], None + + try: + vr = VideoReader(fname, num_threads=-1, ctx=cpu(0)) + except Exception: + return [], None + + fstp = self.frame_step + if self.duration is not None or self.fps is not None: + try: + video_fps = math.ceil(vr.get_avg_fps()) + except Exception as e: + logger.warning(e) + + if self.duration is not None: + assert self.fps is None + fstp = int(self.duration * video_fps / fpc) + else: + assert self.duration is None + fstp = video_fps // self.fps + + assert fstp is not None and fstp > 0 + clip_len = int(fpc * fstp) + + if self.filter_short_videos and len(vr) < clip_len: + warnings.warn(f"skipping video of length {len(vr)}") + return [], None + + vr.seek(0) # Go to start of video before sampling frames + + # Partition video into equal sized segments and sample each clip + # from a different segment + partition_len = len(vr) // self.num_clips + + all_indices, clip_indices = [], [] + for i in range(self.num_clips): + + if partition_len > clip_len: + # If partition_len > clip len, then sample a random window of + # clip_len frames within the segment + end_indx = clip_len + if self.random_clip_sampling: + end_indx = np.random.randint(clip_len, partition_len) + start_indx = end_indx - clip_len + indices = np.linspace(start_indx, end_indx, num=fpc) + indices = np.clip(indices, start_indx, end_indx - 1).astype(np.int64) + # -- + indices = indices + i * partition_len + else: + # If partition overlap not allowed and partition_len < clip_len + # then repeatedly append the last frame in the segment until + # we reach the desired clip length + if not self.allow_clip_overlap: + indices = np.linspace(0, partition_len, num=partition_len // fstp) + indices = np.concatenate( + ( + indices, + np.ones(fpc - partition_len // fstp) * partition_len, + ) + ) + indices = np.clip(indices, 0, partition_len - 1).astype(np.int64) + # -- + indices = indices + i * partition_len + + # If partition overlap is allowed and partition_len < clip_len + # then start_indx of segment i+1 will lie within segment i + else: + sample_len = min(clip_len, len(vr)) - 1 + indices = np.linspace(0, sample_len, num=sample_len // fstp) + indices = np.concatenate( + ( + indices, + np.ones(fpc - sample_len // fstp) * sample_len, + ) + ) + indices = np.clip(indices, 0, sample_len - 1).astype(np.int64) + # -- + clip_step = 0 + if len(vr) > clip_len: + clip_step = (len(vr) - clip_len) // (self.num_clips - 1) + indices = indices + i * clip_step + + clip_indices.append(indices) + all_indices.extend(list(indices)) + + buffer = vr.get_batch(all_indices).asnumpy() + return buffer, clip_indices + + def __len__(self): + return len(self.samples) diff --git a/starVLA/facebookresearch_vjepa2_main/src/hub/__init__.py b/starVLA/facebookresearch_vjepa2_main/src/hub/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/starVLA/facebookresearch_vjepa2_main/src/hub/backbones.py b/starVLA/facebookresearch_vjepa2_main/src/hub/backbones.py new file mode 100644 index 0000000000000000000000000000000000000000..5d5106e83e0b80627200de12c744d214bd8bd69f --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/hub/backbones.py @@ -0,0 +1,343 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +# VJEPA_BASE_URL = "https://dl.fbaipublicfiles.com/vjepa2" + +# for testing +VJEPA_BASE_URL = "http://localhost:8300" + +ARCH_NAME_MAP = { + # V-JEPA 2 + "vit_large": ("vit_large", "vitl"), + "vit_huge": ("vit_huge", "vith"), + "vit_giant": ("vit_giant_xformers", "vitg"), + "vit_ac_giant": ("vit_giant_xformers", "vjepa2-ac-vitg"), + "vit_giant_384": ("vit_giant_xformers", "vitg-384"), + # V-JEPA 2.1 + "vjepa2_1_vit_base_384": ("vit_base", "vjepa2_1_vitb_dist_vitG_384"), + "vjepa2_1_vit_large_384": ("vit_large", "vjepa2_1_vitl_dist_vitG_384"), + "vjepa2_1_vit_giant_384": ("vit_giant_xformers", "vjepa2_1_vitg_384"), + "vjepa2_1_vit_gigantic_384": ("vit_gigantic_xformers", "vjepa2_1_vitG_384"), +} + + +def _clean_backbone_key(state_dict): + for key, val in state_dict.copy().items(): + _ = state_dict.pop(key) + key = key.replace("module.", "") + key = key.replace("backbone.", "") + state_dict[key] = val + return state_dict + + +def _make_vjepa2_ac_model( + *, + model_name: str = "vit_ac_giant", + img_size=256, + patch_size=16, + tubelet_size=2, + num_frames=64, + pretrained: bool = True, + **kwargs, +): + from ..models import ( + ac_predictor as vit_ac_predictor, + vision_transformer as vit_encoder, + ) + + vit_encoder_kwargs = dict( + patch_size=patch_size, + img_size=(img_size, img_size), + num_frames=num_frames, + tubelet_size=tubelet_size, + use_sdpa=True, + use_SiLU=False, + wide_SiLU=True, + uniform_power=False, + use_rope=True, + ) + vit_encoder_kwargs.update(**kwargs) + + arch_name = ARCH_NAME_MAP[model_name][0] + encoder = vit_encoder.__dict__[arch_name](**vit_encoder_kwargs) + + vit_predictor_kwargs = dict( + img_size=(img_size, img_size), + patch_size=patch_size, + num_frames=num_frames, + tubelet_size=tubelet_size, + embed_dim=encoder.embed_dim, + ) + vit_predictor_kwargs.update(**kwargs) + + predictor = vit_ac_predictor.__dict__["vit_ac_predictor"](**vit_predictor_kwargs) + + if pretrained: + model_file = ARCH_NAME_MAP[model_name][-1] + if pretrained is True: + url = VJEPA_BASE_URL + f"/{model_file}.pt" + state_dict = torch.hub.load_state_dict_from_url(url, map_location="cpu") + else: + # pretrained is a path to local checkpoint file + state_dict = torch.load(pretrained, map_location="cpu") + encoder_state_dict = _clean_backbone_key(state_dict["encoder"]) + encoder.load_state_dict(encoder_state_dict, strict=False) + predictor_state_dict = _clean_backbone_key(state_dict["predictor"]) + predictor.load_state_dict(predictor_state_dict, strict=True) + + return encoder, predictor + + +def _make_vjepa2_model( + *, + model_name: str = "vit_large", + checkpoint_key="target_encoder", + img_size=256, + patch_size=16, + tubelet_size=2, + num_frames=64, + predictor_embed_dim=384, + predictor_out_embed_dim=None, + pretrained: bool = True, + **kwargs, +): + from ..models import predictor as vit_predictor, vision_transformer as vit_encoder + + vit_encoder_kwargs = dict( + patch_size=patch_size, + img_size=(img_size, img_size), + num_frames=num_frames, + tubelet_size=tubelet_size, + use_sdpa=True, + use_SiLU=False, + wide_SiLU=True, + uniform_power=False, + use_rope=True, + ) + vit_encoder_kwargs.update(**kwargs) + + arch_name = ARCH_NAME_MAP[model_name][0] + encoder = vit_encoder.__dict__[arch_name](**vit_encoder_kwargs) + + vit_predictor_kwargs = dict( + img_size=(img_size, img_size), + patch_size=patch_size, + use_mask_tokens=True, + embed_dim=encoder.embed_dim, + predictor_embed_dim=predictor_embed_dim, + out_embed_dim=predictor_out_embed_dim, + num_frames=num_frames, + tubelet_size=tubelet_size, + depth=12, + num_heads=12, + num_mask_tokens=10, + use_rope=True, + uniform_power=False, + use_sdpa=True, + use_silu=False, + wide_silu=True, + ) + vit_predictor_kwargs.update(**kwargs) + + predictor = vit_predictor.__dict__["vit_predictor"](**vit_predictor_kwargs) + + if pretrained: + model_file = ARCH_NAME_MAP[model_name][-1] + url = VJEPA_BASE_URL + f"/{model_file}.pt" + state_dict = torch.hub.load_state_dict_from_url(url, map_location="cpu") + encoder_state_dict = _clean_backbone_key(state_dict[checkpoint_key]) + encoder.load_state_dict( + encoder_state_dict, strict=False + ) # state_dict has pos_embed but we use RoPE + predictor_state_dict = _clean_backbone_key(state_dict["predictor"]) + predictor.load_state_dict( + predictor_state_dict, strict=False + ) # state_dict has pos_embed but we use RoPE + + return encoder, predictor + + +def vjepa2_vit_large(*, pretrained: bool = True, **kwargs): + """ + VJEPA 2 ViT-Large model + """ + return _make_vjepa2_model( + model_name="vit_large", img_size=256, pretrained=pretrained, **kwargs + ) + + +def vjepa2_vit_huge(*, pretrained: bool = True, **kwargs): + """ + VJEPA 2 ViT-Huge model + """ + return _make_vjepa2_model( + model_name="vit_huge", img_size=256, pretrained=pretrained, **kwargs + ) + + +def vjepa2_vit_giant(*, pretrained: bool = True, **kwargs): + """ + VJEPA 2 ViT-giant model + """ + return _make_vjepa2_model( + model_name="vit_giant", img_size=256, pretrained=pretrained, **kwargs + ) + + +def vjepa2_vit_giant_384(*, pretrained: bool = True, **kwargs): + """ + VJEPA 2 ViT-giant-384 model + """ + return _make_vjepa2_model( + model_name="vit_giant_384", img_size=384, pretrained=pretrained, **kwargs + ) + + +def vjepa2_ac_vit_giant(*, pretrained: bool = True, **kwargs): + """ + VJEPA 2-AC ViT-giant model + """ + return _make_vjepa2_ac_model( + model_name="vit_ac_giant", img_size=256, pretrained=pretrained, **kwargs + ) + + +# ########## V-JEPA 2.1 ########## + + +vjepa2_1_teacher_embed_dim = 1664 + + +def _make_vjepa2_1_model( + model_name: str = "vjepa2_1_vit_large_384", + checkpoint_key="target_encoder", + img_size=384, + patch_size=16, + tubelet_size=2, + num_frames=64, + predictor_embed_dim=384, + predictor_depth=24, + predictor_num_mask_tokens=10, + n_output_distillation=4, + return_all_tokens=False, + teacher_embed_dim=None, + pretrained: bool = True, + **kwargs, +): + from app.vjepa_2_1.models import predictor as vit_predictor, vision_transformer as vit_encoder + + vit_encoder_kwargs = dict( + patch_size=patch_size, + img_size=(img_size, img_size), + num_frames=num_frames, + tubelet_size=tubelet_size, + use_sdpa=True, + use_SiLU=False, + wide_SiLU=True, + uniform_power=False, + use_rope=True, + img_temporal_dim_size=1, + interpolate_rope=True, + ) + vit_encoder_kwargs.update(**kwargs) + + arch_name = ARCH_NAME_MAP[model_name][0] + encoder = vit_encoder.__dict__[arch_name](**vit_encoder_kwargs) + + vit_predictor_kwargs = dict( + img_size=(img_size, img_size), + patch_size=patch_size, + use_mask_tokens=True, + embed_dim=encoder.embed_dim, + predictor_embed_dim=predictor_embed_dim, + teacher_embed_dim=teacher_embed_dim, + num_frames=num_frames, + tubelet_size=tubelet_size, + depth=predictor_depth, + num_heads=12, + num_mask_tokens=predictor_num_mask_tokens, + use_rope=True, + uniform_power=False, + use_sdpa=True, + use_silu=False, + wide_silu=True, + n_output_distillation=n_output_distillation, + return_all_tokens=return_all_tokens, + img_temporal_dim_size=1, + ) + vit_predictor_kwargs.update(**kwargs) + + predictor = vit_predictor.__dict__["vit_predictor"](**vit_predictor_kwargs) + + if pretrained: + model_file = ARCH_NAME_MAP[model_name][-1] + url = VJEPA_BASE_URL + f"/{model_file}.pt" + state_dict = torch.hub.load_state_dict_from_url(url, map_location="cpu") + encoder_state_dict = _clean_backbone_key(state_dict[checkpoint_key]) + encoder.load_state_dict( + encoder_state_dict, strict=True + ) # state_dict has pos_embed but we use RoPE + predictor_state_dict = _clean_backbone_key(state_dict["predictor"]) + predictor.load_state_dict( + predictor_state_dict, strict=True + ) # state_dict has pos_embed but we use RoPE + + return encoder, predictor + + +def vjepa2_1_vit_base_384(*, pretrained: bool = True, **kwargs): + return _make_vjepa2_1_model( + model_name="vjepa2_1_vit_base_384", + checkpoint_key="ema_encoder", + img_size=384, + predictor_depth=12, + predictor_num_mask_tokens=8, + n_output_distillation=1, + return_all_tokens=True, + teacher_embed_dim=vjepa2_1_teacher_embed_dim, + pretrained=pretrained, + **kwargs, + ) + + +def vjepa2_1_vit_large_384(*, pretrained: bool = True, **kwargs): + return _make_vjepa2_1_model( + model_name="vjepa2_1_vit_large_384", + checkpoint_key="ema_encoder", + img_size=384, + predictor_depth=12, + predictor_num_mask_tokens=8, + n_output_distillation=1, + return_all_tokens=True, + teacher_embed_dim=vjepa2_1_teacher_embed_dim, + pretrained=pretrained, + **kwargs, + ) + + +def vjepa2_1_vit_giant_384(*, pretrained: bool = True, **kwargs): + return _make_vjepa2_1_model( + model_name="vjepa2_1_vit_giant_384", + img_size=384, + predictor_num_mask_tokens=8, + n_output_distillation=4, + return_all_tokens=True, + pretrained=pretrained, + **kwargs, + ) + + +def vjepa2_1_vit_gigantic_384(*, pretrained: bool = True, **kwargs): + return _make_vjepa2_1_model( + model_name="vjepa2_1_vit_gigantic_384", + img_size=384, + predictor_num_mask_tokens=8, + n_output_distillation=4, + return_all_tokens=True, + pretrained=pretrained, + **kwargs, + ) diff --git a/starVLA/facebookresearch_vjepa2_main/src/masks/default.py b/starVLA/facebookresearch_vjepa2_main/src/masks/default.py new file mode 100644 index 0000000000000000000000000000000000000000..11bd3de0a124ba12aba5bb8e27fbe46f44895122 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/masks/default.py @@ -0,0 +1,18 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +from logging import getLogger + +import torch + +_GLOBAL_SEED = 0 +logger = getLogger() + + +class DefaultCollator(object): + + def __call__(self, batch): + collated_batch = torch.utils.data.default_collate(batch) + return collated_batch, None, None diff --git a/starVLA/facebookresearch_vjepa2_main/src/masks/multiseq_multiblock3d.py b/starVLA/facebookresearch_vjepa2_main/src/masks/multiseq_multiblock3d.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8e2f2f079c42b8f8190f9af1ff07005db6b6d2 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/masks/multiseq_multiblock3d.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import math +from logging import getLogger +from multiprocessing import Value + +import torch + +_GLOBAL_SEED = 0 +logger = getLogger() + + +class MaskCollator(object): + + def __init__( + self, + cfgs_mask, + dataset_fpcs, + crop_size=(224, 224), + patch_size=(16, 16), + tubelet_size=2, + ): + super(MaskCollator, self).__init__() + + self.mask_generators = dict() + for fpc in dataset_fpcs: + self.mask_generators[fpc] = [] + for m in cfgs_mask: + mask_generator = _MaskGenerator( + crop_size=crop_size, + num_frames=fpc, + spatial_patch_size=patch_size, + temporal_patch_size=tubelet_size, + spatial_pred_mask_scale=m.get("spatial_scale"), + temporal_pred_mask_scale=m.get("temporal_scale"), + aspect_ratio=m.get("aspect_ratio"), + npred=m.get("num_blocks"), + max_context_frames_ratio=m.get("max_temporal_keep", 1.0), + max_keep=m.get("max_keep", None), + full_complement=m.get("full_complement", False), + pred_full_complement=m.get("pred_full_complement", False), + inv_block=m.get("inv_block", False), + ) + self.mask_generators[fpc].append(mask_generator) + + def step(self): + for fpc in self.mask_generators: + for mask_generator in self.mask_generators[fpc]: + mask_generator.step() + + def __call__(self, batch): + + # Batch: [buffer, label, clip_indices] for video + # or [buffer, label] for images + filtered_batches = {fpc: [] for fpc in self.mask_generators} + for sample in batch: + # Check if sample is from video dataset (has clip_indices) or image dataset + if len(sample) >= 3 and isinstance(sample[-1], (list, tuple)): + # Video sample: sample[-1] is clip_indices, sample[-1][-1] contains frame indices + try: + fpc = len(sample[-1][-1]) + except (TypeError, IndexError): + # Fallback: assume single frame if structure is unexpected + fpc = 1 + else: + # Image sample: single frame + fpc = 1 + if fpc in filtered_batches: + filtered_batches[fpc] += [sample] + + fpc_collations = [] + for fpc in filtered_batches: + fpc_batch = filtered_batches[fpc] + batch_size = len(fpc_batch) + if batch_size == 0: + continue + collated_batch = torch.utils.data.default_collate(fpc_batch) + collated_masks_pred, collated_masks_enc = [], [] + for i, mask_generator in enumerate(self.mask_generators[fpc]): + masks_enc, masks_pred = mask_generator(batch_size) + collated_masks_enc.append(masks_enc) + collated_masks_pred.append(masks_pred) + fpc_collations += [ + (collated_batch, collated_masks_enc, collated_masks_pred) + ] + + return fpc_collations + + +class _MaskGenerator(object): + + def __init__( + self, + crop_size=(224, 224), + num_frames=16, + spatial_patch_size=(16, 16), + temporal_patch_size=2, + spatial_pred_mask_scale=(0.2, 0.8), + temporal_pred_mask_scale=(1.0, 1.0), + aspect_ratio=(0.3, 3.0), + npred=1, + max_context_frames_ratio=1.0, + max_keep=None, + inv_block=False, + full_complement=False, + pred_full_complement=False, + ): + super(_MaskGenerator, self).__init__() + if not isinstance(crop_size, tuple): + crop_size = (crop_size,) * 2 + if not isinstance(spatial_patch_size, tuple): + spatial_patch_size = (spatial_patch_size,) * 2 + self.crop_size = crop_size + self.height, self.width = [ + crop_size[i] // spatial_patch_size[i] for i in (0, 1) + ] + self.duration = num_frames // temporal_patch_size + self.full_complement = full_complement + self.pred_full_complement = pred_full_complement + + self.spatial_patch_size = spatial_patch_size + self.temporal_patch_size = temporal_patch_size + + self.aspect_ratio = aspect_ratio + self.spatial_pred_mask_scale = spatial_pred_mask_scale + self.temporal_pred_mask_scale = temporal_pred_mask_scale + self.npred = npred + self.max_context_duration = max( + 1, int(self.duration * max_context_frames_ratio) + ) # maximum number of time-steps (frames) spanned by context mask + self.max_keep = max_keep # maximum number of patches to keep in context + self._itr_counter = Value("i", -1) # collator is shared across worker processes + self.inv_block = inv_block + + def step(self): + i = self._itr_counter + with i.get_lock(): + i.value += 1 + v = i.value + return v + + def _sample_block_size( + self, generator, temporal_scale, spatial_scale, aspect_ratio_scale + ): + # -- Sample temporal block mask scale + _rand = torch.rand(1, generator=generator).item() + min_t, max_t = temporal_scale + temporal_mask_scale = min_t + _rand * (max_t - min_t) + t = max(1, int(self.duration * temporal_mask_scale)) + + # -- Sample spatial block mask scale + _rand = torch.rand(1, generator=generator).item() + min_s, max_s = spatial_scale + spatial_mask_scale = min_s + _rand * (max_s - min_s) + spatial_num_keep = int(self.height * self.width * spatial_mask_scale) + + # -- Sample block aspect-ratio + _rand = torch.rand(1, generator=generator).item() + min_ar, max_ar = aspect_ratio_scale + aspect_ratio = min_ar + _rand * (max_ar - min_ar) + + # -- Compute block height and width (given scale and aspect-ratio) + h = int(round(math.sqrt(spatial_num_keep * aspect_ratio))) + w = int(round(math.sqrt(spatial_num_keep / aspect_ratio))) + h = min(h, self.height) + w = min(w, self.width) + + return (t, h, w) + + def _sample_block_mask(self, b_size): + t, h, w = b_size + top = torch.randint(0, self.height - h + 1, (1,)) + left = torch.randint(0, self.width - w + 1, (1,)) + start = torch.randint(0, self.duration - t + 1, (1,)) + + mask = torch.ones((self.duration, self.height, self.width), dtype=torch.int32) + mask[start : start + t, top : top + h, left : left + w] = 0 + + # Context mask will only span the first X frames + # (X=self.max_context_frames) + if self.max_context_duration < self.duration: + mask[self.max_context_duration :, :, :] = 0 + + # -- + return mask + + def __call__(self, batch_size): + """ + Create encoder and predictor masks when collating imgs into a batch + # 1. sample pred block size using seed + # 2. sample several pred block locations for each image (w/o seed) + # 3. return pred masks and complement (enc mask) + """ + seed = self.step() + g = torch.Generator() + g.manual_seed(seed) + p_size = self._sample_block_size( + generator=g, + temporal_scale=self.temporal_pred_mask_scale, + spatial_scale=self.spatial_pred_mask_scale, + aspect_ratio_scale=self.aspect_ratio, + ) + + collated_masks_pred, collated_masks_enc = [], [] + min_keep_enc = min_keep_pred = self.duration * self.height * self.width + for _ in range(batch_size): + + empty_context = True + while empty_context: + + mask_e = torch.ones( + (self.duration, self.height, self.width), dtype=torch.int32 + ) + for _ in range(self.npred): + mask_e *= self._sample_block_mask(p_size) + mask_e = mask_e.flatten() + + mask_p = torch.argwhere(mask_e == 0).squeeze() + mask_e = torch.nonzero(mask_e).squeeze() + + empty_context = len(mask_e) == 0 + if not empty_context: + min_keep_pred = min(min_keep_pred, len(mask_p)) + min_keep_enc = min(min_keep_enc, len(mask_e)) + collated_masks_pred.append(mask_p) + collated_masks_enc.append(mask_e) + + if self.max_keep is not None: + min_keep_enc = min(min_keep_enc, self.max_keep) + + collated_masks_enc = [cm[:min_keep_enc] for cm in collated_masks_enc] + collated_masks_pred = [cm[:min_keep_pred] for cm in collated_masks_pred] + if self.full_complement: # predictor mask is just complement of encoder mask + collated_masks_pred = [ + torch.tensor( + sorted( + list( + set(range(int(self.duration * self.height * self.width))) + - set(cm.tolist()) + ) + ), + dtype=cm.dtype, + ) + for cm in collated_masks_enc + ] + elif self.pred_full_complement: + collated_masks_enc = [ + torch.tensor( + sorted( + list( + set(range(int(self.duration * self.height * self.width))) + - set(cm.tolist()) + ) + ), + dtype=cm.dtype, + ) + for cm in collated_masks_pred + ] + + collated_masks_enc = torch.utils.data.default_collate(collated_masks_enc) + collated_masks_pred = torch.utils.data.default_collate(collated_masks_pred) + + if self.inv_block: + return collated_masks_pred, collated_masks_enc # predict context from block + else: + return collated_masks_enc, collated_masks_pred diff --git a/starVLA/facebookresearch_vjepa2_main/src/masks/utils.py b/starVLA/facebookresearch_vjepa2_main/src/masks/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e1950be58bd0a95e7ab99113fd7abd40f92af4c8 --- /dev/null +++ b/starVLA/facebookresearch_vjepa2_main/src/masks/utils.py @@ -0,0 +1,21 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +import torch + + +def apply_masks(x, masks, concat=True): + """ + :param x: tensor of shape [B (batch-size), N (num-patches), D (feature-dim)] + :param masks: list of tensors of shape [B, K] containing indices of K patches in [N] to keep + """ + all_x = [] + for m in masks: + mask_keep = m.unsqueeze(-1).repeat(1, 1, x.size(-1)) + all_x += [torch.gather(x, dim=1, index=mask_keep)] + if not concat: + return all_x + + return torch.cat(all_x, dim=0) diff --git a/starVLA/facebookresearch_vjepa2_main/src/models/__init__.py b/starVLA/facebookresearch_vjepa2_main/src/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391