Publish sealed evaluation sources, batch 20
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- starVLA/dinov3/dinov3/eval/text/tokenizer.py +67 -0
- starVLA/dinov3/dinov3/eval/text/train_dinotxt.py +339 -0
- starVLA/dinov3/dinov3/eval/text/vision_tower.py +207 -0
- starVLA/dinov3/dinov3/eval/utils.py +286 -0
- starVLA/dinov3/dinov3/fsdp/__init__.py +0 -0
- starVLA/dinov3/dinov3/fsdp/ac_compile_parallelize.py +220 -0
- starVLA/dinov3/dinov3/hub/__init__.py +0 -0
- starVLA/dinov3/dinov3/hub/backbones.py +612 -0
- starVLA/dinov3/dinov3/hub/classifiers.py +113 -0
- starVLA/dinov3/dinov3/hub/depthers.py +197 -0
- starVLA/dinov3/dinov3/hub/detectors.py +132 -0
- starVLA/dinov3/dinov3/hub/dinotxt.py +83 -0
- starVLA/dinov3/dinov3/hub/segmentors.py +85 -0
- starVLA/dinov3/dinov3/hub/utils.py +18 -0
- starVLA/dinov3/dinov3/layers/__init__.py +13 -0
- starVLA/dinov3/dinov3/layers/attention.py +164 -0
- starVLA/dinov3/dinov3/layers/block.py +269 -0
- starVLA/dinov3/dinov3/layers/dino_head.py +67 -0
- starVLA/dinov3/dinov3/layers/ffn_layers.py +77 -0
- starVLA/dinov3/dinov3/layers/fp8_linear.py +141 -0
- starVLA/dinov3/dinov3/layers/layer_scale.py +29 -0
- starVLA/dinov3/dinov3/layers/patch_embed.py +89 -0
- starVLA/dinov3/dinov3/layers/rms_norm.py +24 -0
- starVLA/dinov3/dinov3/layers/rope_position_encoding.py +121 -0
- starVLA/dinov3/dinov3/layers/sparse_linear.py +90 -0
- starVLA/dinov3/dinov3/logging/__init__.py +180 -0
- starVLA/dinov3/dinov3/logging/helpers.py +203 -0
- starVLA/dinov3/dinov3/loss/__init__.py +9 -0
- starVLA/dinov3/dinov3/loss/dino_clstoken_loss.py +124 -0
- starVLA/dinov3/dinov3/loss/gram_loss.py +84 -0
- starVLA/dinov3/dinov3/loss/ibot_patch_loss.py +142 -0
- starVLA/dinov3/dinov3/loss/koleo_loss.py +113 -0
- starVLA/dinov3/dinov3/models/__init__.py +133 -0
- starVLA/dinov3/dinov3/models/convnext.py +350 -0
- starVLA/dinov3/dinov3/models/vision_transformer.py +416 -0
- starVLA/dinov3/dinov3/run/__init__.py +0 -0
- starVLA/dinov3/dinov3/run/init.py +33 -0
- starVLA/dinov3/dinov3/run/submit.py +208 -0
- starVLA/dinov3/dinov3/thirdparty/CLIP/__init__.py +0 -0
- starVLA/dinov3/dinov3/thirdparty/CLIP/clip/__init__.py +0 -0
- starVLA/dinov3/dinov3/thirdparty/CLIP/clip/simple_tokenizer.py +143 -0
- starVLA/dinov3/dinov3/thirdparty/__init__.py +0 -0
- starVLA/dinov3/dinov3/train/__init__.py +8 -0
- starVLA/dinov3/dinov3/train/cosine_lr_scheduler.py +85 -0
- starVLA/dinov3/dinov3/train/multidist_meta_arch.py +165 -0
- starVLA/dinov3/dinov3/train/param_groups.py +180 -0
- starVLA/dinov3/dinov3/train/ssl_meta_arch.py +820 -0
- starVLA/dinov3/dinov3/train/train.py +637 -0
- starVLA/dinov3/dinov3/utils/__init__.py +16 -0
- starVLA/dinov3/dinov3/utils/cluster.py +103 -0
starVLA/dinov3/dinov3/eval/text/tokenizer.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from typing import List, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from dinov3.thirdparty.CLIP.clip.simple_tokenizer import SimpleTokenizer
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Tokenizer(SimpleTokenizer):
|
| 13 |
+
def __init__(self, vocab_path: str):
|
| 14 |
+
SimpleTokenizer.__init__(self, bpe_path=vocab_path)
|
| 15 |
+
|
| 16 |
+
def tokenize(
|
| 17 |
+
self, texts: Union[str, List[str]], context_length: int = 77
|
| 18 |
+
) -> torch.LongTensor:
|
| 19 |
+
"""
|
| 20 |
+
Returns the tokenized representation of given input string(s)
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
texts : Union[str, List[str]]
|
| 25 |
+
An input string or a list of input strings to tokenize
|
| 26 |
+
context_length : int
|
| 27 |
+
The context length to use; all CLIP models use 77 as the context length
|
| 28 |
+
|
| 29 |
+
Returns
|
| 30 |
+
-------
|
| 31 |
+
A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
|
| 32 |
+
"""
|
| 33 |
+
if isinstance(texts, str):
|
| 34 |
+
texts = [texts]
|
| 35 |
+
sot_token = self.encoder["<|startoftext|>"]
|
| 36 |
+
eot_token = self.encoder["<|endoftext|>"]
|
| 37 |
+
all_tokens = [[sot_token] + self.encode(text) + [eot_token] for text in texts]
|
| 38 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
|
| 39 |
+
|
| 40 |
+
for i, tokens in enumerate(all_tokens):
|
| 41 |
+
if len(tokens) > context_length:
|
| 42 |
+
tokens = tokens[:context_length] # Truncate
|
| 43 |
+
tokens[-1] = eot_token
|
| 44 |
+
result[i, : len(tokens)] = torch.tensor(tokens)
|
| 45 |
+
|
| 46 |
+
return result
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_tokenizer(bpe_path_or_url: str) -> Tokenizer | None:
|
| 50 |
+
import urllib
|
| 51 |
+
from io import BytesIO
|
| 52 |
+
|
| 53 |
+
from .tokenizer import Tokenizer
|
| 54 |
+
|
| 55 |
+
if urllib.parse.urlparse(bpe_path_or_url).scheme:
|
| 56 |
+
try:
|
| 57 |
+
with urllib.request.urlopen(bpe_path_or_url) as response:
|
| 58 |
+
file_buf = BytesIO(response.read())
|
| 59 |
+
return Tokenizer(vocab_path=file_buf)
|
| 60 |
+
except Exception as e:
|
| 61 |
+
raise FileNotFoundError(
|
| 62 |
+
f"Failed to download file from url {bpe_path_or_url} with error last: {e}"
|
| 63 |
+
)
|
| 64 |
+
else:
|
| 65 |
+
with open(bpe_path_or_url, "rb") as f:
|
| 66 |
+
file_buf = BytesIO(f.read())
|
| 67 |
+
return Tokenizer(vocab_path=file_buf)
|
starVLA/dinov3/dinov3/eval/text/train_dinotxt.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import gc
|
| 7 |
+
import logging
|
| 8 |
+
from functools import partial
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Callable
|
| 14 |
+
|
| 15 |
+
import dinov3.distributed as distributed
|
| 16 |
+
import torch
|
| 17 |
+
from dinov3.checkpointer import (
|
| 18 |
+
find_latest_checkpoint,
|
| 19 |
+
keep_last_n_checkpoints,
|
| 20 |
+
load_checkpoint,
|
| 21 |
+
save_checkpoint,
|
| 22 |
+
)
|
| 23 |
+
from dinov3.configs import setup_job
|
| 24 |
+
from dinov3.data import SamplerType, make_data_loader, make_dataset
|
| 25 |
+
from dinov3.eval.text.build_dinotxt import build_model_and_tokenizer
|
| 26 |
+
from dinov3.eval.text.clip_loss import memory_efficient_clip_loss
|
| 27 |
+
from dinov3.eval.text.dinotxt_model import DINOTxt, DINOTxtConfig
|
| 28 |
+
from dinov3.eval.text.gram_loss import gram_loss_fn
|
| 29 |
+
from dinov3.logging import MetricLogger, setup_logging
|
| 30 |
+
from dinov3.train.cosine_lr_scheduler import linear_warmup_cosine_decay
|
| 31 |
+
from omegaconf import OmegaConf
|
| 32 |
+
from torch import optim
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger("dinov3")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def unwrap_model(model):
|
| 38 |
+
return getattr(model, "module", model)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test(
|
| 42 |
+
model: DINOTxt,
|
| 43 |
+
iteration: str,
|
| 44 |
+
output_dir: str,
|
| 45 |
+
):
|
| 46 |
+
eval_dir = Path(output_dir) / "eval" / str(iteration)
|
| 47 |
+
if distributed.is_subgroup_main_process():
|
| 48 |
+
eval_dir.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
|
| 50 |
+
ckpt_dir = eval_dir / str("sharded_model_checkpoint")
|
| 51 |
+
save_checkpoint(ckpt_dir, iteration=iteration, model=model)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def apply_learning_rate(optimizer, lr: float):
|
| 55 |
+
for param_group in optimizer.param_groups:
|
| 56 |
+
param_group["lr"] = lr
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def exclude(n: str, p: torch.Tensor) -> bool:
|
| 60 |
+
return p.ndim < 2 or "bn" in n or "ln" in n or "bias" in n or "logit_scale" in n
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def include(n: str, p: torch.Tensor) -> bool:
|
| 64 |
+
return not exclude(n, p)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def train(
|
| 68 |
+
train_dataset,
|
| 69 |
+
model: DINOTxt,
|
| 70 |
+
tokenizer: Callable,
|
| 71 |
+
max_iteration: int,
|
| 72 |
+
warmup_length: int,
|
| 73 |
+
checkpointing_period: int,
|
| 74 |
+
output_dir: str,
|
| 75 |
+
dtype_str: str,
|
| 76 |
+
sampler_type: SamplerType,
|
| 77 |
+
lr_scheduler_type: str,
|
| 78 |
+
lr: float,
|
| 79 |
+
weight_decay: float,
|
| 80 |
+
batch_size: int = 256,
|
| 81 |
+
beta1: float = 0.9,
|
| 82 |
+
beta2: float = 0.99,
|
| 83 |
+
eps: float = 1e-8,
|
| 84 |
+
num_workers: int = 10,
|
| 85 |
+
eval_freq: int = 1000,
|
| 86 |
+
gc_freq: int = 100,
|
| 87 |
+
use_gram_loss: bool = False,
|
| 88 |
+
patch_sampling_rate_for_gram_loss: float = 0.5,
|
| 89 |
+
normalize_patch_tokens_for_gram_loss: bool = False,
|
| 90 |
+
gram_loss_weight: float = 1.0,
|
| 91 |
+
max_checkpoints_to_keep: int = None,
|
| 92 |
+
resume: bool = False,
|
| 93 |
+
seed: int = 11,
|
| 94 |
+
):
|
| 95 |
+
named_parameters = list(model.named_parameters())
|
| 96 |
+
gain_or_bias_params = [
|
| 97 |
+
p for n, p in named_parameters if exclude(n, p) and p.requires_grad
|
| 98 |
+
]
|
| 99 |
+
gain_or_bias_params_names = [
|
| 100 |
+
n for n, p in named_parameters if exclude(n, p) and p.requires_grad
|
| 101 |
+
]
|
| 102 |
+
rest_params = [p for n, p in named_parameters if include(n, p) and p.requires_grad]
|
| 103 |
+
rest_params_names = [
|
| 104 |
+
n for n, p in named_parameters if include(n, p) and p.requires_grad
|
| 105 |
+
]
|
| 106 |
+
logger.info(f"Gain or bias params: {gain_or_bias_params_names}")
|
| 107 |
+
logger.info(f"Rest params: {rest_params_names}")
|
| 108 |
+
logger.info(
|
| 109 |
+
f"Learning rate: {lr}, batch_size_per_gpu: {batch_size}, weight_decay: {weight_decay}"
|
| 110 |
+
)
|
| 111 |
+
optimizer = optim.AdamW(
|
| 112 |
+
[
|
| 113 |
+
{"params": gain_or_bias_params, "weight_decay": 0.0},
|
| 114 |
+
{"params": rest_params, "weight_decay": weight_decay},
|
| 115 |
+
],
|
| 116 |
+
lr=lr,
|
| 117 |
+
betas=(beta1, beta2),
|
| 118 |
+
eps=eps,
|
| 119 |
+
)
|
| 120 |
+
learning_rates = linear_warmup_cosine_decay(
|
| 121 |
+
0, lr, 0, warmup_iterations=warmup_length, total_iterations=max_iteration
|
| 122 |
+
)
|
| 123 |
+
logger.info(
|
| 124 |
+
f"Init lr scheduler: {lr_scheduler_type}, warmup length: {warmup_length}, base_lr: {lr}, max iter: {max_iteration}"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if (
|
| 128 |
+
resume
|
| 129 |
+
and (ckpt_dir := find_latest_checkpoint(os.path.join(output_dir, "ckpt")))
|
| 130 |
+
is not None
|
| 131 |
+
):
|
| 132 |
+
iteration = load_checkpoint(ckpt_dir, model=model, optimizer=optimizer)
|
| 133 |
+
start_iteration = iteration + 1
|
| 134 |
+
del iteration, ckpt_dir
|
| 135 |
+
else:
|
| 136 |
+
logger.info("Initializing from scratch")
|
| 137 |
+
start_iteration = 0
|
| 138 |
+
|
| 139 |
+
def collate_fn(batch):
|
| 140 |
+
images, captions = list(zip(*batch))[:2]
|
| 141 |
+
return torch.stack(images), tokenizer.tokenize(captions)
|
| 142 |
+
|
| 143 |
+
train_data_loader = make_data_loader(
|
| 144 |
+
dataset=train_dataset,
|
| 145 |
+
batch_size=batch_size,
|
| 146 |
+
num_workers=num_workers,
|
| 147 |
+
shuffle=False,
|
| 148 |
+
seed=seed,
|
| 149 |
+
sampler_type=sampler_type,
|
| 150 |
+
sampler_advance=start_iteration,
|
| 151 |
+
drop_last=True,
|
| 152 |
+
persistent_workers=True,
|
| 153 |
+
collate_fn=collate_fn,
|
| 154 |
+
)
|
| 155 |
+
rank = distributed.get_rank()
|
| 156 |
+
world_size = distributed.get_world_size()
|
| 157 |
+
logger.info(
|
| 158 |
+
f"Init loss function: rank: {distributed.get_rank()}, world size: {world_size}"
|
| 159 |
+
)
|
| 160 |
+
clip_loss = partial(memory_efficient_clip_loss, group=torch.distributed.group.WORLD)
|
| 161 |
+
cur_iteration = start_iteration
|
| 162 |
+
logger.info(f"Starting training from iteration {start_iteration}...")
|
| 163 |
+
header = "Training"
|
| 164 |
+
metric_logger = MetricLogger(delimiter=" ")
|
| 165 |
+
gc.disable()
|
| 166 |
+
device_id = rank % torch.cuda.device_count()
|
| 167 |
+
|
| 168 |
+
for batch in metric_logger.log_every(
|
| 169 |
+
train_data_loader,
|
| 170 |
+
10,
|
| 171 |
+
header,
|
| 172 |
+
max_iteration,
|
| 173 |
+
start_iteration,
|
| 174 |
+
):
|
| 175 |
+
images, text_tokens = batch
|
| 176 |
+
images = images.to(device=device_id, non_blocking=True)
|
| 177 |
+
text_tokens = text_tokens.to(device=device_id, non_blocking=True)
|
| 178 |
+
(
|
| 179 |
+
image_embeddings,
|
| 180 |
+
text_embeddings,
|
| 181 |
+
logit_scale,
|
| 182 |
+
patch_tokens,
|
| 183 |
+
backbone_patch_tokens,
|
| 184 |
+
) = model(images, text_tokens)
|
| 185 |
+
contrastive_loss = clip_loss(image_embeddings, text_embeddings, logit_scale)
|
| 186 |
+
total_loss = contrastive_loss
|
| 187 |
+
if use_gram_loss:
|
| 188 |
+
gram_loss = gram_loss_fn(
|
| 189 |
+
patch_tokens,
|
| 190 |
+
backbone_patch_tokens,
|
| 191 |
+
patch_sampling_rate_for_gram_loss,
|
| 192 |
+
normalize_patch_tokens_for_gram_loss,
|
| 193 |
+
)
|
| 194 |
+
total_loss = contrastive_loss + gram_loss_weight * gram_loss
|
| 195 |
+
|
| 196 |
+
if total_loss.isnan():
|
| 197 |
+
msg = f"Loss is NaN at iteration {cur_iteration}, aborting..."
|
| 198 |
+
logger.error(msg)
|
| 199 |
+
raise RuntimeError(msg)
|
| 200 |
+
apply_learning_rate(optimizer=optimizer, lr=learning_rates[cur_iteration])
|
| 201 |
+
optimizer.zero_grad()
|
| 202 |
+
total_loss.backward()
|
| 203 |
+
optimizer.step()
|
| 204 |
+
|
| 205 |
+
# This clamping trick is from OpenCLIP reposistory which MetaCLIP follows. Orginally used in CLIP training.
|
| 206 |
+
# NOTE: we clamp to 4.6052 = ln(100), as in the original paper.
|
| 207 |
+
with torch.no_grad():
|
| 208 |
+
unwrap_model(model).logit_scale.clamp_(0, math.log(100))
|
| 209 |
+
metric_logger.update(contrastive_loss=contrastive_loss.item())
|
| 210 |
+
if use_gram_loss:
|
| 211 |
+
metric_logger.update(gram_loss=gram_loss.item())
|
| 212 |
+
metric_logger.update(lr=optimizer.param_groups[0]["lr"])
|
| 213 |
+
metric_logger.update(logit_scale=logit_scale.item())
|
| 214 |
+
is_last_iteration = (cur_iteration + 1) == max_iteration
|
| 215 |
+
is_ckpt_iteration = (
|
| 216 |
+
(cur_iteration + 1) % checkpointing_period == 0
|
| 217 |
+
) or is_last_iteration
|
| 218 |
+
if is_ckpt_iteration:
|
| 219 |
+
ckpt_dir = Path(output_dir, "ckpt").expanduser()
|
| 220 |
+
save_checkpoint(
|
| 221 |
+
ckpt_dir / str(cur_iteration),
|
| 222 |
+
iteration=cur_iteration,
|
| 223 |
+
model=model,
|
| 224 |
+
optimizer=optimizer,
|
| 225 |
+
)
|
| 226 |
+
if distributed.is_main_process():
|
| 227 |
+
keep_last_n_checkpoints(ckpt_dir, max_checkpoints_to_keep)
|
| 228 |
+
if eval_freq > 0 and (cur_iteration + 1) % eval_freq == 0:
|
| 229 |
+
test(
|
| 230 |
+
model,
|
| 231 |
+
iteration=f"training_{cur_iteration}",
|
| 232 |
+
batch_size=batch_size,
|
| 233 |
+
num_workers=num_workers,
|
| 234 |
+
output_dir=output_dir,
|
| 235 |
+
dtype_str=dtype_str,
|
| 236 |
+
)
|
| 237 |
+
torch.cuda.synchronize()
|
| 238 |
+
if (cur_iteration + 1) % gc_freq == 0:
|
| 239 |
+
logger.info("Garbage collection...")
|
| 240 |
+
gc.collect()
|
| 241 |
+
cur_iteration += 1
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def write_config(
|
| 245 |
+
model_config: DINOTxtConfig, output_dir, name="clip_model_config.yaml"
|
| 246 |
+
):
|
| 247 |
+
logger.info(OmegaConf.to_yaml(model_config))
|
| 248 |
+
saved_cfg_path = os.path.join(output_dir, name)
|
| 249 |
+
with open(saved_cfg_path, "w") as f:
|
| 250 |
+
OmegaConf.save(config=model_config, f=f)
|
| 251 |
+
return saved_cfg_path
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def main(argv=None):
|
| 255 |
+
if argv is None:
|
| 256 |
+
argv = sys.argv[1:]
|
| 257 |
+
args_dict = OmegaConf.to_container(OmegaConf.from_cli(argv))
|
| 258 |
+
logger.info(args_dict)
|
| 259 |
+
config = OmegaConf.load(args_dict["trainer_config_file"])
|
| 260 |
+
logger.info(config)
|
| 261 |
+
if "output_dir" in args_dict:
|
| 262 |
+
config.output_dir = args_dict["--output-dir"]
|
| 263 |
+
setup_job(output_dir=config.output_dir, seed=config.seed)
|
| 264 |
+
setup_logging(output=os.path.join(config.output_dir, "nan_logs"), name="nan_logger")
|
| 265 |
+
logger.info("Trainer config:")
|
| 266 |
+
logger.info(config)
|
| 267 |
+
model_config = DINOTxtConfig(
|
| 268 |
+
embed_dim=config.embed_dim,
|
| 269 |
+
text_backbone_config=config.text_backbone_config,
|
| 270 |
+
vision_backbone_config=config.vision_backbone_config,
|
| 271 |
+
text_backbone_pretrained_weights=config.text_backbone_pretrained_weights,
|
| 272 |
+
vision_backbone_pretrained_weights=config.vision_backbone_pretrained_weights,
|
| 273 |
+
vision_model_train_img_size=config.vision_model_train_img_size,
|
| 274 |
+
vision_model_use_class_token=config.vision_model_use_class_token,
|
| 275 |
+
vision_model_use_patch_tokens=config.vision_model_use_patch_tokens,
|
| 276 |
+
vision_model_num_head_blocks=config.vision_model_num_head_blocks,
|
| 277 |
+
vision_model_head_blocks_drop_path=config.vision_model_head_blocks_drop_path,
|
| 278 |
+
vision_model_use_linear_projection=config.vision_model_use_linear_projection,
|
| 279 |
+
vision_model_patch_tokens_pooler_type=config.vision_model_patch_tokens_pooler_type,
|
| 280 |
+
vision_model_patch_token_layer=config.vision_model_patch_token_layer,
|
| 281 |
+
text_model_freeze_backbone=config.text_model_freeze_backbone,
|
| 282 |
+
text_model_num_head_blocks=config.text_model_num_head_blocks,
|
| 283 |
+
text_model_head_blocks_is_causal=config.text_model_head_blocks_is_causal,
|
| 284 |
+
text_model_head_blocks_drop_prob=config.text_model_head_blocks_drop_prob,
|
| 285 |
+
text_model_tokens_pooler_type=config.text_model_tokens_pooler_type,
|
| 286 |
+
text_model_use_linear_projection=config.text_model_use_linear_projection,
|
| 287 |
+
text_vocab_path_or_url=config.text_vocab_path_or_url,
|
| 288 |
+
init_logit_scale=config.init_logit_scale,
|
| 289 |
+
freeze_logit_scale=config.freeze_logit_scale,
|
| 290 |
+
init_logit_bias=config.init_logit_bias,
|
| 291 |
+
)
|
| 292 |
+
write_config(model_config=model_config, output_dir=config.output_dir)
|
| 293 |
+
model, transform, tokenizer = build_model_and_tokenizer(
|
| 294 |
+
model_config,
|
| 295 |
+
use_fsdp=config.use_fsdp,
|
| 296 |
+
do_compile=config.do_compile,
|
| 297 |
+
use_ac=config.use_ac,
|
| 298 |
+
use_cuda_graphs=config.use_cuda_graphs,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
train_dataset = make_dataset(
|
| 302 |
+
dataset_str=config.train_dataset_str,
|
| 303 |
+
transform=transform,
|
| 304 |
+
)
|
| 305 |
+
sampler_type = (
|
| 306 |
+
SamplerType.SHARDED_INFINITE
|
| 307 |
+
if config.dataset_use_cache
|
| 308 |
+
else SamplerType.INFINITE
|
| 309 |
+
)
|
| 310 |
+
train(
|
| 311 |
+
train_dataset=train_dataset,
|
| 312 |
+
model=model,
|
| 313 |
+
tokenizer=tokenizer,
|
| 314 |
+
max_iteration=config.max_iteration,
|
| 315 |
+
warmup_length=config.warmup_length,
|
| 316 |
+
checkpointing_period=config.checkpointing_period,
|
| 317 |
+
output_dir=config.output_dir,
|
| 318 |
+
dtype_str=config.dtype_str,
|
| 319 |
+
lr_scheduler_type=config.lr_scheduler_type,
|
| 320 |
+
lr=config.lr,
|
| 321 |
+
weight_decay=config.weight_decay,
|
| 322 |
+
batch_size=config.batch_size,
|
| 323 |
+
beta1=config.beta1,
|
| 324 |
+
beta2=config.beta2,
|
| 325 |
+
eps=config.eps,
|
| 326 |
+
sampler_type=sampler_type,
|
| 327 |
+
eval_freq=config.eval_freq,
|
| 328 |
+
gc_freq=config.gc_freq,
|
| 329 |
+
max_checkpoints_to_keep=config.max_checkpoints_to_keep,
|
| 330 |
+
use_gram_loss=config.vision_model_use_gram_loss,
|
| 331 |
+
patch_sampling_rate_for_gram_loss=config.vision_model_patch_sampling_rate_for_gram_loss,
|
| 332 |
+
normalize_patch_tokens_for_gram_loss=config.vision_model_normalize_patch_tokens_for_gram_loss,
|
| 333 |
+
gram_loss_weight=config.vision_model_gram_loss_weight,
|
| 334 |
+
resume=not config.no_resume,
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
if __name__ == "__main__":
|
| 339 |
+
main()
|
starVLA/dinov3/dinov3/eval/text/vision_tower.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from functools import partial
|
| 8 |
+
from typing import Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import nn
|
| 12 |
+
|
| 13 |
+
from dinov3.layers import SelfAttentionBlock, SwiGLUFFN
|
| 14 |
+
from dinov3.models.vision_transformer import init_weights_vit
|
| 15 |
+
from dinov3.utils import named_apply
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("dinov3")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class VisionHead(nn.Module):
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
input_dim: int,
|
| 24 |
+
embed_dim: int,
|
| 25 |
+
num_heads: int,
|
| 26 |
+
num_blocks: int,
|
| 27 |
+
blocks_drop_path: float,
|
| 28 |
+
use_class_token: bool,
|
| 29 |
+
use_patch_tokens: bool,
|
| 30 |
+
use_linear_projection: bool,
|
| 31 |
+
):
|
| 32 |
+
super().__init__()
|
| 33 |
+
block_list = [nn.Identity()]
|
| 34 |
+
self.ln_final = nn.Identity()
|
| 35 |
+
if num_blocks > 0:
|
| 36 |
+
block_list = [
|
| 37 |
+
SelfAttentionBlock(
|
| 38 |
+
input_dim,
|
| 39 |
+
num_heads,
|
| 40 |
+
ffn_layer=partial(SwiGLUFFN, align_to=64),
|
| 41 |
+
init_values=1e-5,
|
| 42 |
+
drop_path=blocks_drop_path,
|
| 43 |
+
)
|
| 44 |
+
for _ in range(num_blocks)
|
| 45 |
+
]
|
| 46 |
+
self.ln_final = nn.LayerNorm(input_dim)
|
| 47 |
+
self.blocks = nn.ModuleList(block_list)
|
| 48 |
+
self.num_blocks = num_blocks
|
| 49 |
+
multiplier = 2 if use_class_token and use_patch_tokens else 1
|
| 50 |
+
self.linear_projection = nn.Identity()
|
| 51 |
+
if multiplier * input_dim != embed_dim or use_linear_projection:
|
| 52 |
+
logger.info(
|
| 53 |
+
f"Vision Tower: Using a linear projection from {input_dim} to {embed_dim}"
|
| 54 |
+
)
|
| 55 |
+
assert embed_dim % multiplier == 0, (
|
| 56 |
+
f"Expects {embed_dim} to be divisible by {multiplier}"
|
| 57 |
+
)
|
| 58 |
+
self.linear_projection = nn.Linear(
|
| 59 |
+
input_dim, embed_dim // multiplier, bias=False
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def init_weights(self):
|
| 63 |
+
if self.num_blocks > 0:
|
| 64 |
+
for i in range(self.num_blocks):
|
| 65 |
+
block = self.blocks[i]
|
| 66 |
+
named_apply(init_weights_vit, block)
|
| 67 |
+
self.ln_final.reset_parameters()
|
| 68 |
+
if isinstance(self.linear_projection, nn.Linear):
|
| 69 |
+
nn.init.normal_(
|
| 70 |
+
self.linear_projection.weight,
|
| 71 |
+
std=self.linear_projection.in_features**-0.5,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def forward(self, image_tokens: torch.Tensor) -> torch.Tensor:
|
| 75 |
+
# FIXME(cijose) ROPE embeddings are not used in DINOv2, refactor to use it in the future
|
| 76 |
+
for block in self.blocks:
|
| 77 |
+
image_tokens = block(image_tokens)
|
| 78 |
+
image_tokens = self.ln_final(image_tokens)
|
| 79 |
+
return self.linear_projection(image_tokens)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class VisionTower(nn.Module):
|
| 83 |
+
def __init__(
|
| 84 |
+
self,
|
| 85 |
+
backbone: nn.Module,
|
| 86 |
+
freeze_backbone: bool,
|
| 87 |
+
embed_dim: int,
|
| 88 |
+
num_head_blocks: int,
|
| 89 |
+
head_blocks_block_drop_path: float,
|
| 90 |
+
use_class_token: bool,
|
| 91 |
+
use_patch_tokens: bool,
|
| 92 |
+
patch_token_layer: int,
|
| 93 |
+
patch_tokens_pooler_type: str,
|
| 94 |
+
use_linear_projection: bool,
|
| 95 |
+
):
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.backbone = backbone
|
| 98 |
+
self.freeze_backbone = freeze_backbone
|
| 99 |
+
self.use_class_token = use_class_token
|
| 100 |
+
self.use_patch_tokens = use_patch_tokens
|
| 101 |
+
self.patch_token_layer = patch_token_layer
|
| 102 |
+
self.patch_tokens_pooler_type = patch_tokens_pooler_type
|
| 103 |
+
self.num_register_tokens = 0
|
| 104 |
+
if hasattr(self.backbone, "num_register_tokens"):
|
| 105 |
+
self.num_register_tokens = self.backbone.num_register_tokens
|
| 106 |
+
elif hasattr(self.backbone, "n_storage_tokens"):
|
| 107 |
+
self.num_register_tokens = self.backbone.n_storage_tokens
|
| 108 |
+
backbone_out_dim = self.backbone.embed_dim
|
| 109 |
+
logger.info(f"Visual backbone embedding dimension: {backbone_out_dim}")
|
| 110 |
+
self.head = VisionHead(
|
| 111 |
+
backbone_out_dim,
|
| 112 |
+
embed_dim,
|
| 113 |
+
self.backbone.num_heads,
|
| 114 |
+
num_head_blocks,
|
| 115 |
+
head_blocks_block_drop_path,
|
| 116 |
+
use_class_token,
|
| 117 |
+
use_patch_tokens,
|
| 118 |
+
use_linear_projection,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
def init_weights(self):
|
| 122 |
+
self.backbone.init_weights()
|
| 123 |
+
self.head.init_weights()
|
| 124 |
+
|
| 125 |
+
def get_backbone_features(
|
| 126 |
+
self, images: torch.Tensor
|
| 127 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 128 |
+
tokens = self.backbone.get_intermediate_layers(
|
| 129 |
+
images,
|
| 130 |
+
n=self.patch_token_layer,
|
| 131 |
+
return_class_token=True,
|
| 132 |
+
return_extra_tokens=True,
|
| 133 |
+
)
|
| 134 |
+
class_token = tokens[-1][1]
|
| 135 |
+
patch_tokens = tokens[0][0]
|
| 136 |
+
register_tokens = tokens[0][2]
|
| 137 |
+
return class_token, patch_tokens, register_tokens
|
| 138 |
+
|
| 139 |
+
def get_class_and_patch_tokens(
|
| 140 |
+
self, images: torch.Tensor
|
| 141 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 142 |
+
class_token, patch_tokens, register_tokens = self.get_backbone_features(images)
|
| 143 |
+
image_tokens = self.head(
|
| 144 |
+
torch.cat([class_token.unsqueeze(1), register_tokens, patch_tokens], dim=1)
|
| 145 |
+
)
|
| 146 |
+
return (
|
| 147 |
+
image_tokens[:, 0],
|
| 148 |
+
image_tokens[:, self.num_register_tokens + 1 :],
|
| 149 |
+
patch_tokens,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def forward(self, images: torch.Tensor) -> torch.Tensor:
|
| 153 |
+
class_token, patch_tokens, backbone_patch_tokens = (
|
| 154 |
+
self.get_class_and_patch_tokens(images)
|
| 155 |
+
)
|
| 156 |
+
features = []
|
| 157 |
+
if self.use_class_token:
|
| 158 |
+
features.append(class_token)
|
| 159 |
+
if self.use_patch_tokens:
|
| 160 |
+
if self.patch_tokens_pooler_type == "mean":
|
| 161 |
+
features.append(torch.mean(patch_tokens, dim=1))
|
| 162 |
+
elif self.patch_tokens_pooler_type == "max":
|
| 163 |
+
features.append(torch.max(patch_tokens, dim=1).values)
|
| 164 |
+
else:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
f"Unknown patch tokens pooler type: {self.patch_tokens_pooler_type}"
|
| 167 |
+
)
|
| 168 |
+
return torch.cat(features, dim=-1), patch_tokens, backbone_patch_tokens
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def build_vision_model(
|
| 172 |
+
embed_dim: int,
|
| 173 |
+
backbone_model_config: str,
|
| 174 |
+
freeze_backbone: bool,
|
| 175 |
+
num_head_blocks: int,
|
| 176 |
+
blocks_drop_path: float,
|
| 177 |
+
use_class_token: bool,
|
| 178 |
+
use_patch_tokens: bool,
|
| 179 |
+
patch_token_layer: int,
|
| 180 |
+
patch_tokens_pooler_type: str,
|
| 181 |
+
use_linear_projection: bool,
|
| 182 |
+
backbone: Optional[nn.Module] = None,
|
| 183 |
+
):
|
| 184 |
+
if backbone is None:
|
| 185 |
+
if backbone_model_config is not None:
|
| 186 |
+
from omegaconf import OmegaConf
|
| 187 |
+
|
| 188 |
+
from dinov3.models import build_model_from_cfg as build_vision_backbone
|
| 189 |
+
|
| 190 |
+
cfg = OmegaConf.load(backbone_model_config)
|
| 191 |
+
backbone, _ = build_vision_backbone(cfg, only_teacher=True)
|
| 192 |
+
else:
|
| 193 |
+
raise RuntimeError(
|
| 194 |
+
"Failed to create, vision backbone, either backbone or backbone_model_config should be not None"
|
| 195 |
+
)
|
| 196 |
+
return VisionTower(
|
| 197 |
+
backbone,
|
| 198 |
+
freeze_backbone,
|
| 199 |
+
embed_dim,
|
| 200 |
+
num_head_blocks,
|
| 201 |
+
blocks_drop_path,
|
| 202 |
+
use_class_token,
|
| 203 |
+
use_patch_tokens,
|
| 204 |
+
patch_token_layer,
|
| 205 |
+
patch_tokens_pooler_type,
|
| 206 |
+
use_linear_projection,
|
| 207 |
+
)
|
starVLA/dinov3/dinov3/eval/utils.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import gc
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
from enum import Enum
|
| 10 |
+
from typing import Any, Dict, List, Optional
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
from torchmetrics import Metric
|
| 16 |
+
|
| 17 |
+
import dinov3.distributed as distributed
|
| 18 |
+
from dinov3.data import DatasetWithEnumeratedTargets, SamplerType, make_data_loader
|
| 19 |
+
from dinov3.eval.accumulators import NoOpAccumulator, ResultsAccumulator
|
| 20 |
+
from dinov3.logging import MetricLogger
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger("dinov3")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class LossType(Enum):
|
| 26 |
+
CROSS_ENTROPY = "cross_entropy"
|
| 27 |
+
BINARY_CROSS_ENTROPY = "binary_cross_entropy"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ModelWithNormalize(torch.nn.Module):
|
| 31 |
+
def __init__(self, model: torch.nn.Module) -> None:
|
| 32 |
+
super().__init__()
|
| 33 |
+
self._model = model
|
| 34 |
+
|
| 35 |
+
def forward(self, samples):
|
| 36 |
+
return nn.functional.normalize(self._model(samples), dim=1, p=2)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ModelWithMultiScale(torch.nn.Module):
|
| 40 |
+
def __init__(self, model: torch.nn.Module, mode: str = "bilinear") -> None:
|
| 41 |
+
super().__init__()
|
| 42 |
+
self._model = model
|
| 43 |
+
self._mode = mode
|
| 44 |
+
|
| 45 |
+
def forward(self, samples):
|
| 46 |
+
output = None
|
| 47 |
+
for scale in (1, 0.5**0.5, 0.5):
|
| 48 |
+
if scale == 1:
|
| 49 |
+
resized_samples = samples.clone()
|
| 50 |
+
else:
|
| 51 |
+
resized_samples = nn.functional.interpolate(
|
| 52 |
+
samples, scale_factor=scale, mode=self._mode, align_corners=False
|
| 53 |
+
)
|
| 54 |
+
scale_output = self._model(resized_samples).clone()
|
| 55 |
+
if output is None:
|
| 56 |
+
output = scale_output
|
| 57 |
+
else:
|
| 58 |
+
output += scale_output
|
| 59 |
+
return output / 3
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def wrap_model(
|
| 63 |
+
model: nn.Module,
|
| 64 |
+
*,
|
| 65 |
+
normalize: bool = True,
|
| 66 |
+
multi_scale: bool = False,
|
| 67 |
+
) -> nn.Module:
|
| 68 |
+
logger.info("multi-scale: {}".format("enabled" if multi_scale else "disabled"))
|
| 69 |
+
if multi_scale:
|
| 70 |
+
model = ModelWithMultiScale(model)
|
| 71 |
+
|
| 72 |
+
logger.info("normalize: {}".format("enabled" if normalize else "disabled"))
|
| 73 |
+
if normalize:
|
| 74 |
+
model = ModelWithNormalize(model)
|
| 75 |
+
return model
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class ModelWithIntermediateLayers(nn.Module):
|
| 79 |
+
def __init__(self, feature_model, n, autocast_ctx, reshape=False, return_class_token=True):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.feature_model = feature_model
|
| 82 |
+
self.feature_model.eval()
|
| 83 |
+
self.n = n # Layer indices (Sequence) or n last layers (int) to take
|
| 84 |
+
self.autocast_ctx = autocast_ctx
|
| 85 |
+
self.reshape = reshape
|
| 86 |
+
self.return_class_token = return_class_token
|
| 87 |
+
|
| 88 |
+
def forward(self, images):
|
| 89 |
+
with torch.inference_mode():
|
| 90 |
+
with self.autocast_ctx():
|
| 91 |
+
features = self.feature_model.get_intermediate_layers(
|
| 92 |
+
images,
|
| 93 |
+
n=self.n,
|
| 94 |
+
reshape=self.reshape,
|
| 95 |
+
return_class_token=self.return_class_token
|
| 96 |
+
)
|
| 97 |
+
return features
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@torch.inference_mode()
|
| 101 |
+
def evaluate(
|
| 102 |
+
model: nn.Module,
|
| 103 |
+
data_loader,
|
| 104 |
+
postprocessors: Dict[str, nn.Module],
|
| 105 |
+
metrics: Dict[str, Metric],
|
| 106 |
+
device: torch.device,
|
| 107 |
+
criterion: Optional[nn.Module] = None,
|
| 108 |
+
accumulate_results: bool = False,
|
| 109 |
+
):
|
| 110 |
+
gc.collect() # Avoids garbage collection errors in DataLoader workers
|
| 111 |
+
model.eval()
|
| 112 |
+
if criterion is not None:
|
| 113 |
+
criterion.eval()
|
| 114 |
+
|
| 115 |
+
for metric in metrics.values():
|
| 116 |
+
metric = metric.to(device)
|
| 117 |
+
|
| 118 |
+
metric_logger = MetricLogger(delimiter=" ")
|
| 119 |
+
header = "Test:"
|
| 120 |
+
|
| 121 |
+
accumulator_class = ResultsAccumulator if accumulate_results else NoOpAccumulator
|
| 122 |
+
accumulators = {k: accumulator_class() for k in postprocessors.keys()}
|
| 123 |
+
|
| 124 |
+
# Dataset needs to be wrapped in fairvit.data.adapters.DatasetWithEnumeratedTargets
|
| 125 |
+
for samples, (index, targets), *_ in metric_logger.log_every(data_loader, 10, header):
|
| 126 |
+
samples, targets, index = samples[index >= 0], targets[index >= 0], index[index >= 0]
|
| 127 |
+
if len(index) == 0:
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
outputs = model(samples.to(device))
|
| 131 |
+
index = index.to(device)
|
| 132 |
+
targets = targets.to(device)
|
| 133 |
+
|
| 134 |
+
if criterion is not None:
|
| 135 |
+
loss = criterion(outputs, targets)
|
| 136 |
+
metric_logger.update(loss=loss.item())
|
| 137 |
+
|
| 138 |
+
for k, metric in metrics.items():
|
| 139 |
+
metric_inputs = postprocessors[k](outputs, targets)
|
| 140 |
+
metric.update(**metric_inputs)
|
| 141 |
+
accumulators[k].update(preds=metric_inputs["preds"], target=metric_inputs["target"], index=index)
|
| 142 |
+
|
| 143 |
+
metric_logger.synchronize_between_processes()
|
| 144 |
+
logger.info(f"Averaged stats: {metric_logger}")
|
| 145 |
+
stats = {k: metric.compute() for k, metric in metrics.items()}
|
| 146 |
+
metric_logger_stats = {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
| 147 |
+
|
| 148 |
+
# accumulator.accumulate() returns None for the NoOpAccumulator
|
| 149 |
+
accumulated_results = {k: accumulator.accumulate() for k, accumulator in accumulators.items()}
|
| 150 |
+
|
| 151 |
+
return metric_logger_stats, stats, accumulated_results
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def all_gather_and_flatten(tensor_rank):
|
| 155 |
+
tensor_all_ranks = torch.empty(
|
| 156 |
+
distributed.get_world_size(),
|
| 157 |
+
*tensor_rank.shape,
|
| 158 |
+
dtype=tensor_rank.dtype,
|
| 159 |
+
device=tensor_rank.device,
|
| 160 |
+
)
|
| 161 |
+
tensor_list = list(tensor_all_ranks.unbind(0))
|
| 162 |
+
torch.distributed.all_gather(tensor_list, tensor_rank.contiguous())
|
| 163 |
+
return tensor_all_ranks.flatten(end_dim=1)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def extract_features(model, dataset, batch_size, num_workers, gather_on_cpu=False):
|
| 167 |
+
dataset_with_enumerated_targets = DatasetWithEnumeratedTargets(dataset)
|
| 168 |
+
sample_count = len(dataset_with_enumerated_targets)
|
| 169 |
+
data_loader = make_data_loader(
|
| 170 |
+
dataset=dataset_with_enumerated_targets,
|
| 171 |
+
batch_size=batch_size,
|
| 172 |
+
num_workers=num_workers,
|
| 173 |
+
sampler_type=SamplerType.DISTRIBUTED,
|
| 174 |
+
drop_last=False,
|
| 175 |
+
shuffle=False,
|
| 176 |
+
)
|
| 177 |
+
return extract_features_with_dataloader(model, data_loader, sample_count, gather_on_cpu)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@torch.inference_mode()
|
| 181 |
+
def extract_features_with_dataloader(model, data_loader, sample_count, gather_on_cpu=False):
|
| 182 |
+
gather_device = torch.device("cpu") if gather_on_cpu else torch.device("cuda")
|
| 183 |
+
metric_logger = MetricLogger(delimiter=" ")
|
| 184 |
+
features, all_labels = None, None
|
| 185 |
+
for samples, (index, labels_rank) in metric_logger.log_every(data_loader, 10):
|
| 186 |
+
samples = samples.cuda(non_blocking=True)
|
| 187 |
+
labels_rank = labels_rank.cuda(non_blocking=True)
|
| 188 |
+
index = index.cuda(non_blocking=True)
|
| 189 |
+
features_rank = model(samples).float()
|
| 190 |
+
|
| 191 |
+
# init storage feature matrix
|
| 192 |
+
if features is None:
|
| 193 |
+
features = torch.zeros(sample_count, features_rank.shape[-1], device=gather_device)
|
| 194 |
+
labels_shape = list(labels_rank.shape)
|
| 195 |
+
labels_shape[0] = sample_count
|
| 196 |
+
all_labels = torch.full(labels_shape, fill_value=-1, device=gather_device)
|
| 197 |
+
logger.info(f"Storing features into tensor of shape {features.shape}")
|
| 198 |
+
|
| 199 |
+
# share indexes, features and labels between processes
|
| 200 |
+
index_all = all_gather_and_flatten(index).to(gather_device)
|
| 201 |
+
features_all_ranks = all_gather_and_flatten(features_rank).to(gather_device)
|
| 202 |
+
labels_all_ranks = all_gather_and_flatten(labels_rank).to(gather_device)
|
| 203 |
+
|
| 204 |
+
# update storage feature matrix
|
| 205 |
+
if len(index_all) > 0:
|
| 206 |
+
features.index_copy_(0, index_all, features_all_ranks)
|
| 207 |
+
all_labels.index_copy_(0, index_all, labels_all_ranks)
|
| 208 |
+
|
| 209 |
+
logger.info(f"Features Shape {features.shape}")
|
| 210 |
+
logger.info(f"Labels Shape {all_labels.shape}")
|
| 211 |
+
|
| 212 |
+
return features, all_labels
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def save_features_dict(features_dict: Dict[str, torch.Tensor], path: str) -> None:
|
| 216 |
+
logger.info(f'saving features to "{path}"')
|
| 217 |
+
|
| 218 |
+
for key, value in features_dict.items():
|
| 219 |
+
assert isinstance(key, str)
|
| 220 |
+
assert isinstance(value, torch.Tensor)
|
| 221 |
+
|
| 222 |
+
_, ext = os.path.splitext(path)
|
| 223 |
+
if ext == ".pt":
|
| 224 |
+
torch.save(features_dict, path)
|
| 225 |
+
elif ext == ".npy":
|
| 226 |
+
numpy_features_dict = { # Convert to NumPy arrays (if possible)
|
| 227 |
+
key: value.cpu().numpy() for key, value in features_dict.items()
|
| 228 |
+
}
|
| 229 |
+
np.save(path, numpy_features_dict, allow_pickle=True)
|
| 230 |
+
else:
|
| 231 |
+
raise ValueError(f'Unsupported features dict extension "{ext}"')
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def load_features_dict(path: str) -> Dict[str, torch.Tensor]:
|
| 235 |
+
logger.info(f'loading features from "{path}"')
|
| 236 |
+
|
| 237 |
+
_, ext = os.path.splitext(path)
|
| 238 |
+
if ext == ".pt":
|
| 239 |
+
features_dict = torch.load(path)
|
| 240 |
+
elif ext == ".npy":
|
| 241 |
+
numpy_features_dict = np.load(path, allow_pickle=True).item()
|
| 242 |
+
features_dict = {key: torch.from_numpy(value) for key, value in numpy_features_dict.items()}
|
| 243 |
+
else:
|
| 244 |
+
raise ValueError(f'Unsupported features dict extension "{ext}"')
|
| 245 |
+
|
| 246 |
+
for key, value in features_dict.items():
|
| 247 |
+
assert isinstance(key, str)
|
| 248 |
+
assert isinstance(value, torch.Tensor)
|
| 249 |
+
|
| 250 |
+
return features_dict
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def average_metrics(eval_metrics_dict: dict[Any, dict[str, torch.Tensor]], ignore_keys: List[str] = []):
|
| 254 |
+
"""
|
| 255 |
+
Function that computes the average and the std on a metrics dict.
|
| 256 |
+
A linear evaluation dictionary contains "best_classifier",
|
| 257 |
+
so this specific key is removed for computing aggregated metrics.
|
| 258 |
+
"""
|
| 259 |
+
output_metrics_dict = {}
|
| 260 |
+
metrics = [metric for metric in eval_metrics_dict[0].keys() if metric not in ignore_keys]
|
| 261 |
+
for metric in metrics:
|
| 262 |
+
stats_tensor = torch.tensor([stat[metric] for stat in eval_metrics_dict.values()])
|
| 263 |
+
output_metrics_dict[metric + "_mean"] = stats_tensor.mean().item()
|
| 264 |
+
output_metrics_dict[metric + "_std"] = torch.std(stats_tensor).item()
|
| 265 |
+
|
| 266 |
+
return output_metrics_dict
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def save_results(
|
| 270 |
+
preds: torch.Tensor,
|
| 271 |
+
target: torch.Tensor,
|
| 272 |
+
output_dir: str,
|
| 273 |
+
filename_suffix: Optional[str] = None,
|
| 274 |
+
) -> None:
|
| 275 |
+
"""
|
| 276 |
+
Helper to save predictions from a model and their associated targets, aligned by their index
|
| 277 |
+
"""
|
| 278 |
+
filename_suffix = "" if filename_suffix is None else f"_{filename_suffix}"
|
| 279 |
+
preds_filename = f"preds{filename_suffix}.npy"
|
| 280 |
+
target_filename = f"target{filename_suffix}.npy"
|
| 281 |
+
preds_path = os.path.join(output_dir, preds_filename)
|
| 282 |
+
target_path = os.path.join(output_dir, target_filename)
|
| 283 |
+
logger.info(f"Saving to {preds_path}")
|
| 284 |
+
np.save(preds_path, preds.cpu().numpy())
|
| 285 |
+
logger.info(f"Saving to {target_path}")
|
| 286 |
+
np.save(target_path, target.cpu().numpy())
|
starVLA/dinov3/dinov3/fsdp/__init__.py
ADDED
|
File without changes
|
starVLA/dinov3/dinov3/fsdp/ac_compile_parallelize.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from functools import partial
|
| 8 |
+
from typing import Any, Dict, List
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.distributed as dist
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
from torch.distributed._composable.fsdp import MixedPrecisionPolicy, fully_shard
|
| 14 |
+
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
|
| 15 |
+
from torch.distributed.fsdp import register_fsdp_forward_method
|
| 16 |
+
from torch.distributed.fsdp._fully_shard._fsdp_state import FSDPState
|
| 17 |
+
from torch.utils.checkpoint import create_selective_checkpoint_contexts
|
| 18 |
+
|
| 19 |
+
from dinov3.utils import utils
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger("dinov3")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_activation_checkpoint_wrapper(cfg):
|
| 26 |
+
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
|
| 27 |
+
|
| 28 |
+
if cfg.train.checkpointing_full:
|
| 29 |
+
_checkpointing_wrapper = checkpoint_wrapper
|
| 30 |
+
logger.info("using selective checkpointing on backbone with full checkpointing policy")
|
| 31 |
+
else:
|
| 32 |
+
_save_list = [
|
| 33 |
+
# mm
|
| 34 |
+
torch.ops.aten.mm.default,
|
| 35 |
+
torch.ops.aten._scaled_mm.default,
|
| 36 |
+
# attentions
|
| 37 |
+
torch.ops.aten._scaled_dot_product_efficient_attention.default,
|
| 38 |
+
torch.ops.aten._scaled_dot_product_flash_attention.default,
|
| 39 |
+
torch.ops._c10d_functional.reduce_scatter_tensor.default,
|
| 40 |
+
]
|
| 41 |
+
_checkpointing_wrapper = partial(
|
| 42 |
+
checkpoint_wrapper,
|
| 43 |
+
context_fn=partial(create_selective_checkpoint_contexts, _save_list),
|
| 44 |
+
preserve_rng_state=True,
|
| 45 |
+
)
|
| 46 |
+
logger.info("using selective checkpointing on backbone with selective policy")
|
| 47 |
+
return _checkpointing_wrapper
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def activation_checkpoint_convnext(cfg, model: nn.Module):
|
| 51 |
+
_checkpointing_wrapper = get_activation_checkpoint_wrapper(cfg)
|
| 52 |
+
for stage_id, stage in enumerate(model.stages):
|
| 53 |
+
for block_id, block in enumerate(stage):
|
| 54 |
+
model.stages[stage_id][block_id] = _checkpointing_wrapper(block)
|
| 55 |
+
for dsl_id, dsl in enumerate(model.downsample_layers):
|
| 56 |
+
model.downsample_layers[dsl_id] = _checkpointing_wrapper(dsl)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def activation_checkpoint_transformer(cfg, model: nn.Module):
|
| 60 |
+
_checkpointing_wrapper = get_activation_checkpoint_wrapper(cfg)
|
| 61 |
+
for block_id, b in enumerate(model.blocks):
|
| 62 |
+
model.blocks[block_id] = _checkpointing_wrapper(b)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def wrap_compile_block(module: nn.Module, use_cuda_graphs: bool, is_backbone_block: bool) -> nn.Module:
|
| 66 |
+
if use_cuda_graphs and is_backbone_block:
|
| 67 |
+
module.compile(fullgraph=True, dynamic=False, options={"triton.cudagraphs": True})
|
| 68 |
+
else:
|
| 69 |
+
module.compile()
|
| 70 |
+
return module
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def compile_convnext(cfg, model: nn.Module):
|
| 74 |
+
assert isinstance(model.stages, nn.ModuleList)
|
| 75 |
+
# Compile at stage level
|
| 76 |
+
for stage_id, stage in enumerate(model.stages):
|
| 77 |
+
model.stages[stage_id] = wrap_compile_block(stage, cfg.train.cudagraphs, is_backbone_block=False)
|
| 78 |
+
assert isinstance(model.downsample_layers, nn.ModuleList)
|
| 79 |
+
for dsl_id, dsl in enumerate(model.downsample_layers):
|
| 80 |
+
model.downsample_layers[dsl_id] = wrap_compile_block(dsl, cfg.train.cudagraphs, is_backbone_block=False)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def compile_transformer(cfg, model: nn.Module):
|
| 84 |
+
assert isinstance(model.blocks, nn.ModuleList)
|
| 85 |
+
for block_id, block in enumerate(model.blocks):
|
| 86 |
+
model.blocks[block_id] = wrap_compile_block(block, cfg.train.cudagraphs, is_backbone_block=True)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def fsdp_convnext(fsdp_config: Dict[str, Any], model: nn.Module):
|
| 90 |
+
stages = model.stages
|
| 91 |
+
assert isinstance(stages, nn.ModuleList)
|
| 92 |
+
# FSDP wrap at stage level
|
| 93 |
+
for stage_id, stage in enumerate(stages):
|
| 94 |
+
stage_reshard: int | bool = True
|
| 95 |
+
stages[stage_id] = fully_shard(stage, **fsdp_config, reshard_after_forward=stage_reshard)
|
| 96 |
+
downsample_layers = model.downsample_layers
|
| 97 |
+
assert isinstance(downsample_layers, nn.ModuleList)
|
| 98 |
+
for dsl_id, dsl in enumerate(downsample_layers):
|
| 99 |
+
dsl_reshard: int | bool = True
|
| 100 |
+
downsample_layers[dsl_id] = fully_shard(dsl, **fsdp_config, reshard_after_forward=dsl_reshard)
|
| 101 |
+
dsl: FSDPState
|
| 102 |
+
stage: FSDPState
|
| 103 |
+
for dsl, stage in zip(downsample_layers, stages):
|
| 104 |
+
dsl.set_modules_to_forward_prefetch([stage])
|
| 105 |
+
stage.set_modules_to_backward_prefetch([dsl])
|
| 106 |
+
fully_shard(model, **fsdp_config, reshard_after_forward=True)
|
| 107 |
+
register_fsdp_forward_method(model, "get_intermediate_layers")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def fsdp_transformer(fsdp_config: Dict[str, Any], model: nn.Module):
|
| 111 |
+
# Backbone - FSDP every block
|
| 112 |
+
blocks = model.blocks
|
| 113 |
+
assert isinstance(blocks, nn.ModuleList)
|
| 114 |
+
for block_id, block in enumerate(blocks):
|
| 115 |
+
block_reshard: int | bool = True
|
| 116 |
+
blocks[block_id] = fully_shard(block, **fsdp_config, reshard_after_forward=block_reshard)
|
| 117 |
+
prev_block: FSDPState
|
| 118 |
+
next_block: FSDPState
|
| 119 |
+
for prev_block, next_block in zip(blocks, blocks[1:]):
|
| 120 |
+
prev_block.set_modules_to_forward_prefetch([next_block])
|
| 121 |
+
next_block.set_modules_to_backward_prefetch([prev_block])
|
| 122 |
+
fully_shard(model, **fsdp_config, reshard_after_forward=True)
|
| 123 |
+
register_fsdp_forward_method(model, "get_intermediate_layers")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def ac_compile_parallelize(
|
| 127 |
+
trained_model: nn.ModuleDict,
|
| 128 |
+
inference_only_models: List[nn.ModuleDict],
|
| 129 |
+
cfg: Any,
|
| 130 |
+
trained_model_process_group: dist.ProcessGroup | None = None,
|
| 131 |
+
inference_only_models_process_groups: List[dist.ProcessGroup] | None = None,
|
| 132 |
+
) -> None:
|
| 133 |
+
"""
|
| 134 |
+
Order of the wrappers:
|
| 135 |
+
1/ Activation checkpointing on blocks
|
| 136 |
+
2/ Compile blocks
|
| 137 |
+
3/ FSDP blocks + global model
|
| 138 |
+
"""
|
| 139 |
+
assert (
|
| 140 |
+
isinstance(trained_model, nn.ModuleDict) and "backbone" in trained_model.keys()
|
| 141 |
+
), f"{trained_model} does not contain a backbone?"
|
| 142 |
+
logger.info("DISTRIBUTED FSDP -- preparing model for distributed training")
|
| 143 |
+
if utils.has_batchnorms(trained_model):
|
| 144 |
+
raise NotImplementedError
|
| 145 |
+
|
| 146 |
+
from dinov3.models.convnext import ConvNeXt
|
| 147 |
+
from dinov3.models.vision_transformer import DinoVisionTransformer
|
| 148 |
+
|
| 149 |
+
# FSDP utils for each architecture type
|
| 150 |
+
ARCH_TYPE_MAP = {
|
| 151 |
+
ConvNeXt: dict(
|
| 152 |
+
compile_fn=compile_convnext,
|
| 153 |
+
fsdp_fn=fsdp_convnext,
|
| 154 |
+
activation_checkpointing_fn=activation_checkpoint_convnext,
|
| 155 |
+
),
|
| 156 |
+
DinoVisionTransformer: dict(
|
| 157 |
+
compile_fn=compile_transformer,
|
| 158 |
+
fsdp_fn=fsdp_transformer,
|
| 159 |
+
activation_checkpointing_fn=activation_checkpoint_transformer,
|
| 160 |
+
),
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
# 1/ AC on blocks
|
| 164 |
+
if cfg.train.checkpointing:
|
| 165 |
+
ARCH_TYPE_MAP[type(trained_model.backbone)]["activation_checkpointing_fn"](cfg, trained_model["backbone"])
|
| 166 |
+
# 2/ Compile blocks
|
| 167 |
+
all_models = [trained_model] + inference_only_models
|
| 168 |
+
if trained_model_process_group is None and inference_only_models_process_groups is None:
|
| 169 |
+
all_pgs = [None] * len(all_models)
|
| 170 |
+
elif trained_model_process_group is None:
|
| 171 |
+
all_pgs = [None] + inference_only_models_process_groups
|
| 172 |
+
elif inference_only_models_process_groups is None:
|
| 173 |
+
all_pgs = [trained_model_process_group] + [None] * len(inference_only_models_process_groups)
|
| 174 |
+
else:
|
| 175 |
+
all_pgs = [trained_model_process_group] + inference_only_models_process_groups
|
| 176 |
+
if cfg.train.compile:
|
| 177 |
+
for model in all_models:
|
| 178 |
+
for k in model.keys():
|
| 179 |
+
if k == "backbone":
|
| 180 |
+
ARCH_TYPE_MAP[type(model[k])]["compile_fn"](cfg, model[k])
|
| 181 |
+
else:
|
| 182 |
+
model[k] = wrap_compile_block(model[k], use_cuda_graphs=False, is_backbone_block=False)
|
| 183 |
+
DTYPE_MAP = {
|
| 184 |
+
"fp16": torch.float16,
|
| 185 |
+
"bf16": torch.bfloat16,
|
| 186 |
+
"fp32": torch.float32,
|
| 187 |
+
}
|
| 188 |
+
mp_policy = MixedPrecisionPolicy(
|
| 189 |
+
param_dtype=DTYPE_MAP[cfg.compute_precision.param_dtype],
|
| 190 |
+
reduce_dtype=DTYPE_MAP[cfg.compute_precision.reduce_dtype],
|
| 191 |
+
)
|
| 192 |
+
for model, pg in zip(all_models, all_pgs):
|
| 193 |
+
if pg is None:
|
| 194 |
+
world_mesh = init_device_mesh(
|
| 195 |
+
"cuda",
|
| 196 |
+
mesh_shape=(dist.get_world_size(),),
|
| 197 |
+
mesh_dim_names=("dp",),
|
| 198 |
+
)
|
| 199 |
+
else:
|
| 200 |
+
world_mesh = DeviceMesh.from_group(pg, "cuda")
|
| 201 |
+
fsdp_config = {"mesh": world_mesh, "mp_policy": mp_policy}
|
| 202 |
+
for k in model.keys():
|
| 203 |
+
if k == "backbone":
|
| 204 |
+
ARCH_TYPE_MAP[type(model[k])]["fsdp_fn"](fsdp_config, model[k])
|
| 205 |
+
else:
|
| 206 |
+
model[k] = fully_shard(model[k], **fsdp_config, reshard_after_forward=True)
|
| 207 |
+
|
| 208 |
+
# 4/ Move to `cuda` device
|
| 209 |
+
for model in all_models:
|
| 210 |
+
model.to_empty(device="cuda")
|
| 211 |
+
|
| 212 |
+
# 5/ FSDP2: Reshard immediately after forward for inference-only models
|
| 213 |
+
for model in inference_only_models:
|
| 214 |
+
for k in model.keys():
|
| 215 |
+
fsdp_state: FSDPState = model[k]._get_fsdp_state()
|
| 216 |
+
if not fsdp_state._fsdp_param_group:
|
| 217 |
+
continue
|
| 218 |
+
mi = fsdp_state._fsdp_param_group.post_forward_mesh_info
|
| 219 |
+
fsdp_state._lazy_init()
|
| 220 |
+
fsdp_state._fsdp_param_group.post_forward_mesh_info = mi
|
starVLA/dinov3/dinov3/hub/__init__.py
ADDED
|
File without changes
|
starVLA/dinov3/dinov3/hub/backbones.py
ADDED
|
@@ -0,0 +1,612 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from enum import Enum
|
| 8 |
+
from typing import List, Optional, Union
|
| 9 |
+
from urllib.parse import urlparse
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Weights(Enum):
|
| 16 |
+
LVD1689M = "LVD1689M"
|
| 17 |
+
SAT493M = "SAT493M"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def is_url(path: str) -> bool:
|
| 21 |
+
parsed = urlparse(path)
|
| 22 |
+
return parsed.scheme in ("https", "file")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def convert_path_or_url_to_url(path: str) -> str:
|
| 26 |
+
if is_url(path):
|
| 27 |
+
return path
|
| 28 |
+
return Path(path).expanduser().resolve().as_uri()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _make_dinov3_vit_model_arch(
|
| 32 |
+
*,
|
| 33 |
+
patch_size: int = 16,
|
| 34 |
+
compact_arch_name: str = "vitb",
|
| 35 |
+
):
|
| 36 |
+
if "plus" in compact_arch_name:
|
| 37 |
+
model_arch = compact_arch_name.replace("plus", f"{patch_size}plus")
|
| 38 |
+
else:
|
| 39 |
+
model_arch = f"{compact_arch_name}{patch_size}"
|
| 40 |
+
return model_arch
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _make_dinov3_vit_model_url(
|
| 44 |
+
*,
|
| 45 |
+
patch_size: int = 16,
|
| 46 |
+
compact_arch_name: str = "vitb",
|
| 47 |
+
version: Optional[str] = None,
|
| 48 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 49 |
+
hash: Optional[str] = None,
|
| 50 |
+
):
|
| 51 |
+
model_name = "dinov3"
|
| 52 |
+
model_arch = _make_dinov3_vit_model_arch(patch_size=patch_size, compact_arch_name=compact_arch_name)
|
| 53 |
+
version_suffix = f"_{version}" if version else ""
|
| 54 |
+
weights_name = weights.value.lower()
|
| 55 |
+
hash_suffix = f"-{hash}" if hash else ""
|
| 56 |
+
model_dir = f"{model_name}_{model_arch}"
|
| 57 |
+
model_filename = f"{model_name}_{model_arch}_pretrain_{weights_name}{version_suffix}{hash_suffix}.pth"
|
| 58 |
+
return os.path.join(_DINOV3_BASE_URL, model_dir, model_filename)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _make_dinov3_vit(
|
| 62 |
+
*,
|
| 63 |
+
img_size: int = 224,
|
| 64 |
+
patch_size: int = 16,
|
| 65 |
+
in_chans: int = 3,
|
| 66 |
+
compact_arch_name: str = "vitb",
|
| 67 |
+
pos_embed_rope_base: float = 100.0,
|
| 68 |
+
pos_embed_rope_min_period: float | None = None,
|
| 69 |
+
pos_embed_rope_max_period: float | None = None,
|
| 70 |
+
pos_embed_rope_normalize_coords: str = "separate",
|
| 71 |
+
pos_embed_rope_shift_coords: float | None = None,
|
| 72 |
+
pos_embed_rope_jitter_coords: float | None = None,
|
| 73 |
+
pos_embed_rope_rescale_coords: float | None = None,
|
| 74 |
+
pos_embed_rope_dtype: str = "fp32",
|
| 75 |
+
embed_dim: int = 768,
|
| 76 |
+
depth: int = 12,
|
| 77 |
+
num_heads: int = 12,
|
| 78 |
+
ffn_ratio: float = 4.0,
|
| 79 |
+
qkv_bias: bool = True,
|
| 80 |
+
drop_path_rate: float = 0.0,
|
| 81 |
+
layerscale_init: float | None = None,
|
| 82 |
+
norm_layer: str = "layernorm",
|
| 83 |
+
ffn_layer: str = "mlp",
|
| 84 |
+
ffn_bias: bool = True,
|
| 85 |
+
proj_bias: bool = True,
|
| 86 |
+
n_storage_tokens: int = 0,
|
| 87 |
+
mask_k_bias: bool = False,
|
| 88 |
+
pretrained: bool = True,
|
| 89 |
+
version: Optional[str] = None,
|
| 90 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 91 |
+
hash: Optional[str] = None,
|
| 92 |
+
check_hash: bool = False,
|
| 93 |
+
**kwargs,
|
| 94 |
+
):
|
| 95 |
+
from ..models.vision_transformer import DinoVisionTransformer
|
| 96 |
+
|
| 97 |
+
vit_kwargs = dict(
|
| 98 |
+
img_size=img_size,
|
| 99 |
+
patch_size=patch_size,
|
| 100 |
+
in_chans=in_chans,
|
| 101 |
+
pos_embed_rope_base=pos_embed_rope_base,
|
| 102 |
+
pos_embed_rope_min_period=pos_embed_rope_min_period,
|
| 103 |
+
pos_embed_rope_max_period=pos_embed_rope_max_period,
|
| 104 |
+
pos_embed_rope_normalize_coords=pos_embed_rope_normalize_coords,
|
| 105 |
+
pos_embed_rope_shift_coords=pos_embed_rope_shift_coords,
|
| 106 |
+
pos_embed_rope_jitter_coords=pos_embed_rope_jitter_coords,
|
| 107 |
+
pos_embed_rope_rescale_coords=pos_embed_rope_rescale_coords,
|
| 108 |
+
pos_embed_rope_dtype=pos_embed_rope_dtype,
|
| 109 |
+
embed_dim=embed_dim,
|
| 110 |
+
depth=depth,
|
| 111 |
+
num_heads=num_heads,
|
| 112 |
+
ffn_ratio=ffn_ratio,
|
| 113 |
+
qkv_bias=qkv_bias,
|
| 114 |
+
drop_path_rate=drop_path_rate,
|
| 115 |
+
layerscale_init=layerscale_init,
|
| 116 |
+
norm_layer=norm_layer,
|
| 117 |
+
ffn_layer=ffn_layer,
|
| 118 |
+
ffn_bias=ffn_bias,
|
| 119 |
+
proj_bias=proj_bias,
|
| 120 |
+
n_storage_tokens=n_storage_tokens,
|
| 121 |
+
mask_k_bias=mask_k_bias,
|
| 122 |
+
)
|
| 123 |
+
vit_kwargs.update(**kwargs)
|
| 124 |
+
model = DinoVisionTransformer(**vit_kwargs)
|
| 125 |
+
if pretrained:
|
| 126 |
+
if type(weights) is Weights and weights not in {Weights.LVD1689M, Weights.SAT493M}:
|
| 127 |
+
raise ValueError(f"Unsupported weights for the backbone: {weights}")
|
| 128 |
+
elif type(weights) is Weights:
|
| 129 |
+
url = _make_dinov3_vit_model_url(
|
| 130 |
+
patch_size=patch_size,
|
| 131 |
+
compact_arch_name=compact_arch_name,
|
| 132 |
+
version=version,
|
| 133 |
+
weights=weights,
|
| 134 |
+
hash=hash,
|
| 135 |
+
)
|
| 136 |
+
else:
|
| 137 |
+
url = convert_path_or_url_to_url(weights)
|
| 138 |
+
state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)
|
| 139 |
+
model.load_state_dict(state_dict, strict=True)
|
| 140 |
+
else:
|
| 141 |
+
model.init_weights()
|
| 142 |
+
return model
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _make_dinov3_convnext_model_url(
|
| 146 |
+
*,
|
| 147 |
+
compact_arch_name: str = "convnext_base",
|
| 148 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 149 |
+
hash: Optional[str] = None,
|
| 150 |
+
):
|
| 151 |
+
model_name = "dinov3"
|
| 152 |
+
weights_name = weights.value.lower()
|
| 153 |
+
hash_suffix = f"-{hash}" if hash else ""
|
| 154 |
+
|
| 155 |
+
model_dir = f"{model_name}_{compact_arch_name}"
|
| 156 |
+
model_filename = f"{model_name}_{compact_arch_name}_pretrain_{weights_name}{hash_suffix}.pth"
|
| 157 |
+
return os.path.join(_DINOV3_BASE_URL, model_dir, model_filename)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _make_dinov3_convnext(
|
| 161 |
+
in_chans: int = 3,
|
| 162 |
+
depths: List[int] = [3, 3, 27, 3],
|
| 163 |
+
dims: List[int] = [128, 256, 512, 1024],
|
| 164 |
+
compact_arch_name: str = "convnext_base",
|
| 165 |
+
drop_path_rate: float = 0.0,
|
| 166 |
+
layer_scale_init_value: float = 1e-6,
|
| 167 |
+
pretrained: bool = True,
|
| 168 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 169 |
+
hash: Optional[str] = None,
|
| 170 |
+
**kwargs,
|
| 171 |
+
):
|
| 172 |
+
from ..models.convnext import ConvNeXt
|
| 173 |
+
|
| 174 |
+
model_kwargs = dict(
|
| 175 |
+
in_chans=in_chans,
|
| 176 |
+
depths=depths,
|
| 177 |
+
dims=dims,
|
| 178 |
+
drop_path_rate=drop_path_rate,
|
| 179 |
+
layer_scale_init_value=layer_scale_init_value,
|
| 180 |
+
)
|
| 181 |
+
model_kwargs.update(**kwargs)
|
| 182 |
+
model = ConvNeXt(**model_kwargs)
|
| 183 |
+
if pretrained:
|
| 184 |
+
if type(weights) is Weights and weights not in {Weights.LVD1689M, Weights.SAT493M}:
|
| 185 |
+
raise ValueError(f"Unsupported weights for the backbone: {weights}")
|
| 186 |
+
elif type(weights) is Weights:
|
| 187 |
+
url = _make_dinov3_convnext_model_url(
|
| 188 |
+
compact_arch_name=compact_arch_name,
|
| 189 |
+
weights=weights,
|
| 190 |
+
hash=hash,
|
| 191 |
+
)
|
| 192 |
+
else:
|
| 193 |
+
url = convert_path_or_url_to_url(weights)
|
| 194 |
+
state_dict = _safe_load_state_dict_from_url(url, map_location="cpu")
|
| 195 |
+
model.load_state_dict(state_dict, strict=True)
|
| 196 |
+
return model
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def dinov3_vits16(
|
| 200 |
+
*,
|
| 201 |
+
pretrained: bool = True,
|
| 202 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 203 |
+
check_hash: bool = False,
|
| 204 |
+
**kwargs,
|
| 205 |
+
):
|
| 206 |
+
if "hash" not in kwargs:
|
| 207 |
+
kwargs["hash"] = "08c60483"
|
| 208 |
+
kwargs["version"] = None
|
| 209 |
+
return _make_dinov3_vit(
|
| 210 |
+
img_size=224,
|
| 211 |
+
patch_size=16,
|
| 212 |
+
in_chans=3,
|
| 213 |
+
pos_embed_rope_base=100,
|
| 214 |
+
pos_embed_rope_normalize_coords="separate",
|
| 215 |
+
pos_embed_rope_rescale_coords=2,
|
| 216 |
+
pos_embed_rope_dtype="fp32",
|
| 217 |
+
embed_dim=384,
|
| 218 |
+
depth=12,
|
| 219 |
+
num_heads=6,
|
| 220 |
+
ffn_ratio=4,
|
| 221 |
+
qkv_bias=True,
|
| 222 |
+
drop_path_rate=0.0,
|
| 223 |
+
layerscale_init=1.0e-05,
|
| 224 |
+
norm_layer="layernormbf16",
|
| 225 |
+
ffn_layer="mlp",
|
| 226 |
+
ffn_bias=True,
|
| 227 |
+
proj_bias=True,
|
| 228 |
+
n_storage_tokens=4,
|
| 229 |
+
mask_k_bias=True,
|
| 230 |
+
pretrained=pretrained,
|
| 231 |
+
weights=weights,
|
| 232 |
+
compact_arch_name="vits",
|
| 233 |
+
check_hash=check_hash,
|
| 234 |
+
**kwargs,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def dinov3_vits16plus(
|
| 239 |
+
*,
|
| 240 |
+
pretrained: bool = True,
|
| 241 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 242 |
+
check_hash: bool = False,
|
| 243 |
+
**kwargs,
|
| 244 |
+
):
|
| 245 |
+
if "hash" not in kwargs:
|
| 246 |
+
kwargs["hash"] = "4057cbaa"
|
| 247 |
+
kwargs["version"] = None
|
| 248 |
+
return _make_dinov3_vit(
|
| 249 |
+
img_size=224,
|
| 250 |
+
patch_size=16,
|
| 251 |
+
in_chans=3,
|
| 252 |
+
pos_embed_rope_base=100,
|
| 253 |
+
pos_embed_rope_normalize_coords="separate",
|
| 254 |
+
pos_embed_rope_rescale_coords=2,
|
| 255 |
+
pos_embed_rope_dtype="fp32",
|
| 256 |
+
embed_dim=384,
|
| 257 |
+
depth=12,
|
| 258 |
+
num_heads=6,
|
| 259 |
+
ffn_ratio=6,
|
| 260 |
+
qkv_bias=True,
|
| 261 |
+
drop_path_rate=0.0,
|
| 262 |
+
layerscale_init=1.0e-05,
|
| 263 |
+
norm_layer="layernormbf16",
|
| 264 |
+
ffn_layer="swiglu",
|
| 265 |
+
ffn_bias=True,
|
| 266 |
+
proj_bias=True,
|
| 267 |
+
n_storage_tokens=4,
|
| 268 |
+
mask_k_bias=True,
|
| 269 |
+
pretrained=pretrained,
|
| 270 |
+
weights=weights,
|
| 271 |
+
compact_arch_name="vitsplus",
|
| 272 |
+
check_hash=check_hash,
|
| 273 |
+
**kwargs,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def dinov3_vitb16(
|
| 278 |
+
*,
|
| 279 |
+
pretrained: bool = True,
|
| 280 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 281 |
+
check_hash: bool = False,
|
| 282 |
+
**kwargs,
|
| 283 |
+
):
|
| 284 |
+
if "hash" not in kwargs:
|
| 285 |
+
kwargs["hash"] = "73cec8be"
|
| 286 |
+
kwargs["version"] = None
|
| 287 |
+
return _make_dinov3_vit(
|
| 288 |
+
img_size=224,
|
| 289 |
+
patch_size=16,
|
| 290 |
+
in_chans=3,
|
| 291 |
+
pos_embed_rope_base=100,
|
| 292 |
+
pos_embed_rope_normalize_coords="separate",
|
| 293 |
+
pos_embed_rope_rescale_coords=2,
|
| 294 |
+
pos_embed_rope_dtype="fp32",
|
| 295 |
+
embed_dim=768,
|
| 296 |
+
depth=12,
|
| 297 |
+
num_heads=12,
|
| 298 |
+
ffn_ratio=4,
|
| 299 |
+
qkv_bias=True,
|
| 300 |
+
drop_path_rate=0.0,
|
| 301 |
+
layerscale_init=1.0e-05,
|
| 302 |
+
norm_layer="layernormbf16",
|
| 303 |
+
ffn_layer="mlp",
|
| 304 |
+
ffn_bias=True,
|
| 305 |
+
proj_bias=True,
|
| 306 |
+
n_storage_tokens=4,
|
| 307 |
+
mask_k_bias=True,
|
| 308 |
+
pretrained=pretrained,
|
| 309 |
+
weights=weights,
|
| 310 |
+
compact_arch_name="vitb",
|
| 311 |
+
check_hash=check_hash,
|
| 312 |
+
**kwargs,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def dinov3_vitl16(
|
| 317 |
+
*,
|
| 318 |
+
pretrained: bool = True,
|
| 319 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 320 |
+
check_hash: bool = False,
|
| 321 |
+
**kwargs,
|
| 322 |
+
):
|
| 323 |
+
untie_global_and_local_cls_norm = False
|
| 324 |
+
if weights == Weights.LVD1689M:
|
| 325 |
+
if "hash" not in kwargs:
|
| 326 |
+
kwargs["hash"] = "8aa4cbdd"
|
| 327 |
+
elif weights == Weights.SAT493M:
|
| 328 |
+
if "hash" not in kwargs:
|
| 329 |
+
kwargs["hash"] = "eadcf0ff"
|
| 330 |
+
untie_global_and_local_cls_norm = True
|
| 331 |
+
elif type(weights) is str:
|
| 332 |
+
import re
|
| 333 |
+
|
| 334 |
+
pattern = r"-(.{8}).pth"
|
| 335 |
+
matches = re.findall(pattern, weights)
|
| 336 |
+
if len(matches) != 1:
|
| 337 |
+
raise ValueError(f"Unexpected weights specification for the ViT-L backbone: {weights}")
|
| 338 |
+
hash = matches[0]
|
| 339 |
+
if hash == "eadcf0ff":
|
| 340 |
+
untie_global_and_local_cls_norm = True
|
| 341 |
+
kwargs["version"] = None
|
| 342 |
+
return _make_dinov3_vit(
|
| 343 |
+
img_size=224,
|
| 344 |
+
patch_size=16,
|
| 345 |
+
in_chans=3,
|
| 346 |
+
pos_embed_rope_base=100,
|
| 347 |
+
pos_embed_rope_normalize_coords="separate",
|
| 348 |
+
pos_embed_rope_rescale_coords=2,
|
| 349 |
+
pos_embed_rope_dtype="fp32",
|
| 350 |
+
embed_dim=1024,
|
| 351 |
+
depth=24,
|
| 352 |
+
num_heads=16,
|
| 353 |
+
ffn_ratio=4,
|
| 354 |
+
qkv_bias=True,
|
| 355 |
+
drop_path_rate=0.0,
|
| 356 |
+
layerscale_init=1.0e-05,
|
| 357 |
+
norm_layer="layernormbf16",
|
| 358 |
+
ffn_layer="mlp",
|
| 359 |
+
ffn_bias=True,
|
| 360 |
+
proj_bias=True,
|
| 361 |
+
n_storage_tokens=4,
|
| 362 |
+
mask_k_bias=True,
|
| 363 |
+
untie_global_and_local_cls_norm=untie_global_and_local_cls_norm,
|
| 364 |
+
pretrained=pretrained,
|
| 365 |
+
weights=weights,
|
| 366 |
+
compact_arch_name="vitl",
|
| 367 |
+
check_hash=check_hash,
|
| 368 |
+
**kwargs,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def dinov3_vitl16plus(
|
| 373 |
+
*,
|
| 374 |
+
pretrained: bool = True,
|
| 375 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 376 |
+
check_hash: bool = False,
|
| 377 |
+
**kwargs,
|
| 378 |
+
):
|
| 379 |
+
if "hash" not in kwargs:
|
| 380 |
+
kwargs["hash"] = "46503df0"
|
| 381 |
+
|
| 382 |
+
return _make_dinov3_vit(
|
| 383 |
+
img_size=224,
|
| 384 |
+
patch_size=16,
|
| 385 |
+
in_chans=3,
|
| 386 |
+
pos_embed_rope_base=100,
|
| 387 |
+
pos_embed_rope_normalize_coords="separate",
|
| 388 |
+
pos_embed_rope_rescale_coords=2,
|
| 389 |
+
pos_embed_rope_dtype="fp32",
|
| 390 |
+
embed_dim=1024,
|
| 391 |
+
depth=24,
|
| 392 |
+
num_heads=16,
|
| 393 |
+
ffn_ratio=6.0,
|
| 394 |
+
qkv_bias=True,
|
| 395 |
+
drop_path_rate=0.0,
|
| 396 |
+
layerscale_init=1.0e-05,
|
| 397 |
+
norm_layer="layernormbf16",
|
| 398 |
+
ffn_layer="swiglu",
|
| 399 |
+
ffn_bias=True,
|
| 400 |
+
proj_bias=True,
|
| 401 |
+
n_storage_tokens=4,
|
| 402 |
+
mask_k_bias=True,
|
| 403 |
+
pretrained=pretrained,
|
| 404 |
+
weights=weights,
|
| 405 |
+
compact_arch_name="vitlplus",
|
| 406 |
+
check_hash=check_hash,
|
| 407 |
+
**kwargs,
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def dinov3_vith16plus(
|
| 412 |
+
*,
|
| 413 |
+
pretrained: bool = True,
|
| 414 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 415 |
+
check_hash: bool = False,
|
| 416 |
+
**kwargs,
|
| 417 |
+
):
|
| 418 |
+
if "hash" not in kwargs:
|
| 419 |
+
kwargs["hash"] = "7c1da9a5"
|
| 420 |
+
|
| 421 |
+
return _make_dinov3_vit(
|
| 422 |
+
img_size=224,
|
| 423 |
+
patch_size=16,
|
| 424 |
+
in_chans=3,
|
| 425 |
+
pos_embed_rope_base=100,
|
| 426 |
+
pos_embed_rope_normalize_coords="separate",
|
| 427 |
+
pos_embed_rope_rescale_coords=2,
|
| 428 |
+
pos_embed_rope_dtype="fp32",
|
| 429 |
+
embed_dim=1280,
|
| 430 |
+
depth=32,
|
| 431 |
+
num_heads=20,
|
| 432 |
+
ffn_ratio=6.0,
|
| 433 |
+
qkv_bias=True,
|
| 434 |
+
drop_path_rate=0.0,
|
| 435 |
+
layerscale_init=1.0e-05,
|
| 436 |
+
norm_layer="layernormbf16",
|
| 437 |
+
ffn_layer="swiglu",
|
| 438 |
+
ffn_bias=True,
|
| 439 |
+
proj_bias=True,
|
| 440 |
+
n_storage_tokens=4,
|
| 441 |
+
mask_k_bias=True,
|
| 442 |
+
pretrained=pretrained,
|
| 443 |
+
weights=weights,
|
| 444 |
+
compact_arch_name="vithplus",
|
| 445 |
+
check_hash=check_hash,
|
| 446 |
+
**kwargs,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def dinov3_vit7b16(
|
| 451 |
+
*,
|
| 452 |
+
pretrained: bool = True,
|
| 453 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 454 |
+
check_hash: bool = False,
|
| 455 |
+
**kwargs,
|
| 456 |
+
):
|
| 457 |
+
if weights == Weights.LVD1689M:
|
| 458 |
+
if "hash" not in kwargs:
|
| 459 |
+
kwargs["hash"] = "a955f4ea"
|
| 460 |
+
elif weights == Weights.SAT493M:
|
| 461 |
+
if "hash" not in kwargs:
|
| 462 |
+
kwargs["hash"] = "a6675841"
|
| 463 |
+
kwargs["version"] = None
|
| 464 |
+
untie_global_and_local_cls_norm = True
|
| 465 |
+
return _make_dinov3_vit(
|
| 466 |
+
img_size=224,
|
| 467 |
+
patch_size=16,
|
| 468 |
+
in_chans=3,
|
| 469 |
+
pos_embed_rope_base=100,
|
| 470 |
+
pos_embed_rope_normalize_coords="separate",
|
| 471 |
+
pos_embed_rope_rescale_coords=2,
|
| 472 |
+
pos_embed_rope_dtype="fp32",
|
| 473 |
+
embed_dim=4096,
|
| 474 |
+
depth=40,
|
| 475 |
+
num_heads=32,
|
| 476 |
+
ffn_ratio=3,
|
| 477 |
+
qkv_bias=False,
|
| 478 |
+
drop_path_rate=0.0,
|
| 479 |
+
layerscale_init=1.0e-05,
|
| 480 |
+
norm_layer="layernormbf16",
|
| 481 |
+
ffn_layer="swiglu64",
|
| 482 |
+
ffn_bias=True,
|
| 483 |
+
proj_bias=True,
|
| 484 |
+
n_storage_tokens=4,
|
| 485 |
+
mask_k_bias=True,
|
| 486 |
+
untie_global_and_local_cls_norm=untie_global_and_local_cls_norm,
|
| 487 |
+
pretrained=pretrained,
|
| 488 |
+
weights=weights,
|
| 489 |
+
compact_arch_name="vit7b",
|
| 490 |
+
check_hash=check_hash,
|
| 491 |
+
**kwargs,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def dinov3_convnext_tiny(
|
| 496 |
+
*,
|
| 497 |
+
pretrained: bool = True,
|
| 498 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 499 |
+
**kwargs,
|
| 500 |
+
):
|
| 501 |
+
_hash_convnext = "21b726bb"
|
| 502 |
+
if "hash" not in kwargs:
|
| 503 |
+
kwargs["hash"] = _hash_convnext
|
| 504 |
+
|
| 505 |
+
from ..models.convnext import convnext_sizes
|
| 506 |
+
|
| 507 |
+
size_dict = convnext_sizes["tiny"]
|
| 508 |
+
|
| 509 |
+
model = _make_dinov3_convnext(
|
| 510 |
+
in_chans=3,
|
| 511 |
+
depths=size_dict["depths"],
|
| 512 |
+
dims=size_dict["dims"],
|
| 513 |
+
compact_arch_name="convnext_tiny",
|
| 514 |
+
drop_path_rate=0,
|
| 515 |
+
layer_scale_init_value=1e-6,
|
| 516 |
+
pretrained=pretrained,
|
| 517 |
+
weights=weights,
|
| 518 |
+
**kwargs,
|
| 519 |
+
)
|
| 520 |
+
if not pretrained:
|
| 521 |
+
model.init_weights()
|
| 522 |
+
return model
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def dinov3_convnext_small(
|
| 526 |
+
*,
|
| 527 |
+
pretrained: bool = True,
|
| 528 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 529 |
+
**kwargs,
|
| 530 |
+
):
|
| 531 |
+
_hash_convnext = "296db49d"
|
| 532 |
+
if "hash" not in kwargs:
|
| 533 |
+
kwargs["hash"] = _hash_convnext
|
| 534 |
+
|
| 535 |
+
from ..models.convnext import convnext_sizes
|
| 536 |
+
|
| 537 |
+
size_dict = convnext_sizes["small"]
|
| 538 |
+
|
| 539 |
+
model = _make_dinov3_convnext(
|
| 540 |
+
in_chans=3,
|
| 541 |
+
depths=size_dict["depths"],
|
| 542 |
+
dims=size_dict["dims"],
|
| 543 |
+
compact_arch_name="convnext_small",
|
| 544 |
+
drop_path_rate=0,
|
| 545 |
+
layer_scale_init_value=1e-6,
|
| 546 |
+
pretrained=pretrained,
|
| 547 |
+
weights=weights,
|
| 548 |
+
**kwargs,
|
| 549 |
+
)
|
| 550 |
+
if not pretrained:
|
| 551 |
+
model.init_weights()
|
| 552 |
+
return model
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def dinov3_convnext_base(
|
| 556 |
+
*,
|
| 557 |
+
pretrained: bool = True,
|
| 558 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 559 |
+
**kwargs,
|
| 560 |
+
):
|
| 561 |
+
_hash_convnext = "801f2ba9"
|
| 562 |
+
if "hash" not in kwargs:
|
| 563 |
+
kwargs["hash"] = _hash_convnext
|
| 564 |
+
|
| 565 |
+
from ..models.convnext import convnext_sizes
|
| 566 |
+
|
| 567 |
+
size_dict = convnext_sizes["base"]
|
| 568 |
+
|
| 569 |
+
model = _make_dinov3_convnext(
|
| 570 |
+
in_chans=3,
|
| 571 |
+
depths=size_dict["depths"],
|
| 572 |
+
dims=size_dict["dims"],
|
| 573 |
+
compact_arch_name="convnext_base",
|
| 574 |
+
drop_path_rate=0,
|
| 575 |
+
layer_scale_init_value=1e-6,
|
| 576 |
+
pretrained=pretrained,
|
| 577 |
+
weights=weights,
|
| 578 |
+
**kwargs,
|
| 579 |
+
)
|
| 580 |
+
if not pretrained:
|
| 581 |
+
model.init_weights()
|
| 582 |
+
return model
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def dinov3_convnext_large(
|
| 586 |
+
*,
|
| 587 |
+
pretrained: bool = True,
|
| 588 |
+
weights: Union[Weights, str] = Weights.LVD1689M,
|
| 589 |
+
**kwargs,
|
| 590 |
+
):
|
| 591 |
+
_hash_convnext = "61fa432d"
|
| 592 |
+
if "hash" not in kwargs:
|
| 593 |
+
kwargs["hash"] = _hash_convnext
|
| 594 |
+
|
| 595 |
+
from ..models.convnext import convnext_sizes
|
| 596 |
+
|
| 597 |
+
size_dict = convnext_sizes["large"]
|
| 598 |
+
|
| 599 |
+
model = _make_dinov3_convnext(
|
| 600 |
+
in_chans=3,
|
| 601 |
+
depths=size_dict["depths"],
|
| 602 |
+
dims=size_dict["dims"],
|
| 603 |
+
compact_arch_name="convnext_large",
|
| 604 |
+
drop_path_rate=0,
|
| 605 |
+
layer_scale_init_value=1e-6,
|
| 606 |
+
pretrained=pretrained,
|
| 607 |
+
weights=weights,
|
| 608 |
+
**kwargs,
|
| 609 |
+
)
|
| 610 |
+
if not pretrained:
|
| 611 |
+
model.init_weights()
|
| 612 |
+
return model
|
starVLA/dinov3/dinov3/hub/classifiers.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from enum import Enum
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
|
| 12 |
+
from .backbones import (
|
| 13 |
+
dinov3_vit7b16,
|
| 14 |
+
Weights as BackboneWeights,
|
| 15 |
+
convert_path_or_url_to_url,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ClassifierWeights(Enum):
|
| 22 |
+
IMAGENET1K = "IMAGENET1K"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _make_dinov3_linear_classification_head(
|
| 26 |
+
*,
|
| 27 |
+
backbone_name: str = "dinov3_vit7b16",
|
| 28 |
+
embed_dim: int = 8192,
|
| 29 |
+
pretrained: bool = True,
|
| 30 |
+
classifier_weights: ClassifierWeights | str = ClassifierWeights.IMAGENET1K,
|
| 31 |
+
check_hash: bool = False,
|
| 32 |
+
**kwargs,
|
| 33 |
+
):
|
| 34 |
+
linear_head = nn.Linear(embed_dim, 1_000)
|
| 35 |
+
if pretrained:
|
| 36 |
+
if type(classifier_weights) is ClassifierWeights:
|
| 37 |
+
assert classifier_weights == ClassifierWeights.IMAGENET1K, (
|
| 38 |
+
f"Unsupported weights for linear classifier: {classifier_weights}"
|
| 39 |
+
)
|
| 40 |
+
weights_name = classifier_weights.value.lower()
|
| 41 |
+
hash = kwargs["hash"] if "hash" in kwargs else "90d8ed92"
|
| 42 |
+
model_filename = f"{backbone_name}_{weights_name}_linear_head-{hash}.pth"
|
| 43 |
+
url = os.path.join(_DINOV3_BASE_URL, backbone_name, model_filename)
|
| 44 |
+
else:
|
| 45 |
+
url = convert_path_or_url_to_url(classifier_weights)
|
| 46 |
+
state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)
|
| 47 |
+
linear_head.load_state_dict(state_dict, strict=True)
|
| 48 |
+
return linear_head
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _LinearClassifierWrapper(nn.Module):
|
| 52 |
+
def __init__(self, *, backbone: nn.Module, linear_head: nn.Module):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.backbone = backbone
|
| 55 |
+
self.linear_head = linear_head
|
| 56 |
+
|
| 57 |
+
def forward(self, x):
|
| 58 |
+
x = self.backbone.forward_features(x)
|
| 59 |
+
cls_token = x["x_norm_clstoken"]
|
| 60 |
+
patch_tokens = x["x_norm_patchtokens"]
|
| 61 |
+
linear_input = torch.cat(
|
| 62 |
+
[
|
| 63 |
+
cls_token,
|
| 64 |
+
patch_tokens.mean(dim=1),
|
| 65 |
+
],
|
| 66 |
+
dim=1,
|
| 67 |
+
)
|
| 68 |
+
return self.linear_head(linear_input)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _make_dinov3_linear_classifier(
|
| 72 |
+
*,
|
| 73 |
+
backbone_name: str = "dinov3_vit7b16",
|
| 74 |
+
pretrained: bool = True,
|
| 75 |
+
classifier_weights: ClassifierWeights | str = ClassifierWeights.IMAGENET1K,
|
| 76 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M,
|
| 77 |
+
check_hash: bool = False,
|
| 78 |
+
**kwargs,
|
| 79 |
+
):
|
| 80 |
+
if backbone_name == "dinov3_vit7b16":
|
| 81 |
+
backbone = dinov3_vit7b16(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash)
|
| 82 |
+
else:
|
| 83 |
+
raise AssertionError(f"Unsupported backbone: {backbone_name}, linear classifiers are provided only for ViT-7b")
|
| 84 |
+
embed_dim = backbone.embed_dim
|
| 85 |
+
linear_head = _make_dinov3_linear_classification_head(
|
| 86 |
+
backbone_name=backbone_name,
|
| 87 |
+
embed_dim=2 * embed_dim,
|
| 88 |
+
pretrained=pretrained,
|
| 89 |
+
classifier_weights=classifier_weights,
|
| 90 |
+
**kwargs,
|
| 91 |
+
)
|
| 92 |
+
return _LinearClassifierWrapper(backbone=backbone, linear_head=linear_head)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def dinov3_vit7b16_lc(
|
| 96 |
+
*,
|
| 97 |
+
pretrained: bool = True,
|
| 98 |
+
weights: ClassifierWeights | str = ClassifierWeights.IMAGENET1K,
|
| 99 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M,
|
| 100 |
+
check_hash: bool = False,
|
| 101 |
+
**kwargs,
|
| 102 |
+
):
|
| 103 |
+
"""
|
| 104 |
+
Linear classifier on top of a DINOv3 ViT-7B/16 backbone pretrained on the LVD-1689M dataset and trained on ImageNet-1k.
|
| 105 |
+
"""
|
| 106 |
+
return _make_dinov3_linear_classifier(
|
| 107 |
+
backbone_name="dinov3_vit7b16",
|
| 108 |
+
pretrained=pretrained,
|
| 109 |
+
classifier_weights=weights,
|
| 110 |
+
backbone_weights=backbone_weights,
|
| 111 |
+
check_hash=check_hash,
|
| 112 |
+
**kwargs,
|
| 113 |
+
)
|
starVLA/dinov3/dinov3/hub/depthers.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from enum import Enum
|
| 7 |
+
from typing import Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from dinov3.eval.depth.models import DecoderConfig, make_depther_from_config
|
| 11 |
+
|
| 12 |
+
from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url
|
| 13 |
+
from .backbones import (
|
| 14 |
+
Weights as BackboneWeights,
|
| 15 |
+
dinov3_vitl16,
|
| 16 |
+
dinov3_vit7b16,
|
| 17 |
+
convert_path_or_url_to_url,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DepthWeights(Enum):
|
| 22 |
+
CHMV2 = "CHMV2"
|
| 23 |
+
SYNTHMIX = "SYNTHMIX"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _get_depth_range(dataset: DepthWeights):
|
| 27 |
+
depth_ranges = {
|
| 28 |
+
DepthWeights.SYNTHMIX: (0.001, 100.0),
|
| 29 |
+
}
|
| 30 |
+
return depth_ranges[dataset]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
_DPT_HEAD_CONFIG_DICT = dict(
|
| 34 |
+
use_backbone_norm=True,
|
| 35 |
+
use_batchnorm=True,
|
| 36 |
+
use_cls_token=False,
|
| 37 |
+
n_output_channels=256,
|
| 38 |
+
depth_weights=DepthWeights.SYNTHMIX,
|
| 39 |
+
backbone_weights=BackboneWeights.LVD1689M,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _get_out_layers(backbone_name):
|
| 44 |
+
if "vitl" in backbone_name:
|
| 45 |
+
return [4, 11, 17, 23]
|
| 46 |
+
elif "vit7b" in backbone_name:
|
| 47 |
+
return [9, 19, 29, 39]
|
| 48 |
+
else:
|
| 49 |
+
raise ValueError(f"Unrecognized backbone name {backbone_name}")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _get_post_process_channels(backbone_name):
|
| 53 |
+
if "vitl" in backbone_name:
|
| 54 |
+
return [1024, 1024, 1024, 1024]
|
| 55 |
+
elif "vit7b" in backbone_name:
|
| 56 |
+
return [2048, 2048, 2048, 2048]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
_BACKBONE_DICT = {
|
| 60 |
+
"dinov3_vit7b16": dinov3_vit7b16,
|
| 61 |
+
"dinov3_vitl16": dinov3_vitl16,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _get_depther_config(
|
| 66 |
+
backbone_name: str = "dinov3_vit7b16",
|
| 67 |
+
depth_range: Optional[Tuple[float, float]] = None,
|
| 68 |
+
**kwargs,
|
| 69 |
+
):
|
| 70 |
+
out_index = _get_out_layers(backbone_name)
|
| 71 |
+
post_process_channels = _get_post_process_channels(backbone_name)
|
| 72 |
+
|
| 73 |
+
depth_range = depth_range or _get_depth_range(DepthWeights(_DPT_HEAD_CONFIG_DICT["depth_weights"]))
|
| 74 |
+
min_depth, max_depth = depth_range
|
| 75 |
+
depther_config = DecoderConfig(
|
| 76 |
+
min_depth=min_depth,
|
| 77 |
+
max_depth=max_depth,
|
| 78 |
+
backbone_out_layers=out_index,
|
| 79 |
+
n_output_channels=_DPT_HEAD_CONFIG_DICT["n_output_channels"], # type: ignore
|
| 80 |
+
use_backbone_norm=bool(_DPT_HEAD_CONFIG_DICT["use_backbone_norm"]),
|
| 81 |
+
use_batchnorm=bool(_DPT_HEAD_CONFIG_DICT["use_batchnorm"]),
|
| 82 |
+
use_cls_token=bool(_DPT_HEAD_CONFIG_DICT["use_cls_token"]),
|
| 83 |
+
type="dpt",
|
| 84 |
+
# DPTHead args
|
| 85 |
+
head_kwargs=dict(
|
| 86 |
+
channels=512,
|
| 87 |
+
post_process_channels=post_process_channels,
|
| 88 |
+
),
|
| 89 |
+
**kwargs,
|
| 90 |
+
)
|
| 91 |
+
return depther_config
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _make_dinov3_dpt_depther(
|
| 95 |
+
*,
|
| 96 |
+
backbone_name: str = "dinov3_vit7b16",
|
| 97 |
+
pretrained: bool = True,
|
| 98 |
+
depther_weights: DepthWeights | str = DepthWeights.SYNTHMIX,
|
| 99 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M,
|
| 100 |
+
depth_range: Optional[Tuple[float, float]] = None,
|
| 101 |
+
check_hash: bool = False,
|
| 102 |
+
autocast_dtype: torch.dtype = torch.float32,
|
| 103 |
+
**kwargs,
|
| 104 |
+
):
|
| 105 |
+
backbone: torch.nn.Module = _BACKBONE_DICT[backbone_name](
|
| 106 |
+
pretrained=pretrained,
|
| 107 |
+
weights=backbone_weights,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
depther = make_depther_from_config(
|
| 111 |
+
backbone,
|
| 112 |
+
config=_get_depther_config(backbone_name, depth_range),
|
| 113 |
+
autocast_dtype=autocast_dtype,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if pretrained:
|
| 117 |
+
if isinstance(depther_weights, DepthWeights):
|
| 118 |
+
assert depther_weights == DepthWeights.SYNTHMIX, f"Unsupported depther weights {depther_weights}"
|
| 119 |
+
weights_name = depther_weights.value.lower()
|
| 120 |
+
hash = kwargs["hash"] if "hash" in kwargs else "02040be1"
|
| 121 |
+
url = _DINOV3_BASE_URL + f"/{backbone_name}/{backbone_name}_{weights_name}_dpt_head-{hash}.pth"
|
| 122 |
+
else:
|
| 123 |
+
url = convert_path_or_url_to_url(depther_weights)
|
| 124 |
+
checkpoint = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)
|
| 125 |
+
depther.decoder.load_state_dict(checkpoint, strict=True)
|
| 126 |
+
return depther
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def dinov3_vit7b16_dd(
|
| 130 |
+
*,
|
| 131 |
+
pretrained: bool = True,
|
| 132 |
+
weights: DepthWeights | str = DepthWeights.SYNTHMIX,
|
| 133 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M,
|
| 134 |
+
check_hash: bool = False,
|
| 135 |
+
autocast_dtype: torch.dtype = torch.float32,
|
| 136 |
+
**kwargs,
|
| 137 |
+
):
|
| 138 |
+
return _make_dinov3_dpt_depther(
|
| 139 |
+
backbone_name="dinov3_vit7b16",
|
| 140 |
+
pretrained=pretrained,
|
| 141 |
+
depther_weights=weights,
|
| 142 |
+
backbone_weights=backbone_weights,
|
| 143 |
+
check_hash=check_hash,
|
| 144 |
+
autocast_dtype=autocast_dtype,
|
| 145 |
+
**kwargs,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _get_chmv2_config(
|
| 150 |
+
**kwargs,
|
| 151 |
+
):
|
| 152 |
+
return DecoderConfig(
|
| 153 |
+
min_depth=0.001,
|
| 154 |
+
max_depth=96.0,
|
| 155 |
+
backbone_out_layers=[5, 11, 17, 23],
|
| 156 |
+
n_output_channels=256,
|
| 157 |
+
use_backbone_norm=True,
|
| 158 |
+
use_batchnorm=False,
|
| 159 |
+
use_cls_token=True,
|
| 160 |
+
type="dpt",
|
| 161 |
+
bins_strategy="chmv2_mixlog",
|
| 162 |
+
norm_strategy="chmv2_mixlog",
|
| 163 |
+
head_kwargs={
|
| 164 |
+
"n_hidden_channels": 128,
|
| 165 |
+
"use_bias": True,
|
| 166 |
+
"projection_after_fusion": False,
|
| 167 |
+
},
|
| 168 |
+
**kwargs,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def dinov3_vitl16_chmv2(
|
| 173 |
+
pretrained: bool = True,
|
| 174 |
+
weights: DepthWeights | str = DepthWeights.CHMV2,
|
| 175 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.SAT493M,
|
| 176 |
+
check_hash: bool = False,
|
| 177 |
+
autocast_dtype: torch.dtype = torch.float32,
|
| 178 |
+
**kwargs,
|
| 179 |
+
):
|
| 180 |
+
backbone: torch.nn.Module = dinov3_vitl16(pretrained=pretrained, weights=backbone_weights)
|
| 181 |
+
|
| 182 |
+
chmv2_depther = make_depther_from_config(
|
| 183 |
+
backbone,
|
| 184 |
+
config=_get_chmv2_config(),
|
| 185 |
+
autocast_dtype=autocast_dtype,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
if pretrained:
|
| 189 |
+
if isinstance(weights, DepthWeights):
|
| 190 |
+
assert weights == DepthWeights.CHMV2, f"Unsupported chmv2 weights {weights}"
|
| 191 |
+
weights_name = weights.value.lower()
|
| 192 |
+
url = _DINOV3_BASE_URL + f"/chmv2/dinov3_vitl16_{weights_name}_dpt_head-3703d643.pth"
|
| 193 |
+
else:
|
| 194 |
+
url = convert_path_or_url_to_url(weights)
|
| 195 |
+
checkpoint = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)
|
| 196 |
+
chmv2_depther.decoder.load_state_dict(checkpoint, strict=True)
|
| 197 |
+
return chmv2_depther
|
starVLA/dinov3/dinov3/hub/detectors.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from enum import Enum
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from dinov3.eval.detection.config import DetectionHeadConfig
|
| 12 |
+
from dinov3.eval.detection.models.detr import PostProcess, build_model
|
| 13 |
+
from dinov3.eval.detection.models.position_encoding import PositionEncoding
|
| 14 |
+
|
| 15 |
+
from .backbones import Weights as BackboneWeights, dinov3_vit7b16, dinov3_vitl16plus, convert_path_or_url_to_url
|
| 16 |
+
from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class DetectionWeights(Enum):
|
| 20 |
+
COCO2017 = "COCO2017"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DetectorWithProcessor(torch.nn.Module):
|
| 24 |
+
"""
|
| 25 |
+
takes as input a list of (3, H, W) normalized image tensors and outputs
|
| 26 |
+
a list of dicts with keys "scores", "labels" and "boxes" (format XYXY)
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, detector, postprocessor):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.detector = detector
|
| 32 |
+
self.postprocessor = postprocessor
|
| 33 |
+
|
| 34 |
+
def forward(self, samples: list[torch.Tensor]):
|
| 35 |
+
outputs = self.detector(samples)
|
| 36 |
+
sizes_tensor = torch.tensor([sample.shape[1:] for sample in samples], device=samples[0].device) # N * [3, H, W]
|
| 37 |
+
return self.postprocessor(outputs, target_sizes=sizes_tensor, original_target_sizes=sizes_tensor)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _make_dinov3_detector(
|
| 41 |
+
*,
|
| 42 |
+
backbone_name: str,
|
| 43 |
+
pretrained: bool = True,
|
| 44 |
+
detector_weights: str | DetectionWeights,
|
| 45 |
+
backbone_weights: str | BackboneWeights,
|
| 46 |
+
check_hash: bool = False,
|
| 47 |
+
**kwargs,
|
| 48 |
+
):
|
| 49 |
+
detection_kwargs = dict(
|
| 50 |
+
with_box_refine=True,
|
| 51 |
+
two_stage=True,
|
| 52 |
+
mixed_selection=True,
|
| 53 |
+
look_forward_twice=True,
|
| 54 |
+
k_one2many=6,
|
| 55 |
+
lambda_one2many=1.0,
|
| 56 |
+
num_queries_one2one=1500,
|
| 57 |
+
num_queries_one2many=1500,
|
| 58 |
+
reparam=True,
|
| 59 |
+
position_embedding=PositionEncoding.SINE,
|
| 60 |
+
num_feature_levels=1,
|
| 61 |
+
dec_layers=6,
|
| 62 |
+
dim_feedforward=2048,
|
| 63 |
+
dropout=0.0,
|
| 64 |
+
norm_type="pre_norm",
|
| 65 |
+
proposal_feature_levels=4,
|
| 66 |
+
proposal_min_size=50,
|
| 67 |
+
decoder_type="global_rpe_decomp",
|
| 68 |
+
decoder_use_checkpoint=False,
|
| 69 |
+
decoder_rpe_hidden_dim=512,
|
| 70 |
+
decoder_rpe_type="linear",
|
| 71 |
+
layers_to_use=None,
|
| 72 |
+
blocks_to_train=None,
|
| 73 |
+
add_transformer_encoder=True,
|
| 74 |
+
num_encoder_layers=6,
|
| 75 |
+
backbone_use_layernorm=False,
|
| 76 |
+
num_classes=91, # 91 classes in COCO
|
| 77 |
+
aux_loss=True,
|
| 78 |
+
topk=1500,
|
| 79 |
+
hidden_dim=768,
|
| 80 |
+
nheads=8,
|
| 81 |
+
)
|
| 82 |
+
config = DetectionHeadConfig(**detection_kwargs)
|
| 83 |
+
backbone_class = dict(dinov3_vit7b16=dinov3_vit7b16, dinov3_vitl16plus=dinov3_vitl16plus)[backbone_name]
|
| 84 |
+
n_windows_sqrt = dict(dinov3_vit7b16=3, dinov3_vitl16plus=2)[backbone_name]
|
| 85 |
+
backbone = backbone_class(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash)
|
| 86 |
+
backbone.eval()
|
| 87 |
+
|
| 88 |
+
config.n_windows_sqrt = n_windows_sqrt
|
| 89 |
+
config.proposal_in_stride = backbone.patch_size
|
| 90 |
+
config.proposal_tgt_strides = [int(m * backbone.patch_size) for m in (0.5, 1, 2, 4)]
|
| 91 |
+
|
| 92 |
+
if config.layers_to_use is None:
|
| 93 |
+
# e.g. [2, 5, 8, 11] for a backbone with 12 blocks, similar to depth evaluation
|
| 94 |
+
config.layers_to_use = [m * backbone.n_blocks // 4 - 1 for m in range(1, 5)]
|
| 95 |
+
|
| 96 |
+
detector = build_model(backbone, config)
|
| 97 |
+
if pretrained:
|
| 98 |
+
if type(detector_weights) is DetectionWeights and detector_weights == DetectionWeights.COCO2017:
|
| 99 |
+
assert detector_weights == DetectionWeights.COCO2017, f"Unsupported detector weights {detector_weights}"
|
| 100 |
+
detection_weights_name = detector_weights.value.lower()
|
| 101 |
+
hash = kwargs["hash"] if "hash" in kwargs else "b0235ff7"
|
| 102 |
+
model_filename = f"{backbone_name}_{detection_weights_name}_detr_head-{hash}.pth"
|
| 103 |
+
url = os.path.join(_DINOV3_BASE_URL, backbone_name, model_filename)
|
| 104 |
+
else:
|
| 105 |
+
url = convert_path_or_url_to_url(detector_weights)
|
| 106 |
+
state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)["model"]
|
| 107 |
+
detector.load_state_dict(state_dict, strict=False)
|
| 108 |
+
# Necessary for inference
|
| 109 |
+
detector.num_queries = detector.num_queries_one2one
|
| 110 |
+
detector.transformer.two_stage_num_proposals = detector.num_queries
|
| 111 |
+
|
| 112 |
+
postprocessor = PostProcess(config.topk, config.reparam)
|
| 113 |
+
model = DetectorWithProcessor(detector=detector, postprocessor=postprocessor)
|
| 114 |
+
return model
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def dinov3_vit7b16_de(
|
| 118 |
+
*,
|
| 119 |
+
pretrained: bool = True,
|
| 120 |
+
weights: DetectionWeights | str = DetectionWeights.COCO2017,
|
| 121 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M,
|
| 122 |
+
check_hash: bool = False,
|
| 123 |
+
**kwargs,
|
| 124 |
+
):
|
| 125 |
+
return _make_dinov3_detector(
|
| 126 |
+
backbone_name="dinov3_vit7b16",
|
| 127 |
+
pretrained=pretrained,
|
| 128 |
+
detector_weights=weights,
|
| 129 |
+
backbone_weights=backbone_weights,
|
| 130 |
+
check_hash=check_hash,
|
| 131 |
+
**kwargs,
|
| 132 |
+
)
|
starVLA/dinov3/dinov3/hub/dinotxt.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from typing import Any, Tuple, Union
|
| 8 |
+
from enum import Enum
|
| 9 |
+
|
| 10 |
+
from torch import nn
|
| 11 |
+
|
| 12 |
+
from .backbones import dinov3_vitl16, Weights as BackboneWeights, convert_path_or_url_to_url
|
| 13 |
+
from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class DINOTxtWeights(Enum):
|
| 17 |
+
LVTD2300M = "LVTD2300M"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# returns dinotxt model and tokenizer
|
| 21 |
+
def dinov3_vitl16_dinotxt_tet1280d20h24l(
|
| 22 |
+
*,
|
| 23 |
+
pretrained: bool = True,
|
| 24 |
+
weights: Union[DINOTxtWeights, str] = DINOTxtWeights.LVTD2300M,
|
| 25 |
+
backbone_weights: Union[BackboneWeights, str] = BackboneWeights.LVD1689M,
|
| 26 |
+
bpe_path_or_url: str = "https://dl.fbaipublicfiles.com/dinov3/thirdparty/bpe_simple_vocab_16e6.txt.gz",
|
| 27 |
+
check_hash: bool = False,
|
| 28 |
+
) -> Tuple[nn.Module, Any]:
|
| 29 |
+
from dinov3.eval.text.dinotxt_model import DINOTxt, DINOTxtConfig
|
| 30 |
+
from dinov3.eval.text.text_transformer import TextTransformer
|
| 31 |
+
from dinov3.eval.text.tokenizer import get_tokenizer
|
| 32 |
+
|
| 33 |
+
dinotxt_config = DINOTxtConfig(
|
| 34 |
+
embed_dim=2048,
|
| 35 |
+
vision_model_freeze_backbone=True,
|
| 36 |
+
vision_model_train_img_size=224,
|
| 37 |
+
vision_model_use_class_token=True,
|
| 38 |
+
vision_model_use_patch_tokens=True,
|
| 39 |
+
vision_model_num_head_blocks=2,
|
| 40 |
+
vision_model_head_blocks_drop_path=0.3,
|
| 41 |
+
vision_model_use_linear_projection=False,
|
| 42 |
+
vision_model_patch_tokens_pooler_type="mean",
|
| 43 |
+
vision_model_patch_token_layer=1, # which layer to take patch tokens from
|
| 44 |
+
# 1 - last layer, 2 - second last layer, etc.
|
| 45 |
+
text_model_freeze_backbone=False,
|
| 46 |
+
text_model_num_head_blocks=0,
|
| 47 |
+
text_model_head_blocks_is_causal=False,
|
| 48 |
+
text_model_head_blocks_drop_prob=0.0,
|
| 49 |
+
text_model_tokens_pooler_type="argmax",
|
| 50 |
+
text_model_use_linear_projection=True,
|
| 51 |
+
init_logit_scale=math.log(1 / 0.07),
|
| 52 |
+
init_logit_bias=None,
|
| 53 |
+
freeze_logit_scale=False,
|
| 54 |
+
)
|
| 55 |
+
vision_backbone = dinov3_vitl16(pretrained=pretrained, weights=backbone_weights)
|
| 56 |
+
text_backbone = TextTransformer(
|
| 57 |
+
context_length=77,
|
| 58 |
+
vocab_size=49408,
|
| 59 |
+
dim=1280,
|
| 60 |
+
num_heads=20,
|
| 61 |
+
num_layers=24,
|
| 62 |
+
ffn_ratio=4,
|
| 63 |
+
is_causal=True,
|
| 64 |
+
ls_init_value=None,
|
| 65 |
+
dropout_prob=0.0,
|
| 66 |
+
)
|
| 67 |
+
model = DINOTxt(model_config=dinotxt_config, vision_backbone=vision_backbone, text_backbone=text_backbone)
|
| 68 |
+
if pretrained:
|
| 69 |
+
model.visual_model.backbone = vision_backbone
|
| 70 |
+
model.eval()
|
| 71 |
+
if type(weights) is DINOTxtWeights and weights == DINOTxtWeights.LVTD2300M:
|
| 72 |
+
url = f"{_DINOV3_BASE_URL}/dinov3_vitl16/dinov3_vitl16_dinotxt_vision_head_and_text_encoder-a442d8f5.pth"
|
| 73 |
+
elif type(weights) is DINOTxtWeights and weights != DINOTxtWeights.LVTD2300M:
|
| 74 |
+
raise AssertionError(f"Unsuported weights for DINOTxt: {weights}")
|
| 75 |
+
else:
|
| 76 |
+
url = convert_path_or_url_to_url(weights)
|
| 77 |
+
vision_head_and_text_encoder_state_dict = _safe_load_state_dict_from_url(
|
| 78 |
+
url, map_location="cpu", check_hash=check_hash
|
| 79 |
+
)
|
| 80 |
+
model.load_state_dict(vision_head_and_text_encoder_state_dict, strict=False)
|
| 81 |
+
else:
|
| 82 |
+
model.init_weights()
|
| 83 |
+
return model, get_tokenizer(bpe_path_or_url=bpe_path_or_url)
|
starVLA/dinov3/dinov3/hub/segmentors.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from enum import Enum
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from dinov3.eval.segmentation.models import build_segmentation_decoder
|
| 11 |
+
|
| 12 |
+
from .backbones import (
|
| 13 |
+
dinov3_vit7b16,
|
| 14 |
+
dinov3_vitl16,
|
| 15 |
+
Weights as BackboneWeights,
|
| 16 |
+
convert_path_or_url_to_url,
|
| 17 |
+
)
|
| 18 |
+
from .utils import _DINOV3_BASE_URL, _safe_load_state_dict_from_url
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SegmentorWeights(Enum):
|
| 22 |
+
ADE20K = "ADE20K"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _make_dinov3_m2f_segmentor(
|
| 26 |
+
*,
|
| 27 |
+
backbone_name: str = "dinov3_vit7b16",
|
| 28 |
+
pretrained: bool = True,
|
| 29 |
+
segmentor_weights: SegmentorWeights | str = SegmentorWeights.ADE20K,
|
| 30 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M,
|
| 31 |
+
check_hash: bool = False,
|
| 32 |
+
autocast_dtype: torch.dtype = torch.bfloat16,
|
| 33 |
+
**kwargs,
|
| 34 |
+
):
|
| 35 |
+
if backbone_name == "dinov3_vit7b16":
|
| 36 |
+
backbone_model = dinov3_vit7b16(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash)
|
| 37 |
+
elif backbone_name == "dinov3_vitl16":
|
| 38 |
+
backbone_model = dinov3_vitl16(pretrained=pretrained, weights=backbone_weights, check_hash=check_hash)
|
| 39 |
+
else:
|
| 40 |
+
raise AssertionError(f"No pretrained segmentation checkpoint available for {backbone_name}")
|
| 41 |
+
|
| 42 |
+
hidden_dim = 2048 if "hidden_dim" not in kwargs else kwargs["hidden_dim"]
|
| 43 |
+
segmentor = build_segmentation_decoder(
|
| 44 |
+
backbone_model=backbone_model,
|
| 45 |
+
decoder_type="m2f",
|
| 46 |
+
hidden_dim=hidden_dim,
|
| 47 |
+
autocast_dtype=autocast_dtype,
|
| 48 |
+
)
|
| 49 |
+
if pretrained:
|
| 50 |
+
if type(segmentor_weights) is SegmentorWeights:
|
| 51 |
+
assert segmentor_weights == SegmentorWeights.ADE20K, (
|
| 52 |
+
f"Unsupported weights for segmentor: {segmentor_weights}"
|
| 53 |
+
)
|
| 54 |
+
segmentor_weights_name = segmentor_weights.value.lower()
|
| 55 |
+
hash = kwargs["hash"] if "hash" in kwargs else "bf307cb1"
|
| 56 |
+
model_filename = f"{backbone_name}_{segmentor_weights_name}_m2f_head-{hash}.pth"
|
| 57 |
+
url = os.path.join(_DINOV3_BASE_URL, backbone_name, model_filename)
|
| 58 |
+
else:
|
| 59 |
+
url = convert_path_or_url_to_url(segmentor_weights)
|
| 60 |
+
state_dict = _safe_load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)
|
| 61 |
+
missing_keys, unexpected_keys = segmentor.load_state_dict(state_dict, strict=False)
|
| 62 |
+
assert len([k for k in missing_keys if "backbone" not in k]) == 0
|
| 63 |
+
assert len(unexpected_keys) == 0
|
| 64 |
+
|
| 65 |
+
return segmentor
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def dinov3_vit7b16_ms(
|
| 69 |
+
*,
|
| 70 |
+
pretrained: bool = True,
|
| 71 |
+
weights: SegmentorWeights | str = SegmentorWeights.ADE20K,
|
| 72 |
+
backbone_weights: BackboneWeights | str = BackboneWeights.LVD1689M,
|
| 73 |
+
check_hash: bool = False,
|
| 74 |
+
autocast_dtype: torch.dtype = torch.bfloat16,
|
| 75 |
+
**kwargs,
|
| 76 |
+
):
|
| 77 |
+
return _make_dinov3_m2f_segmentor(
|
| 78 |
+
backbone_name="dinov3_vit7b16",
|
| 79 |
+
pretrained=pretrained,
|
| 80 |
+
segmentor_weights=weights,
|
| 81 |
+
backbone_weights=backbone_weights,
|
| 82 |
+
check_hash=check_hash,
|
| 83 |
+
autocast_dtype=autocast_dtype,
|
| 84 |
+
**kwargs,
|
| 85 |
+
)
|
starVLA/dinov3/dinov3/hub/utils.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
_DINOV3_BASE_URL = "https://dl.fbaipublicfiles.com/dinov3"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _safe_load_state_dict_from_url(url: str, **kwargs):
|
| 13 |
+
# See https://github.com/pytorch/pytorch/releases/tag/v2.1.0 (Misc / #98479)
|
| 14 |
+
if torch.__version__ >= (2, 1):
|
| 15 |
+
local_kwargs = {**kwargs, "weights_only": True}
|
| 16 |
+
else:
|
| 17 |
+
local_kwargs = kwargs
|
| 18 |
+
return torch.hub.load_state_dict_from_url(url, **local_kwargs)
|
starVLA/dinov3/dinov3/layers/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from .attention import CausalSelfAttention, LinearKMaskedBias, SelfAttention
|
| 7 |
+
from .block import CausalSelfAttentionBlock, SelfAttentionBlock
|
| 8 |
+
from .ffn_layers import Mlp, SwiGLUFFN
|
| 9 |
+
from .fp8_linear import convert_linears_to_fp8
|
| 10 |
+
from .layer_scale import LayerScale
|
| 11 |
+
from .patch_embed import PatchEmbed
|
| 12 |
+
from .rms_norm import RMSNorm
|
| 13 |
+
from .rope_position_encoding import RopePositionEmbedding
|
starVLA/dinov3/dinov3/layers/attention.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from typing import List, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from dinov3.utils import cat_keep_shapes, uncat_with_shapes
|
| 12 |
+
from torch import Tensor, nn
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# RoPE-related functions:
|
| 16 |
+
def rope_rotate_half(x: Tensor) -> Tensor:
|
| 17 |
+
# x: [ x0 x1 x2 x3 x4 x5]
|
| 18 |
+
# out: [-x3 -x4 -x5 x0 x1 x2]
|
| 19 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 20 |
+
return torch.cat([-x2, x1], dim=-1)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def rope_apply(x: Tensor, sin: Tensor, cos: Tensor) -> Tensor:
|
| 24 |
+
# x: [..., D], eg [x0, x1, x2, x3, x4, x5]
|
| 25 |
+
# sin: [..., D], eg [sin0, sin1, sin2, sin0, sin1, sin2]
|
| 26 |
+
# cos: [..., D], eg [cos0, cos1, cos2, cos0, cos1, cos2]
|
| 27 |
+
return (x * cos) + (rope_rotate_half(x) * sin)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class LinearKMaskedBias(nn.Linear):
|
| 31 |
+
def __init__(self, *args, **kwargs):
|
| 32 |
+
super().__init__(*args, **kwargs)
|
| 33 |
+
o = self.out_features
|
| 34 |
+
assert o % 3 == 0
|
| 35 |
+
if self.bias is not None:
|
| 36 |
+
self.register_buffer("bias_mask", torch.full_like(self.bias, fill_value=math.nan))
|
| 37 |
+
|
| 38 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 39 |
+
masked_bias = self.bias * self.bias_mask.to(self.bias.dtype) if self.bias is not None else None
|
| 40 |
+
return F.linear(input, self.weight, masked_bias)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class SelfAttention(nn.Module):
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
dim: int,
|
| 47 |
+
num_heads: int = 8,
|
| 48 |
+
qkv_bias: bool = False,
|
| 49 |
+
proj_bias: bool = True,
|
| 50 |
+
attn_drop: float = 0.0,
|
| 51 |
+
proj_drop: float = 0.0,
|
| 52 |
+
mask_k_bias: bool = False,
|
| 53 |
+
device=None,
|
| 54 |
+
) -> None:
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.num_heads = num_heads
|
| 57 |
+
head_dim = dim // num_heads
|
| 58 |
+
self.scale = head_dim**-0.5
|
| 59 |
+
|
| 60 |
+
linear_class = LinearKMaskedBias if mask_k_bias else nn.Linear
|
| 61 |
+
self.qkv = linear_class(dim, dim * 3, bias=qkv_bias, device=device)
|
| 62 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 63 |
+
self.proj = nn.Linear(dim, dim, bias=proj_bias, device=device)
|
| 64 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 65 |
+
|
| 66 |
+
def apply_rope(self, q: Tensor, k: Tensor, rope: Tensor | Tuple[Tensor, Tensor]) -> Tuple[Tensor, Tensor]:
|
| 67 |
+
# All operations will use the dtype of rope, the output is cast back to the dtype of q and k
|
| 68 |
+
q_dtype = q.dtype
|
| 69 |
+
k_dtype = k.dtype
|
| 70 |
+
sin, cos = rope
|
| 71 |
+
rope_dtype = sin.dtype
|
| 72 |
+
q = q.to(dtype=rope_dtype)
|
| 73 |
+
k = k.to(dtype=rope_dtype)
|
| 74 |
+
N = q.shape[-2]
|
| 75 |
+
prefix = N - sin.shape[-2]
|
| 76 |
+
assert prefix >= 0
|
| 77 |
+
q_prefix = q[:, :, :prefix, :]
|
| 78 |
+
q = rope_apply(q[:, :, prefix:, :], sin, cos) # [B, head, hw, D//head]
|
| 79 |
+
q = torch.cat((q_prefix, q), dim=-2) # [B, head, N, D//head]
|
| 80 |
+
k_prefix = k[:, :, :prefix, :]
|
| 81 |
+
k = rope_apply(k[:, :, prefix:, :], sin, cos) # [B, head, hw, D//head]
|
| 82 |
+
k = torch.cat((k_prefix, k), dim=-2) # [B, head, N, D//head]
|
| 83 |
+
q = q.to(dtype=q_dtype)
|
| 84 |
+
k = k.to(dtype=k_dtype)
|
| 85 |
+
return q, k
|
| 86 |
+
|
| 87 |
+
def forward(self, x: Tensor, attn_bias=None, rope: Tensor = None) -> Tensor:
|
| 88 |
+
qkv = self.qkv(x)
|
| 89 |
+
attn_v = self.compute_attention(qkv=qkv, attn_bias=attn_bias, rope=rope)
|
| 90 |
+
x = self.proj(attn_v)
|
| 91 |
+
x = self.proj_drop(x)
|
| 92 |
+
return x
|
| 93 |
+
|
| 94 |
+
def forward_list(self, x_list, attn_bias=None, rope_list=None) -> List[Tensor]:
|
| 95 |
+
assert len(x_list) == len(rope_list) # should be enforced by the Block
|
| 96 |
+
x_flat, shapes, num_tokens = cat_keep_shapes(x_list)
|
| 97 |
+
qkv_flat = self.qkv(x_flat)
|
| 98 |
+
qkv_list = uncat_with_shapes(qkv_flat, shapes, num_tokens)
|
| 99 |
+
att_out = []
|
| 100 |
+
for _, (qkv, _, rope) in enumerate(zip(qkv_list, shapes, rope_list)):
|
| 101 |
+
att_out.append(self.compute_attention(qkv, attn_bias=attn_bias, rope=rope))
|
| 102 |
+
x_flat, shapes, num_tokens = cat_keep_shapes(att_out)
|
| 103 |
+
x_flat = self.proj(x_flat)
|
| 104 |
+
return uncat_with_shapes(x_flat, shapes, num_tokens)
|
| 105 |
+
|
| 106 |
+
def compute_attention(self, qkv: Tensor, attn_bias=None, rope=None) -> Tensor:
|
| 107 |
+
assert attn_bias is None
|
| 108 |
+
B, N, _ = qkv.shape
|
| 109 |
+
C = self.qkv.in_features
|
| 110 |
+
|
| 111 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
| 112 |
+
q, k, v = torch.unbind(qkv, 2)
|
| 113 |
+
q, k, v = [t.transpose(1, 2) for t in [q, k, v]]
|
| 114 |
+
if rope is not None:
|
| 115 |
+
q, k = self.apply_rope(q, k, rope)
|
| 116 |
+
x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
|
| 117 |
+
x = x.transpose(1, 2)
|
| 118 |
+
return x.reshape([B, N, C])
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class CausalSelfAttention(nn.Module):
|
| 122 |
+
def __init__(
|
| 123 |
+
self,
|
| 124 |
+
dim: int,
|
| 125 |
+
num_heads: int = 8,
|
| 126 |
+
qkv_bias: bool = False,
|
| 127 |
+
proj_bias: bool = True,
|
| 128 |
+
attn_drop: float = 0.0,
|
| 129 |
+
proj_drop: float = 0.0,
|
| 130 |
+
) -> None:
|
| 131 |
+
super().__init__()
|
| 132 |
+
self.dim = dim
|
| 133 |
+
self.num_heads = num_heads
|
| 134 |
+
head_dim = dim // num_heads
|
| 135 |
+
self.scale = head_dim**-0.5
|
| 136 |
+
|
| 137 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 138 |
+
self.attn_drop = attn_drop
|
| 139 |
+
self.proj = nn.Linear(dim, dim, bias=proj_bias)
|
| 140 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 141 |
+
|
| 142 |
+
def init_weights(
|
| 143 |
+
self, init_attn_std: float | None = None, init_proj_std: float | None = None, factor: float = 1.0
|
| 144 |
+
) -> None:
|
| 145 |
+
init_attn_std = init_attn_std or (self.dim**-0.5)
|
| 146 |
+
init_proj_std = init_proj_std or init_attn_std * factor
|
| 147 |
+
nn.init.normal_(self.qkv.weight, std=init_attn_std)
|
| 148 |
+
nn.init.normal_(self.proj.weight, std=init_proj_std)
|
| 149 |
+
if self.qkv.bias is not None:
|
| 150 |
+
nn.init.zeros_(self.qkv.bias)
|
| 151 |
+
if self.proj.bias is not None:
|
| 152 |
+
nn.init.zeros_(self.proj.bias)
|
| 153 |
+
|
| 154 |
+
def forward(self, x: Tensor, is_causal: bool = True) -> Tensor:
|
| 155 |
+
B, N, C = x.shape
|
| 156 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
| 157 |
+
q, k, v = torch.unbind(qkv, 2)
|
| 158 |
+
q, k, v = [t.transpose(1, 2) for t in [q, k, v]]
|
| 159 |
+
x = torch.nn.functional.scaled_dot_product_attention(
|
| 160 |
+
q, k, v, attn_mask=None, dropout_p=self.attn_drop if self.training else 0, is_causal=is_causal
|
| 161 |
+
)
|
| 162 |
+
x = x.transpose(1, 2).contiguous().view(B, N, C)
|
| 163 |
+
x = self.proj_drop(self.proj(x))
|
| 164 |
+
return x
|
starVLA/dinov3/dinov3/layers/block.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from typing import Callable, List, Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
|
| 11 |
+
from dinov3.utils import cat_keep_shapes, uncat_with_shapes
|
| 12 |
+
|
| 13 |
+
from .attention import CausalSelfAttention, SelfAttention
|
| 14 |
+
from .ffn_layers import Mlp
|
| 15 |
+
from .layer_scale import LayerScale # , DropPath
|
| 16 |
+
|
| 17 |
+
torch._dynamo.config.automatic_dynamic_shapes = False
|
| 18 |
+
torch._dynamo.config.accumulated_cache_size_limit = 1024
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SelfAttentionBlock(nn.Module):
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
dim: int,
|
| 25 |
+
num_heads: int,
|
| 26 |
+
ffn_ratio: float = 4.0,
|
| 27 |
+
qkv_bias: bool = False,
|
| 28 |
+
proj_bias: bool = True,
|
| 29 |
+
ffn_bias: bool = True,
|
| 30 |
+
drop: float = 0.0,
|
| 31 |
+
attn_drop: float = 0.0,
|
| 32 |
+
init_values=None,
|
| 33 |
+
drop_path: float = 0.0,
|
| 34 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 35 |
+
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
|
| 36 |
+
attn_class: Callable[..., nn.Module] = SelfAttention,
|
| 37 |
+
ffn_layer: Callable[..., nn.Module] = Mlp,
|
| 38 |
+
mask_k_bias: bool = False,
|
| 39 |
+
device=None,
|
| 40 |
+
) -> None:
|
| 41 |
+
super().__init__()
|
| 42 |
+
# print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
|
| 43 |
+
self.norm1 = norm_layer(dim)
|
| 44 |
+
self.attn = attn_class(
|
| 45 |
+
dim,
|
| 46 |
+
num_heads=num_heads,
|
| 47 |
+
qkv_bias=qkv_bias,
|
| 48 |
+
proj_bias=proj_bias,
|
| 49 |
+
attn_drop=attn_drop,
|
| 50 |
+
proj_drop=drop,
|
| 51 |
+
mask_k_bias=mask_k_bias,
|
| 52 |
+
device=device,
|
| 53 |
+
)
|
| 54 |
+
self.ls1 = LayerScale(dim, init_values=init_values, device=device) if init_values else nn.Identity()
|
| 55 |
+
|
| 56 |
+
self.norm2 = norm_layer(dim)
|
| 57 |
+
mlp_hidden_dim = int(dim * ffn_ratio)
|
| 58 |
+
self.mlp = ffn_layer(
|
| 59 |
+
in_features=dim,
|
| 60 |
+
hidden_features=mlp_hidden_dim,
|
| 61 |
+
act_layer=act_layer,
|
| 62 |
+
drop=drop,
|
| 63 |
+
bias=ffn_bias,
|
| 64 |
+
device=device,
|
| 65 |
+
)
|
| 66 |
+
self.ls2 = LayerScale(dim, init_values=init_values, device=device) if init_values else nn.Identity()
|
| 67 |
+
|
| 68 |
+
self.sample_drop_ratio = drop_path
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def _maybe_index_rope(rope: tuple[Tensor, Tensor] | None, indices: Tensor) -> tuple[Tensor, Tensor] | None:
|
| 72 |
+
if rope is None:
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
sin, cos = rope
|
| 76 |
+
assert sin.ndim == cos.ndim
|
| 77 |
+
if sin.ndim == 4:
|
| 78 |
+
# If the rope embedding has a batch dimension (is different for each batch element), index into it
|
| 79 |
+
return sin[indices], cos[indices] # [batch, heads, patches, embed_dim]
|
| 80 |
+
else:
|
| 81 |
+
# No batch dimension, do not index
|
| 82 |
+
return sin, cos # [heads, patches, embed_dim] or [patches, embed_dim]
|
| 83 |
+
|
| 84 |
+
def _forward(self, x: Tensor, rope=None) -> Tensor:
|
| 85 |
+
"""
|
| 86 |
+
This is the reference implementation for a single tensor, matching what is done below for a list.
|
| 87 |
+
We call the list op on [x] instead of this function.
|
| 88 |
+
"""
|
| 89 |
+
b, _, _ = x.shape
|
| 90 |
+
sample_subset_size = max(int(b * (1 - self.sample_drop_ratio)), 1)
|
| 91 |
+
residual_scale_factor = b / sample_subset_size
|
| 92 |
+
|
| 93 |
+
if self.training and self.sample_drop_ratio > 0.0:
|
| 94 |
+
indices_1 = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 95 |
+
|
| 96 |
+
x_subset_1 = x[indices_1]
|
| 97 |
+
rope_subset = self._maybe_index_rope(rope, indices_1)
|
| 98 |
+
residual_1 = self.attn(self.norm1(x_subset_1), rope=rope_subset)
|
| 99 |
+
|
| 100 |
+
x_attn = torch.index_add(
|
| 101 |
+
x,
|
| 102 |
+
dim=0,
|
| 103 |
+
source=self.ls1(residual_1),
|
| 104 |
+
index=indices_1,
|
| 105 |
+
alpha=residual_scale_factor,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
indices_2 = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 109 |
+
|
| 110 |
+
x_subset_2 = x_attn[indices_2]
|
| 111 |
+
residual_2 = self.mlp(self.norm2(x_subset_2))
|
| 112 |
+
|
| 113 |
+
x_ffn = torch.index_add(
|
| 114 |
+
x_attn,
|
| 115 |
+
dim=0,
|
| 116 |
+
source=self.ls2(residual_2),
|
| 117 |
+
index=indices_2,
|
| 118 |
+
alpha=residual_scale_factor,
|
| 119 |
+
)
|
| 120 |
+
else:
|
| 121 |
+
x_attn = x + self.ls1(self.attn(self.norm1(x), rope=rope))
|
| 122 |
+
x_ffn = x_attn + self.ls2(self.mlp(self.norm2(x_attn)))
|
| 123 |
+
|
| 124 |
+
return x_ffn
|
| 125 |
+
|
| 126 |
+
def _forward_list(self, x_list: List[Tensor], rope_list=None) -> List[Tensor]:
|
| 127 |
+
"""
|
| 128 |
+
This list operator concatenates the tokens from the list of inputs together to save
|
| 129 |
+
on the elementwise operations. Torch-compile memory-planning allows hiding the overhead
|
| 130 |
+
related to concat ops.
|
| 131 |
+
"""
|
| 132 |
+
b_list = [x.shape[0] for x in x_list]
|
| 133 |
+
sample_subset_sizes = [max(int(b * (1 - self.sample_drop_ratio)), 1) for b in b_list]
|
| 134 |
+
residual_scale_factors = [b / sample_subset_size for b, sample_subset_size in zip(b_list, sample_subset_sizes)]
|
| 135 |
+
|
| 136 |
+
if self.training and self.sample_drop_ratio > 0.0:
|
| 137 |
+
indices_1_list = [
|
| 138 |
+
(torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 139 |
+
for x, b, sample_subset_size in zip(x_list, b_list, sample_subset_sizes)
|
| 140 |
+
]
|
| 141 |
+
x_subset_1_list = [x[indices_1] for x, indices_1 in zip(x_list, indices_1_list)]
|
| 142 |
+
|
| 143 |
+
if rope_list is not None:
|
| 144 |
+
rope_subset_list = [
|
| 145 |
+
self._maybe_index_rope(rope, indices_1) for rope, indices_1 in zip(rope_list, indices_1_list)
|
| 146 |
+
]
|
| 147 |
+
else:
|
| 148 |
+
rope_subset_list = rope_list
|
| 149 |
+
|
| 150 |
+
flattened, shapes, num_tokens = cat_keep_shapes(x_subset_1_list)
|
| 151 |
+
norm1 = uncat_with_shapes(self.norm1(flattened), shapes, num_tokens)
|
| 152 |
+
residual_1_list = self.attn.forward_list(norm1, rope_list=rope_subset_list)
|
| 153 |
+
|
| 154 |
+
x_attn_list = [
|
| 155 |
+
torch.index_add(
|
| 156 |
+
x,
|
| 157 |
+
dim=0,
|
| 158 |
+
source=self.ls1(residual_1),
|
| 159 |
+
index=indices_1,
|
| 160 |
+
alpha=residual_scale_factor,
|
| 161 |
+
)
|
| 162 |
+
for x, residual_1, indices_1, residual_scale_factor in zip(
|
| 163 |
+
x_list, residual_1_list, indices_1_list, residual_scale_factors
|
| 164 |
+
)
|
| 165 |
+
]
|
| 166 |
+
|
| 167 |
+
indices_2_list = [
|
| 168 |
+
(torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 169 |
+
for x, b, sample_subset_size in zip(x_list, b_list, sample_subset_sizes)
|
| 170 |
+
]
|
| 171 |
+
x_subset_2_list = [x[indices_2] for x, indices_2 in zip(x_attn_list, indices_2_list)]
|
| 172 |
+
flattened, shapes, num_tokens = cat_keep_shapes(x_subset_2_list)
|
| 173 |
+
norm2_flat = self.norm2(flattened)
|
| 174 |
+
norm2_list = uncat_with_shapes(norm2_flat, shapes, num_tokens)
|
| 175 |
+
|
| 176 |
+
residual_2_list = self.mlp.forward_list(norm2_list)
|
| 177 |
+
|
| 178 |
+
x_ffn = [
|
| 179 |
+
torch.index_add(
|
| 180 |
+
x_attn,
|
| 181 |
+
dim=0,
|
| 182 |
+
source=self.ls2(residual_2),
|
| 183 |
+
index=indices_2,
|
| 184 |
+
alpha=residual_scale_factor,
|
| 185 |
+
)
|
| 186 |
+
for x_attn, residual_2, indices_2, residual_scale_factor in zip(
|
| 187 |
+
x_attn_list, residual_2_list, indices_2_list, residual_scale_factors
|
| 188 |
+
)
|
| 189 |
+
]
|
| 190 |
+
else:
|
| 191 |
+
x_out = []
|
| 192 |
+
for x, rope in zip(x_list, rope_list):
|
| 193 |
+
x_attn = x + self.ls1(self.attn(self.norm1(x), rope=rope))
|
| 194 |
+
x_ffn = x_attn + self.ls2(self.mlp(self.norm2(x_attn)))
|
| 195 |
+
x_out.append(x_ffn)
|
| 196 |
+
x_ffn = x_out
|
| 197 |
+
|
| 198 |
+
return x_ffn
|
| 199 |
+
|
| 200 |
+
def forward(self, x_or_x_list, rope_or_rope_list=None) -> List[Tensor]:
|
| 201 |
+
if isinstance(x_or_x_list, Tensor):
|
| 202 |
+
# for reference:
|
| 203 |
+
# return self._forward(x_or_x_list, rope=rope_or_rope_list)
|
| 204 |
+
# in order to match implementations we call the list op:
|
| 205 |
+
return self._forward_list([x_or_x_list], rope_list=[rope_or_rope_list])[0]
|
| 206 |
+
elif isinstance(x_or_x_list, list):
|
| 207 |
+
if rope_or_rope_list is None:
|
| 208 |
+
rope_or_rope_list = [None for x in x_or_x_list]
|
| 209 |
+
# return [self._forward(x, rope=rope) for x, rope in zip(x_or_x_list, rope_or_rope_list)]
|
| 210 |
+
return self._forward_list(x_or_x_list, rope_list=rope_or_rope_list)
|
| 211 |
+
else:
|
| 212 |
+
raise AssertionError
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class CausalSelfAttentionBlock(nn.Module):
|
| 216 |
+
def __init__(
|
| 217 |
+
self,
|
| 218 |
+
dim: int,
|
| 219 |
+
num_heads: int,
|
| 220 |
+
ffn_ratio: float = 4.0,
|
| 221 |
+
ls_init_value: Optional[float] = None,
|
| 222 |
+
is_causal: bool = True,
|
| 223 |
+
act_layer: Callable = nn.GELU,
|
| 224 |
+
norm_layer: Callable = nn.LayerNorm,
|
| 225 |
+
dropout_prob: float = 0.0,
|
| 226 |
+
):
|
| 227 |
+
super().__init__()
|
| 228 |
+
|
| 229 |
+
self.dim = dim
|
| 230 |
+
self.is_causal = is_causal
|
| 231 |
+
self.ls1 = LayerScale(dim, init_values=ls_init_value) if ls_init_value else nn.Identity()
|
| 232 |
+
self.attention_norm = norm_layer(dim)
|
| 233 |
+
self.attention = CausalSelfAttention(dim, num_heads, attn_drop=dropout_prob, proj_drop=dropout_prob)
|
| 234 |
+
|
| 235 |
+
self.ffn_norm = norm_layer(dim)
|
| 236 |
+
ffn_hidden_dim = int(dim * ffn_ratio)
|
| 237 |
+
self.feed_forward = Mlp(
|
| 238 |
+
in_features=dim,
|
| 239 |
+
hidden_features=ffn_hidden_dim,
|
| 240 |
+
drop=dropout_prob,
|
| 241 |
+
act_layer=act_layer,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
self.ls2 = LayerScale(dim, init_values=ls_init_value) if ls_init_value else nn.Identity()
|
| 245 |
+
|
| 246 |
+
def init_weights(
|
| 247 |
+
self,
|
| 248 |
+
init_attn_std: float | None = None,
|
| 249 |
+
init_proj_std: float | None = None,
|
| 250 |
+
init_fc_std: float | None = None,
|
| 251 |
+
factor: float = 1.0,
|
| 252 |
+
) -> None:
|
| 253 |
+
init_attn_std = init_attn_std or (self.dim**-0.5)
|
| 254 |
+
init_proj_std = init_proj_std or init_attn_std * factor
|
| 255 |
+
init_fc_std = init_fc_std or (2 * self.dim) ** -0.5
|
| 256 |
+
self.attention.init_weights(init_attn_std, init_proj_std)
|
| 257 |
+
self.attention_norm.reset_parameters()
|
| 258 |
+
nn.init.normal_(self.feed_forward.fc1.weight, std=init_fc_std)
|
| 259 |
+
nn.init.normal_(self.feed_forward.fc2.weight, std=init_proj_std)
|
| 260 |
+
self.ffn_norm.reset_parameters()
|
| 261 |
+
|
| 262 |
+
def forward(
|
| 263 |
+
self,
|
| 264 |
+
x: torch.Tensor,
|
| 265 |
+
):
|
| 266 |
+
|
| 267 |
+
x_attn = x + self.ls1(self.attention(self.attention_norm(x), self.is_causal))
|
| 268 |
+
x_ffn = x_attn + self.ls2(self.feed_forward(self.ffn_norm(x_attn)))
|
| 269 |
+
return x_ffn
|
starVLA/dinov3/dinov3/layers/dino_head.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
from torch.nn.init import trunc_normal_
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DINOHead(nn.Module):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
in_dim,
|
| 15 |
+
out_dim,
|
| 16 |
+
use_bn=False,
|
| 17 |
+
nlayers=3,
|
| 18 |
+
hidden_dim=2048,
|
| 19 |
+
bottleneck_dim=256,
|
| 20 |
+
mlp_bias=True,
|
| 21 |
+
):
|
| 22 |
+
super().__init__()
|
| 23 |
+
nlayers = max(nlayers, 1)
|
| 24 |
+
self.mlp = _build_mlp(
|
| 25 |
+
nlayers,
|
| 26 |
+
in_dim,
|
| 27 |
+
bottleneck_dim,
|
| 28 |
+
hidden_dim=hidden_dim,
|
| 29 |
+
use_bn=use_bn,
|
| 30 |
+
bias=mlp_bias,
|
| 31 |
+
)
|
| 32 |
+
self.last_layer = nn.Linear(bottleneck_dim, out_dim, bias=False)
|
| 33 |
+
|
| 34 |
+
def init_weights(self) -> None:
|
| 35 |
+
self.apply(self._init_weights)
|
| 36 |
+
|
| 37 |
+
def _init_weights(self, m):
|
| 38 |
+
if isinstance(m, nn.Linear):
|
| 39 |
+
trunc_normal_(m.weight, std=0.02)
|
| 40 |
+
if m.bias is not None:
|
| 41 |
+
nn.init.constant_(m.bias, 0)
|
| 42 |
+
|
| 43 |
+
def forward(self, x, no_last_layer=False, only_last_layer=False):
|
| 44 |
+
if not only_last_layer:
|
| 45 |
+
x = self.mlp(x)
|
| 46 |
+
eps = 1e-6 if x.dtype == torch.float16 else 1e-12
|
| 47 |
+
x = nn.functional.normalize(x, dim=-1, p=2, eps=eps)
|
| 48 |
+
if not no_last_layer:
|
| 49 |
+
x = self.last_layer(x)
|
| 50 |
+
return x
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True):
|
| 54 |
+
if nlayers == 1:
|
| 55 |
+
return nn.Linear(in_dim, bottleneck_dim, bias=bias)
|
| 56 |
+
else:
|
| 57 |
+
layers = [nn.Linear(in_dim, hidden_dim, bias=bias)]
|
| 58 |
+
if use_bn:
|
| 59 |
+
layers.append(nn.BatchNorm1d(hidden_dim))
|
| 60 |
+
layers.append(nn.GELU())
|
| 61 |
+
for _ in range(nlayers - 2):
|
| 62 |
+
layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias))
|
| 63 |
+
if use_bn:
|
| 64 |
+
layers.append(nn.BatchNorm1d(hidden_dim))
|
| 65 |
+
layers.append(nn.GELU())
|
| 66 |
+
layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias))
|
| 67 |
+
return nn.Sequential(*layers)
|
starVLA/dinov3/dinov3/layers/ffn_layers.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from typing import Callable, List, Optional
|
| 7 |
+
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
|
| 11 |
+
from dinov3.utils import cat_keep_shapes, uncat_with_shapes
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ListForwardMixin(object):
|
| 15 |
+
def forward(self, x: Tensor):
|
| 16 |
+
raise NotImplementedError
|
| 17 |
+
|
| 18 |
+
def forward_list(self, x_list: List[Tensor]) -> List[Tensor]:
|
| 19 |
+
x_flat, shapes, num_tokens = cat_keep_shapes(x_list)
|
| 20 |
+
x_flat = self.forward(x_flat)
|
| 21 |
+
return uncat_with_shapes(x_flat, shapes, num_tokens)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Mlp(nn.Module, ListForwardMixin):
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
in_features: int,
|
| 28 |
+
hidden_features: Optional[int] = None,
|
| 29 |
+
out_features: Optional[int] = None,
|
| 30 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 31 |
+
drop: float = 0.0,
|
| 32 |
+
bias: bool = True,
|
| 33 |
+
device=None,
|
| 34 |
+
) -> None:
|
| 35 |
+
super().__init__()
|
| 36 |
+
out_features = out_features or in_features
|
| 37 |
+
hidden_features = hidden_features or in_features
|
| 38 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias, device=device)
|
| 39 |
+
self.act = act_layer()
|
| 40 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias, device=device)
|
| 41 |
+
self.drop = nn.Dropout(drop)
|
| 42 |
+
|
| 43 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 44 |
+
x = self.fc1(x)
|
| 45 |
+
x = self.act(x)
|
| 46 |
+
x = self.drop(x)
|
| 47 |
+
x = self.fc2(x)
|
| 48 |
+
x = self.drop(x)
|
| 49 |
+
return x
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class SwiGLUFFN(nn.Module, ListForwardMixin):
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
in_features: int,
|
| 56 |
+
hidden_features: Optional[int] = None,
|
| 57 |
+
out_features: Optional[int] = None,
|
| 58 |
+
act_layer: Optional[Callable[..., nn.Module]] = None,
|
| 59 |
+
drop: float = 0.0,
|
| 60 |
+
bias: bool = True,
|
| 61 |
+
align_to: int = 8,
|
| 62 |
+
device=None,
|
| 63 |
+
) -> None:
|
| 64 |
+
super().__init__()
|
| 65 |
+
out_features = out_features or in_features
|
| 66 |
+
hidden_features = hidden_features or in_features
|
| 67 |
+
d = int(hidden_features * 2 / 3)
|
| 68 |
+
swiglu_hidden_features = d + (-d % align_to)
|
| 69 |
+
self.w1 = nn.Linear(in_features, swiglu_hidden_features, bias=bias, device=device)
|
| 70 |
+
self.w2 = nn.Linear(in_features, swiglu_hidden_features, bias=bias, device=device)
|
| 71 |
+
self.w3 = nn.Linear(swiglu_hidden_features, out_features, bias=bias, device=device)
|
| 72 |
+
|
| 73 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 74 |
+
x1 = self.w1(x)
|
| 75 |
+
x2 = self.w2(x)
|
| 76 |
+
hidden = F.silu(x1) * x2
|
| 77 |
+
return self.w3(hidden)
|
starVLA/dinov3/dinov3/layers/fp8_linear.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from dinov3.layers.attention import LinearKMaskedBias
|
| 11 |
+
from dinov3.utils import named_replace
|
| 12 |
+
|
| 13 |
+
# avoid division by zero when calculating scale
|
| 14 |
+
EPS = 1e-12
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def scale(t, amax_t):
|
| 18 |
+
max_v = torch.finfo(torch.float8_e4m3fn).max
|
| 19 |
+
scale_t = torch.clamp(amax_t.float(), min=EPS) / max_v
|
| 20 |
+
t_fp8 = (t / scale_t).to(torch.float8_e4m3fn)
|
| 21 |
+
return t_fp8, scale_t
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def matmul(first, amax_first, second_t, amax_second_t, bias):
|
| 25 |
+
first_fp8, scale_first = scale(first, amax_first)
|
| 26 |
+
second_t_fp8, scale_second_t = scale(second_t, amax_second_t)
|
| 27 |
+
# PyTorch's row-wise scaled matmul kernel is based on CUTLASS and is quite
|
| 28 |
+
# slow. Hence we fall back to an "unscaled" matmul, which uses cuBLAS, and
|
| 29 |
+
# apply the scale manually afterwards.
|
| 30 |
+
output = torch._scaled_mm(
|
| 31 |
+
first_fp8,
|
| 32 |
+
second_t_fp8.t(),
|
| 33 |
+
scale_a=scale_first.new_ones((1, 1)),
|
| 34 |
+
scale_b=scale_second_t.t().new_ones((1, 1)),
|
| 35 |
+
bias=None,
|
| 36 |
+
out_dtype=torch.bfloat16,
|
| 37 |
+
use_fast_accum=False,
|
| 38 |
+
)
|
| 39 |
+
output = (output * scale_first * scale_second_t.t()).to(torch.bfloat16)
|
| 40 |
+
if bias is not None:
|
| 41 |
+
output = output + bias
|
| 42 |
+
return output
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@torch.compiler.allow_in_graph
|
| 46 |
+
class Fp8LinearFn(torch.autograd.Function):
|
| 47 |
+
@staticmethod
|
| 48 |
+
def forward(ctx, a, b_t, bias):
|
| 49 |
+
amax_a = a.abs().amax(dim=-1, keepdim=True)
|
| 50 |
+
amax_b_t = b_t.abs().amax(dim=-1, keepdim=True)
|
| 51 |
+
out = matmul(a, amax_a, b_t, amax_b_t, bias)
|
| 52 |
+
|
| 53 |
+
ctx.a_requires_grad = a.requires_grad
|
| 54 |
+
ctx.b_requires_grad = b_t.requires_grad
|
| 55 |
+
ctx.bias_requires_grad = bias.requires_grad if bias is not None else False
|
| 56 |
+
|
| 57 |
+
ctx.save_for_backward(a, b_t, amax_b_t.max())
|
| 58 |
+
|
| 59 |
+
return out
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def backward(ctx, grad_out):
|
| 63 |
+
a, b_t, amax_b = ctx.saved_tensors
|
| 64 |
+
|
| 65 |
+
if ctx.a_requires_grad:
|
| 66 |
+
b = b_t.t().contiguous()
|
| 67 |
+
amax_grad_out = grad_out.abs().amax(dim=-1, keepdim=True)
|
| 68 |
+
amax_b = amax_b.repeat(b.shape[0], 1)
|
| 69 |
+
grad_a = matmul(grad_out, amax_grad_out, b, amax_b, None)
|
| 70 |
+
else:
|
| 71 |
+
grad_a = None
|
| 72 |
+
if ctx.b_requires_grad:
|
| 73 |
+
grad_b = grad_out.t() @ a
|
| 74 |
+
else:
|
| 75 |
+
grad_b = None
|
| 76 |
+
if ctx.bias_requires_grad:
|
| 77 |
+
grad_bias = grad_out.sum(dim=0)
|
| 78 |
+
else:
|
| 79 |
+
grad_bias = None
|
| 80 |
+
|
| 81 |
+
return grad_a, grad_b, grad_bias
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class Fp8Linear(torch.nn.Linear):
|
| 85 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 86 |
+
out = Fp8LinearFn.apply(input.flatten(end_dim=-2), self.weight, self.bias)
|
| 87 |
+
out = out.unflatten(0, input.shape[:-1])
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class Fp8LinearKMaskedBias(LinearKMaskedBias):
|
| 92 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 93 |
+
masked_bias = self.bias * self.bias_mask if self.bias is not None else None
|
| 94 |
+
out = Fp8LinearFn.apply(input.flatten(end_dim=-2), self.weight, masked_bias)
|
| 95 |
+
out = out.unflatten(0, input.shape[:-1])
|
| 96 |
+
return out
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def convert_linears_to_fp8(root_module: torch.nn.Module, *, filter: str) -> torch.nn.Module:
|
| 100 |
+
filter_re = re.compile(filter)
|
| 101 |
+
total_count = 0
|
| 102 |
+
|
| 103 |
+
def replace(module: torch.nn.Module, name: str) -> torch.nn.Module:
|
| 104 |
+
nonlocal total_count
|
| 105 |
+
if not isinstance(module, torch.nn.Linear) or not filter_re.search(name):
|
| 106 |
+
return module
|
| 107 |
+
if type(module) == torch.nn.Linear:
|
| 108 |
+
new_cls = Fp8Linear
|
| 109 |
+
elif type(module) == LinearKMaskedBias:
|
| 110 |
+
new_cls = Fp8LinearKMaskedBias
|
| 111 |
+
else:
|
| 112 |
+
assert False, str(type(module))
|
| 113 |
+
if module.in_features % 64 != 0 or module.out_features % 64 != 0:
|
| 114 |
+
# This is not a strict requirement, but H100 TensorCores for fp8
|
| 115 |
+
# operate on tiles of 64 elements anyways, and Inductor sometimes
|
| 116 |
+
# pads inner dims to become multiples of 64. Also, if one day we
|
| 117 |
+
# switch back to cuBLAS, it artificially requires dims to be
|
| 118 |
+
# multiples of 16.
|
| 119 |
+
raise RuntimeError(
|
| 120 |
+
"fp8 requires all dimensions to be multiples of 64 " "(consider using ffn_layer=swiglu64 or higher)"
|
| 121 |
+
)
|
| 122 |
+
new_module = new_cls(
|
| 123 |
+
in_features=module.in_features,
|
| 124 |
+
out_features=module.out_features,
|
| 125 |
+
bias=module.bias is not None,
|
| 126 |
+
dtype=module.weight.dtype,
|
| 127 |
+
device=module.weight.device,
|
| 128 |
+
)
|
| 129 |
+
new_module.weight = module.weight
|
| 130 |
+
new_module.bias = module.bias
|
| 131 |
+
total_count += 1
|
| 132 |
+
return new_module
|
| 133 |
+
|
| 134 |
+
out = named_replace(replace, root_module)
|
| 135 |
+
assert total_count > 0, "fp8: no layer found to convert"
|
| 136 |
+
# Force re-compile everything
|
| 137 |
+
torch._dynamo.reset_code_caches()
|
| 138 |
+
from torch._inductor.cudagraph_trees import reset_cudagraph_trees
|
| 139 |
+
|
| 140 |
+
reset_cudagraph_trees()
|
| 141 |
+
return out
|
starVLA/dinov3/dinov3/layers/layer_scale.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from typing import Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class LayerScale(nn.Module):
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
dim: int,
|
| 16 |
+
init_values: Union[float, Tensor] = 1e-5,
|
| 17 |
+
inplace: bool = False,
|
| 18 |
+
device=None,
|
| 19 |
+
) -> None:
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.inplace = inplace
|
| 22 |
+
self.gamma = nn.Parameter(torch.empty(dim, device=device))
|
| 23 |
+
self.init_values = init_values
|
| 24 |
+
|
| 25 |
+
def reset_parameters(self):
|
| 26 |
+
nn.init.constant_(self.gamma, self.init_values)
|
| 27 |
+
|
| 28 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 29 |
+
return x.mul_(self.gamma) if self.inplace else x * self.gamma
|
starVLA/dinov3/dinov3/layers/patch_embed.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from typing import Callable, Tuple, Union
|
| 8 |
+
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def make_2tuple(x):
|
| 13 |
+
if isinstance(x, tuple):
|
| 14 |
+
assert len(x) == 2
|
| 15 |
+
return x
|
| 16 |
+
|
| 17 |
+
assert isinstance(x, int)
|
| 18 |
+
return (x, x)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class PatchEmbed(nn.Module):
|
| 22 |
+
"""
|
| 23 |
+
2D image to patch embedding: (B,C,H,W) -> (B,N,D)
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
img_size: Image size.
|
| 27 |
+
patch_size: Patch token size.
|
| 28 |
+
in_chans: Number of input image channels.
|
| 29 |
+
embed_dim: Number of linear projection output channels.
|
| 30 |
+
norm_layer: Normalization layer.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
img_size: Union[int, Tuple[int, int]] = 224,
|
| 36 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
| 37 |
+
in_chans: int = 3,
|
| 38 |
+
embed_dim: int = 768,
|
| 39 |
+
norm_layer: Callable | None = None,
|
| 40 |
+
flatten_embedding: bool = True,
|
| 41 |
+
) -> None:
|
| 42 |
+
super().__init__()
|
| 43 |
+
|
| 44 |
+
image_HW = make_2tuple(img_size)
|
| 45 |
+
patch_HW = make_2tuple(patch_size)
|
| 46 |
+
patch_grid_size = (
|
| 47 |
+
image_HW[0] // patch_HW[0],
|
| 48 |
+
image_HW[1] // patch_HW[1],
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
self.img_size = image_HW
|
| 52 |
+
self.patch_size = patch_HW
|
| 53 |
+
self.patches_resolution = patch_grid_size
|
| 54 |
+
self.num_patches = patch_grid_size[0] * patch_grid_size[1]
|
| 55 |
+
|
| 56 |
+
self.in_chans = in_chans
|
| 57 |
+
self.embed_dim = embed_dim
|
| 58 |
+
|
| 59 |
+
self.flatten_embedding = flatten_embedding
|
| 60 |
+
|
| 61 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
|
| 62 |
+
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
|
| 63 |
+
|
| 64 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 65 |
+
_, _, H, W = x.shape
|
| 66 |
+
# patch_H, patch_W = self.patch_size
|
| 67 |
+
# assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
|
| 68 |
+
# assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
|
| 69 |
+
|
| 70 |
+
x = self.proj(x) # B C H W
|
| 71 |
+
H, W = x.size(2), x.size(3)
|
| 72 |
+
x = x.flatten(2).transpose(1, 2) # B HW C
|
| 73 |
+
x = self.norm(x)
|
| 74 |
+
if not self.flatten_embedding:
|
| 75 |
+
x = x.reshape(-1, H, W, self.embed_dim) # B H W C
|
| 76 |
+
return x
|
| 77 |
+
|
| 78 |
+
def flops(self) -> float:
|
| 79 |
+
Ho, Wo = self.patches_resolution
|
| 80 |
+
flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
|
| 81 |
+
if self.norm is not None:
|
| 82 |
+
flops += Ho * Wo * self.embed_dim
|
| 83 |
+
return flops
|
| 84 |
+
|
| 85 |
+
def reset_parameters(self):
|
| 86 |
+
k = 1 / (self.in_chans * (self.patch_size[0] ** 2))
|
| 87 |
+
nn.init.uniform_(self.proj.weight, -math.sqrt(k), math.sqrt(k))
|
| 88 |
+
if self.proj.bias is not None:
|
| 89 |
+
nn.init.uniform_(self.proj.bias, -math.sqrt(k), math.sqrt(k))
|
starVLA/dinov3/dinov3/layers/rms_norm.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor, nn
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class RMSNorm(nn.Module):
|
| 11 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 14 |
+
self.eps = eps
|
| 15 |
+
|
| 16 |
+
def reset_parameters(self) -> None:
|
| 17 |
+
nn.init.constant_(self.weight, 1)
|
| 18 |
+
|
| 19 |
+
def _norm(self, x: Tensor) -> Tensor:
|
| 20 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 21 |
+
|
| 22 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 23 |
+
output = self._norm(x.float()).type_as(x)
|
| 24 |
+
return output * self.weight
|
starVLA/dinov3/dinov3/layers/rope_position_encoding.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from typing import Literal
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from torch import Tensor, nn
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# RoPE positional embedding with no mixing of coordinates (axial) and no learnable weights
|
| 15 |
+
# Supports two parametrizations of the rope parameters: either using `base` or `min_period` and `max_period`.
|
| 16 |
+
class RopePositionEmbedding(nn.Module):
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
embed_dim: int,
|
| 20 |
+
*,
|
| 21 |
+
num_heads: int,
|
| 22 |
+
base: float | None = 100.0,
|
| 23 |
+
min_period: float | None = None,
|
| 24 |
+
max_period: float | None = None,
|
| 25 |
+
normalize_coords: Literal["min", "max", "separate"] = "separate",
|
| 26 |
+
shift_coords: float | None = None,
|
| 27 |
+
jitter_coords: float | None = None,
|
| 28 |
+
rescale_coords: float | None = None,
|
| 29 |
+
dtype: torch.dtype | None = None,
|
| 30 |
+
device: torch.device | None = None,
|
| 31 |
+
):
|
| 32 |
+
super().__init__()
|
| 33 |
+
assert embed_dim % (4 * num_heads) == 0
|
| 34 |
+
both_periods = min_period is not None and max_period is not None
|
| 35 |
+
if (base is None and not both_periods) or (base is not None and both_periods):
|
| 36 |
+
raise ValueError("Either `base` or `min_period`+`max_period` must be provided.")
|
| 37 |
+
|
| 38 |
+
D_head = embed_dim // num_heads
|
| 39 |
+
self.base = base
|
| 40 |
+
self.min_period = min_period
|
| 41 |
+
self.max_period = max_period
|
| 42 |
+
self.D_head = D_head
|
| 43 |
+
self.normalize_coords = normalize_coords
|
| 44 |
+
self.shift_coords = shift_coords
|
| 45 |
+
self.jitter_coords = jitter_coords
|
| 46 |
+
self.rescale_coords = rescale_coords
|
| 47 |
+
|
| 48 |
+
# Needs persistent=True because we do teacher.load_state_dict(student.state_dict()) to initialize the teacher
|
| 49 |
+
self.dtype = dtype # Don't rely on self.periods.dtype
|
| 50 |
+
self.register_buffer(
|
| 51 |
+
"periods",
|
| 52 |
+
torch.empty(D_head // 4, device=device, dtype=dtype),
|
| 53 |
+
persistent=True,
|
| 54 |
+
)
|
| 55 |
+
self._init_weights()
|
| 56 |
+
|
| 57 |
+
def forward(self, *, H: int, W: int) -> tuple[Tensor, Tensor]:
|
| 58 |
+
device = self.periods.device
|
| 59 |
+
dtype = self.dtype
|
| 60 |
+
dd = {"device": device, "dtype": dtype}
|
| 61 |
+
|
| 62 |
+
# Prepare coords in range [-1, +1]
|
| 63 |
+
if self.normalize_coords == "max":
|
| 64 |
+
max_HW = max(H, W)
|
| 65 |
+
coords_h = torch.arange(0.5, H, **dd) / max_HW # [H]
|
| 66 |
+
coords_w = torch.arange(0.5, W, **dd) / max_HW # [W]
|
| 67 |
+
elif self.normalize_coords == "min":
|
| 68 |
+
min_HW = min(H, W)
|
| 69 |
+
coords_h = torch.arange(0.5, H, **dd) / min_HW # [H]
|
| 70 |
+
coords_w = torch.arange(0.5, W, **dd) / min_HW # [W]
|
| 71 |
+
elif self.normalize_coords == "separate":
|
| 72 |
+
coords_h = torch.arange(0.5, H, **dd) / H # [H]
|
| 73 |
+
coords_w = torch.arange(0.5, W, **dd) / W # [W]
|
| 74 |
+
else:
|
| 75 |
+
raise ValueError(f"Unknown normalize_coords: {self.normalize_coords}")
|
| 76 |
+
coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1) # [H, W, 2]
|
| 77 |
+
coords = coords.flatten(0, 1) # [HW, 2]
|
| 78 |
+
coords = 2.0 * coords - 1.0 # Shift range [0, 1] to [-1, +1]
|
| 79 |
+
|
| 80 |
+
# Shift coords by adding a uniform value in [-shift, shift]
|
| 81 |
+
if self.training and self.shift_coords is not None:
|
| 82 |
+
shift_hw = torch.empty(2, **dd).uniform_(-self.shift_coords, self.shift_coords)
|
| 83 |
+
coords += shift_hw[None, :]
|
| 84 |
+
|
| 85 |
+
# Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter]
|
| 86 |
+
if self.training and self.jitter_coords is not None:
|
| 87 |
+
jitter_max = np.log(self.jitter_coords)
|
| 88 |
+
jitter_min = -jitter_max
|
| 89 |
+
jitter_hw = torch.empty(2, **dd).uniform_(jitter_min, jitter_max).exp()
|
| 90 |
+
coords *= jitter_hw[None, :]
|
| 91 |
+
|
| 92 |
+
# Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale]
|
| 93 |
+
if self.training and self.rescale_coords is not None:
|
| 94 |
+
rescale_max = np.log(self.rescale_coords)
|
| 95 |
+
rescale_min = -rescale_max
|
| 96 |
+
rescale_hw = torch.empty(1, **dd).uniform_(rescale_min, rescale_max).exp()
|
| 97 |
+
coords *= rescale_hw
|
| 98 |
+
|
| 99 |
+
# Prepare angles and sin/cos
|
| 100 |
+
angles = 2 * math.pi * coords[:, :, None] / self.periods[None, None, :] # [HW, 2, D//4]
|
| 101 |
+
angles = angles.flatten(1, 2) # [HW, D//2]
|
| 102 |
+
angles = angles.tile(2) # [HW, D]
|
| 103 |
+
cos = torch.cos(angles) # [HW, D]
|
| 104 |
+
sin = torch.sin(angles) # [HW, D]
|
| 105 |
+
|
| 106 |
+
return (sin, cos) # 2 * [HW, D]
|
| 107 |
+
|
| 108 |
+
def _init_weights(self):
|
| 109 |
+
device = self.periods.device
|
| 110 |
+
dtype = self.dtype
|
| 111 |
+
if self.base is not None:
|
| 112 |
+
periods = self.base ** (
|
| 113 |
+
2 * torch.arange(self.D_head // 4, device=device, dtype=dtype) / (self.D_head // 2)
|
| 114 |
+
) # [D//4]
|
| 115 |
+
else:
|
| 116 |
+
base = self.max_period / self.min_period
|
| 117 |
+
exponents = torch.linspace(0, 1, self.D_head // 4, device=device, dtype=dtype) # [D//4] range [0, 1]
|
| 118 |
+
periods = base**exponents # range [1, max_period / min_period]
|
| 119 |
+
periods = periods / base # range [min_period / max_period, 1]
|
| 120 |
+
periods = periods * self.max_period # range [min_period, max_period]
|
| 121 |
+
self.periods.data = periods
|
starVLA/dinov3/dinov3/layers/sparse_linear.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from typing import Callable
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import xformers.ops as xops
|
| 13 |
+
|
| 14 |
+
from dinov3.utils import named_apply, named_replace
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger("dinov3")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class LinearW24(torch.nn.Linear):
|
| 20 |
+
ALGO = "largest_abs_values_greedy"
|
| 21 |
+
|
| 22 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 23 |
+
super().__init__(*args, **kwargs)
|
| 24 |
+
self.sparsity_enabled = False
|
| 25 |
+
|
| 26 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 27 |
+
if not self.sparsity_enabled:
|
| 28 |
+
return super().forward(input)
|
| 29 |
+
|
| 30 |
+
input_shape = input.shape
|
| 31 |
+
input = input.flatten(end_dim=-2)
|
| 32 |
+
dim0 = input.shape[0]
|
| 33 |
+
if dim0 % 8 != 0:
|
| 34 |
+
# NOTE: This should be torch-compiled away
|
| 35 |
+
input = F.pad(input, [0, 0, 0, -dim0 % 8])
|
| 36 |
+
w_sparse = xops.sparsify24(
|
| 37 |
+
self.weight,
|
| 38 |
+
algo=self.ALGO,
|
| 39 |
+
gradient="ste",
|
| 40 |
+
backend="cusparselt",
|
| 41 |
+
)
|
| 42 |
+
return F.linear(input, w_sparse, self.bias,)[
|
| 43 |
+
:dim0
|
| 44 |
+
].unflatten(dim=0, sizes=input_shape[:-1])
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def replace_linears_with_sparse_linear(root_module: nn.Module, *, filter_fn: Callable[[str], bool]) -> nn.Module:
|
| 48 |
+
total_count = 0
|
| 49 |
+
|
| 50 |
+
def replace(module: nn.Module, name: str) -> nn.Module:
|
| 51 |
+
nonlocal total_count
|
| 52 |
+
if not isinstance(module, nn.Linear) or not filter_fn(name):
|
| 53 |
+
return module
|
| 54 |
+
assert type(module) == nn.Linear, "Subtypes not supported"
|
| 55 |
+
new_module = LinearW24(
|
| 56 |
+
in_features=module.in_features,
|
| 57 |
+
out_features=module.out_features,
|
| 58 |
+
bias=module.bias is not None,
|
| 59 |
+
dtype=module.weight.dtype,
|
| 60 |
+
device=module.weight.device,
|
| 61 |
+
)
|
| 62 |
+
new_module.weight = module.weight
|
| 63 |
+
new_module.bias = module.bias
|
| 64 |
+
total_count += 1
|
| 65 |
+
return new_module
|
| 66 |
+
|
| 67 |
+
out = named_replace(replace, root_module)
|
| 68 |
+
assert total_count > 0, "2:4 sparsity: no layer found to sparsify"
|
| 69 |
+
return out
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def update_24sparsity(root_module: nn.Module, enabled: bool) -> int:
|
| 73 |
+
num_modified = 0
|
| 74 |
+
|
| 75 |
+
def maybe_apply_sparsity(module: nn.Module, name: str) -> nn.Module:
|
| 76 |
+
nonlocal num_modified
|
| 77 |
+
if not isinstance(module, LinearW24):
|
| 78 |
+
return module
|
| 79 |
+
num_modified += 1
|
| 80 |
+
module.sparsity_enabled = enabled
|
| 81 |
+
logger.info(f"- {'' if module.sparsity_enabled else 'de'}sparsifying {name}")
|
| 82 |
+
return module
|
| 83 |
+
|
| 84 |
+
named_apply(maybe_apply_sparsity, root_module)
|
| 85 |
+
# Force re-compile everything
|
| 86 |
+
torch._dynamo.reset_code_caches()
|
| 87 |
+
from torch._inductor.cudagraph_trees import reset_cudagraph_trees
|
| 88 |
+
|
| 89 |
+
reset_cudagraph_trees()
|
| 90 |
+
return num_modified
|
starVLA/dinov3/dinov3/logging/__init__.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import functools
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
from termcolor import colored
|
| 13 |
+
|
| 14 |
+
from dinov3.distributed import TorchDistributedEnvironment
|
| 15 |
+
|
| 16 |
+
from dinov3.logging.helpers import MetricLogger, SmoothedValue
|
| 17 |
+
|
| 18 |
+
_LEVEL_COLORED_KWARGS = {
|
| 19 |
+
logging.DEBUG: {"color": "green", "attrs": ["bold"]},
|
| 20 |
+
logging.INFO: {"color": "green"},
|
| 21 |
+
logging.WARNING: {"color": "yellow"},
|
| 22 |
+
logging.ERROR: {"color": "red"},
|
| 23 |
+
logging.CRITICAL: {"color": "red", "attrs": ["bold"]},
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class _LevelColoredFormatter(logging.Formatter):
|
| 28 |
+
def __init__(self, *args, **kwargs):
|
| 29 |
+
super().__init__(*args, **kwargs)
|
| 30 |
+
|
| 31 |
+
def formatMessage(self, record):
|
| 32 |
+
log = super().formatMessage(record)
|
| 33 |
+
|
| 34 |
+
colored_kwargs = _LEVEL_COLORED_KWARGS.get(record.levelno)
|
| 35 |
+
if colored_kwargs is None:
|
| 36 |
+
return log
|
| 37 |
+
|
| 38 |
+
msg = record.msg % record.args if record.msg == "%s" else record.msg
|
| 39 |
+
index = log.rfind(msg, len(log) - len(msg))
|
| 40 |
+
# Can happen in some cases, like if the msg contains `%s` which
|
| 41 |
+
# have been replaced in `formatMessage`. Fallback to no colors
|
| 42 |
+
if index == -1:
|
| 43 |
+
return log
|
| 44 |
+
prefix = log[:index]
|
| 45 |
+
prefix = colored(prefix, **colored_kwargs)
|
| 46 |
+
return prefix + msg
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# So that calling _configure_logger multiple times won't add many handlers
|
| 50 |
+
@functools.lru_cache()
|
| 51 |
+
def _configure_logger(
|
| 52 |
+
name: Optional[str] = None,
|
| 53 |
+
*,
|
| 54 |
+
level: int = logging.DEBUG,
|
| 55 |
+
output: Optional[str] = None,
|
| 56 |
+
color: bool = True,
|
| 57 |
+
log_to_stdout_only_in_main_process: bool = True,
|
| 58 |
+
):
|
| 59 |
+
"""
|
| 60 |
+
Configure a logger.
|
| 61 |
+
|
| 62 |
+
Adapted from Detectron2.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
name: The name of the logger to configure.
|
| 66 |
+
level: The logging level to use.
|
| 67 |
+
output: A file name or a directory to save log. If None, will not save log file.
|
| 68 |
+
If ends with ".txt" or ".log", assumed to be a file name.
|
| 69 |
+
Otherwise, logs will be saved to `output/log.txt`.
|
| 70 |
+
color: Whether stdout output should be colored (ignored if stdout is not a terminal).
|
| 71 |
+
log_to_stdout_only_in_main_process: The main process (rank 0) always logs to stdout,
|
| 72 |
+
regardless of this flag. If False, other ranks will also log to their stdout.
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
The configured logger.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
# Disable colored output if the stdout is not a terminal
|
| 79 |
+
color = color and os.isatty(sys.stdout.fileno())
|
| 80 |
+
|
| 81 |
+
logger = logging.getLogger(name)
|
| 82 |
+
logger.setLevel(level)
|
| 83 |
+
logger.propagate = False
|
| 84 |
+
|
| 85 |
+
# Loosely match Google glog format:
|
| 86 |
+
# [IWEF]yyyymmdd hh:mm:ss.uuuuuu threadid file:line] msg
|
| 87 |
+
# but use a shorter timestamp and include the logger name:
|
| 88 |
+
# [IWEF]yyyymmdd hh:mm:ss logger threadid file:line] msg
|
| 89 |
+
fmt_prefix = "%(levelname).1s%(asctime)s %(process)s %(name)s %(filename)s:%(lineno)s] "
|
| 90 |
+
fmt_message = "%(message)s"
|
| 91 |
+
fmt = fmt_prefix + fmt_message
|
| 92 |
+
datefmt = "%Y%m%d %H:%M:%S"
|
| 93 |
+
plain_formatter = logging.Formatter(fmt=fmt, datefmt=datefmt)
|
| 94 |
+
|
| 95 |
+
torch_env = TorchDistributedEnvironment()
|
| 96 |
+
|
| 97 |
+
# rank 0 always logs to stdout, for other ranks it depends on log_to_stdout_only_in_main_process
|
| 98 |
+
should_log_to_stdout = torch_env.is_main_process or not log_to_stdout_only_in_main_process
|
| 99 |
+
if should_log_to_stdout:
|
| 100 |
+
handler = logging.StreamHandler(stream=sys.stdout)
|
| 101 |
+
handler.setLevel(logging.DEBUG)
|
| 102 |
+
|
| 103 |
+
formatter: logging.Formatter
|
| 104 |
+
if color:
|
| 105 |
+
formatter = _LevelColoredFormatter(
|
| 106 |
+
fmt=fmt,
|
| 107 |
+
datefmt=datefmt,
|
| 108 |
+
)
|
| 109 |
+
else:
|
| 110 |
+
formatter = plain_formatter
|
| 111 |
+
|
| 112 |
+
handler.setFormatter(formatter)
|
| 113 |
+
logger.addHandler(handler)
|
| 114 |
+
|
| 115 |
+
# file logging for all workers
|
| 116 |
+
if output:
|
| 117 |
+
if os.path.splitext(output)[-1] in (".txt", ".log"):
|
| 118 |
+
filename = output
|
| 119 |
+
else:
|
| 120 |
+
filename = os.path.join(output, "logs", "log.txt")
|
| 121 |
+
|
| 122 |
+
if not torch_env.is_main_process:
|
| 123 |
+
filename = filename + f".rank{torch_env.rank}"
|
| 124 |
+
|
| 125 |
+
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
| 126 |
+
|
| 127 |
+
handler = logging.StreamHandler(open(filename, "a"))
|
| 128 |
+
handler.setLevel(logging.DEBUG)
|
| 129 |
+
handler.setFormatter(plain_formatter)
|
| 130 |
+
logger.addHandler(handler)
|
| 131 |
+
|
| 132 |
+
logger.debug(f"PyTorch distributed environment: {torch_env}")
|
| 133 |
+
return logger
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def setup_logging(
|
| 137 |
+
output: Optional[str] = None,
|
| 138 |
+
*,
|
| 139 |
+
name: Optional[str] = None,
|
| 140 |
+
level: int = logging.DEBUG,
|
| 141 |
+
color: bool = True,
|
| 142 |
+
capture_warnings: bool = True,
|
| 143 |
+
log_to_stdout_only_in_main_process: bool = True,
|
| 144 |
+
) -> None:
|
| 145 |
+
"""
|
| 146 |
+
Setup logging.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
output: A file name or a directory to save log files. If None, log
|
| 150 |
+
files will not be saved. If output ends with ".txt" or ".log", it
|
| 151 |
+
is assumed to be a file name.
|
| 152 |
+
Otherwise, logs will be saved to `output/log.txt`.
|
| 153 |
+
name: The name of the logger to configure, by default the root logger.
|
| 154 |
+
level: The logging level to use.
|
| 155 |
+
color: Whether stdout output should be colored (ignored if stdout is not a terminal).
|
| 156 |
+
capture_warnings: Whether warnings should be captured as logs.
|
| 157 |
+
log_to_stdout_only_in_main_process: The main process (rank 0) always logs to stdout,
|
| 158 |
+
regardless of this flag. If False, other ranks will also log to their stdout.
|
| 159 |
+
"""
|
| 160 |
+
logging.captureWarnings(capture_warnings)
|
| 161 |
+
# Ensure the path is canonical to properly use the cache of `_configure_logger`
|
| 162 |
+
output = output if output is None else os.path.realpath(output)
|
| 163 |
+
_configure_logger(
|
| 164 |
+
name,
|
| 165 |
+
level=level,
|
| 166 |
+
output=output,
|
| 167 |
+
color=color,
|
| 168 |
+
log_to_stdout_only_in_main_process=log_to_stdout_only_in_main_process,
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def cleanup_logging(*, name: Optional[str] = None) -> None:
|
| 173 |
+
logger = logging.getLogger(name)
|
| 174 |
+
for handler in logger.handlers:
|
| 175 |
+
handler.flush()
|
| 176 |
+
handler.close()
|
| 177 |
+
logger.removeHandler(handler)
|
| 178 |
+
|
| 179 |
+
# clears the cache of `_configure_logger` to allow re-initialization
|
| 180 |
+
_configure_logger.cache_clear()
|
starVLA/dinov3/dinov3/logging/helpers.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import datetime
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
import time
|
| 10 |
+
from collections import defaultdict, deque
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
import dinov3.distributed as distributed
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger("dinov3")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MetricLogger(object):
|
| 20 |
+
def __init__(self, delimiter="\t", output_file=None):
|
| 21 |
+
self.meters = defaultdict(SmoothedValue)
|
| 22 |
+
self.delimiter = delimiter
|
| 23 |
+
self.output_file = output_file
|
| 24 |
+
|
| 25 |
+
def update(self, **kwargs):
|
| 26 |
+
for k, v in kwargs.items():
|
| 27 |
+
if isinstance(v, torch.Tensor):
|
| 28 |
+
v = v.item()
|
| 29 |
+
assert isinstance(v, (float, int))
|
| 30 |
+
self.meters[k].update(v)
|
| 31 |
+
|
| 32 |
+
def __getattr__(self, attr):
|
| 33 |
+
if attr in self.meters:
|
| 34 |
+
return self.meters[attr]
|
| 35 |
+
if attr in self.__dict__:
|
| 36 |
+
return self.__dict__[attr]
|
| 37 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr))
|
| 38 |
+
|
| 39 |
+
def __str__(self):
|
| 40 |
+
loss_str = []
|
| 41 |
+
for name, meter in self.meters.items():
|
| 42 |
+
loss_str.append("{}: {}".format(name, str(meter)))
|
| 43 |
+
return self.delimiter.join(loss_str)
|
| 44 |
+
|
| 45 |
+
def synchronize_between_processes(self):
|
| 46 |
+
for meter in self.meters.values():
|
| 47 |
+
meter.synchronize_between_processes()
|
| 48 |
+
|
| 49 |
+
def add_meter(self, name, meter):
|
| 50 |
+
self.meters[name] = meter
|
| 51 |
+
|
| 52 |
+
def dump_in_output_file(self, iteration, iter_time, data_time):
|
| 53 |
+
if self.output_file is None or not distributed.is_main_process():
|
| 54 |
+
return
|
| 55 |
+
dict_to_dump = dict(
|
| 56 |
+
iteration=iteration,
|
| 57 |
+
iter_time=iter_time,
|
| 58 |
+
data_time=data_time,
|
| 59 |
+
)
|
| 60 |
+
dict_to_dump.update({k: v.median for k, v in self.meters.items()})
|
| 61 |
+
with open(self.output_file, "a") as f:
|
| 62 |
+
f.write(json.dumps(dict_to_dump) + "\n")
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
def log_every(self, iterable, print_freq, header=None, n_iterations=None, start_iteration=0):
|
| 66 |
+
i = start_iteration
|
| 67 |
+
if not header:
|
| 68 |
+
header = ""
|
| 69 |
+
start_time = time.time()
|
| 70 |
+
end = time.time()
|
| 71 |
+
iter_time = SmoothedValue(fmt="{avg:.6f}")
|
| 72 |
+
data_time = SmoothedValue(fmt="{avg:.6f}")
|
| 73 |
+
|
| 74 |
+
if n_iterations is None:
|
| 75 |
+
n_iterations = len(iterable)
|
| 76 |
+
|
| 77 |
+
space_fmt = ":" + str(len(str(n_iterations))) + "d"
|
| 78 |
+
|
| 79 |
+
log_list = [
|
| 80 |
+
header,
|
| 81 |
+
"[{0" + space_fmt + "}/{1}]",
|
| 82 |
+
"eta: {eta}",
|
| 83 |
+
"{meters}",
|
| 84 |
+
"time: {time}",
|
| 85 |
+
"data: {data}",
|
| 86 |
+
]
|
| 87 |
+
if torch.cuda.is_available():
|
| 88 |
+
log_list += ["mem: {current_memory:.0f}"]
|
| 89 |
+
log_list += ["(max mem: {max_memory:.0f})"]
|
| 90 |
+
|
| 91 |
+
log_msg = self.delimiter.join(log_list)
|
| 92 |
+
MB = 1024.0 * 1024.0
|
| 93 |
+
for obj in iterable:
|
| 94 |
+
if i >= n_iterations:
|
| 95 |
+
break
|
| 96 |
+
|
| 97 |
+
data_time.update(time.time() - end)
|
| 98 |
+
yield obj
|
| 99 |
+
iter_time.update(time.time() - end)
|
| 100 |
+
if i % print_freq == 0 or i == n_iterations - 1:
|
| 101 |
+
self.dump_in_output_file(iteration=i, iter_time=iter_time.avg, data_time=data_time.avg)
|
| 102 |
+
eta_seconds = iter_time.global_avg * (n_iterations - i)
|
| 103 |
+
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
| 104 |
+
if torch.cuda.is_available():
|
| 105 |
+
logger.info(
|
| 106 |
+
log_msg.format(
|
| 107 |
+
i,
|
| 108 |
+
n_iterations,
|
| 109 |
+
eta=eta_string,
|
| 110 |
+
meters=str(self),
|
| 111 |
+
time=str(iter_time),
|
| 112 |
+
data=str(data_time),
|
| 113 |
+
current_memory=torch.cuda.memory_allocated() / MB,
|
| 114 |
+
max_memory=torch.cuda.max_memory_allocated() / MB,
|
| 115 |
+
)
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
logger.info(
|
| 119 |
+
log_msg.format(
|
| 120 |
+
i,
|
| 121 |
+
n_iterations,
|
| 122 |
+
eta=eta_string,
|
| 123 |
+
meters=str(self),
|
| 124 |
+
time=str(iter_time),
|
| 125 |
+
data=str(data_time),
|
| 126 |
+
)
|
| 127 |
+
)
|
| 128 |
+
i += 1
|
| 129 |
+
end = time.time()
|
| 130 |
+
total_time = time.time() - start_time
|
| 131 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
| 132 |
+
s_it = total_time / n_iterations if n_iterations > 0 else 0
|
| 133 |
+
logger.info("{} Total time: {} ({:.6f} s / it)".format(header, total_time_str, s_it))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class SmoothedValue:
|
| 137 |
+
"""Track a series of values and provide access to smoothed values over a
|
| 138 |
+
window or the global series average.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
def __init__(self, window_size=20, fmt=None):
|
| 142 |
+
if fmt is None:
|
| 143 |
+
fmt = "{median:.4f} ({global_avg:.4f})"
|
| 144 |
+
self.deque = deque(maxlen=window_size)
|
| 145 |
+
self.total = 0.0
|
| 146 |
+
self.count = 0
|
| 147 |
+
self.fmt = fmt
|
| 148 |
+
|
| 149 |
+
def update(self, value, num=1):
|
| 150 |
+
self.deque.append(value)
|
| 151 |
+
self.count += num
|
| 152 |
+
self.total += value * num
|
| 153 |
+
|
| 154 |
+
def synchronize_between_processes(self):
|
| 155 |
+
"""
|
| 156 |
+
Distributed synchronization of the metric
|
| 157 |
+
Warning: does not synchronize the deque!
|
| 158 |
+
"""
|
| 159 |
+
if not distributed.is_enabled():
|
| 160 |
+
return
|
| 161 |
+
t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
|
| 162 |
+
torch.distributed.barrier()
|
| 163 |
+
torch.distributed.all_reduce(t)
|
| 164 |
+
t = t.tolist()
|
| 165 |
+
self.count = int(t[0])
|
| 166 |
+
self.total = t[1]
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def median(self):
|
| 170 |
+
d = torch.tensor(list(self.deque))
|
| 171 |
+
return d.median().item() # returns float("nan") when d is empty
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def avg(self):
|
| 175 |
+
d = torch.tensor(list(self.deque), dtype=torch.float32)
|
| 176 |
+
return d.mean().item() # returns float("nan") when d is empty
|
| 177 |
+
|
| 178 |
+
@property
|
| 179 |
+
def global_avg(self):
|
| 180 |
+
if self.count == 0:
|
| 181 |
+
return float("nan")
|
| 182 |
+
return self.total / self.count
|
| 183 |
+
|
| 184 |
+
@property
|
| 185 |
+
def max(self):
|
| 186 |
+
if len(self.deque) == 0:
|
| 187 |
+
return float("nan")
|
| 188 |
+
return max(self.deque)
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def value(self):
|
| 192 |
+
if len(self.deque) == 0:
|
| 193 |
+
return float("nan")
|
| 194 |
+
return self.deque[-1]
|
| 195 |
+
|
| 196 |
+
def __str__(self):
|
| 197 |
+
return self.fmt.format(
|
| 198 |
+
median=self.median,
|
| 199 |
+
avg=self.avg,
|
| 200 |
+
global_avg=self.global_avg,
|
| 201 |
+
max=self.max,
|
| 202 |
+
value=self.value,
|
| 203 |
+
)
|
starVLA/dinov3/dinov3/loss/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from .dino_clstoken_loss import DINOLoss
|
| 7 |
+
from .gram_loss import GramLoss
|
| 8 |
+
from .ibot_patch_loss import iBOTPatchLoss
|
| 9 |
+
from .koleo_loss import KoLeoLoss, KoLeoLossDistributed
|
starVLA/dinov3/dinov3/loss/dino_clstoken_loss.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed as dist
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch import nn
|
| 12 |
+
|
| 13 |
+
from dinov3.distributed import get_process_subgroup, get_subgroup_size
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class DINOLoss(nn.Module):
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
out_dim,
|
| 20 |
+
student_temp=0.1,
|
| 21 |
+
center_momentum=0.9,
|
| 22 |
+
):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.student_temp = student_temp
|
| 25 |
+
self.center_momentum = center_momentum
|
| 26 |
+
self.register_buffer("center", torch.full((1, out_dim), math.nan))
|
| 27 |
+
self.updated = True
|
| 28 |
+
self.reduce_handle = None
|
| 29 |
+
self.len_teacher_output = None
|
| 30 |
+
self.async_batch_center = None
|
| 31 |
+
|
| 32 |
+
def init_weights(self) -> None:
|
| 33 |
+
self.center.zero_()
|
| 34 |
+
|
| 35 |
+
@torch.no_grad()
|
| 36 |
+
def softmax_center_teacher(self, teacher_output, teacher_temp, update_centers=True):
|
| 37 |
+
if update_centers:
|
| 38 |
+
self.apply_center_update()
|
| 39 |
+
# teacher centering and sharpening
|
| 40 |
+
return F.softmax((teacher_output - self.center) / teacher_temp, dim=-1)
|
| 41 |
+
|
| 42 |
+
@torch.no_grad()
|
| 43 |
+
def sinkhorn_knopp_teacher(self, teacher_output, teacher_temp, n_iterations=3):
|
| 44 |
+
# teacher_output: [batch, prototypes]
|
| 45 |
+
teacher_output = teacher_output.float()
|
| 46 |
+
world_size = get_subgroup_size() if dist.is_initialized() else 1
|
| 47 |
+
Q = torch.exp(teacher_output / teacher_temp).t() # Q is K-by-B for consistency with notations from our paper
|
| 48 |
+
B = Q.shape[1] * world_size # number of samples to assign
|
| 49 |
+
K = Q.shape[0] # how many prototypes
|
| 50 |
+
|
| 51 |
+
# make the matrix sums to 1
|
| 52 |
+
sum_Q = torch.sum(Q)
|
| 53 |
+
if dist.is_initialized():
|
| 54 |
+
dist.all_reduce(sum_Q, group=get_process_subgroup())
|
| 55 |
+
Q /= sum_Q
|
| 56 |
+
|
| 57 |
+
for _ in range(n_iterations):
|
| 58 |
+
# normalize each row: total weight per prototype must be 1/K
|
| 59 |
+
sum_of_rows = torch.sum(Q, dim=1, keepdim=True)
|
| 60 |
+
if dist.is_initialized():
|
| 61 |
+
dist.all_reduce(sum_of_rows, group=get_process_subgroup())
|
| 62 |
+
Q /= sum_of_rows
|
| 63 |
+
Q /= K
|
| 64 |
+
|
| 65 |
+
# normalize each column: total weight per sample must be 1/B
|
| 66 |
+
Q /= torch.sum(Q, dim=0, keepdim=True)
|
| 67 |
+
Q /= B
|
| 68 |
+
|
| 69 |
+
Q *= B # the colomns must sum to 1 so that Q is an assignment
|
| 70 |
+
return Q.t()
|
| 71 |
+
|
| 72 |
+
def forward(self, student_logits, teacher_probs, ignore_diagonal=False):
|
| 73 |
+
"""
|
| 74 |
+
Cross-entropy between softmax outputs of the teacher and student networks.
|
| 75 |
+
student_logits: [student crops, batch, prototypes]
|
| 76 |
+
teacher_probs: [teacher crops, batch, prototypes] must sum to 1 over the last dim
|
| 77 |
+
|
| 78 |
+
loss = 0
|
| 79 |
+
count = 0
|
| 80 |
+
for each sample `b` in the batch:
|
| 81 |
+
for each student crop `s` of this sample:
|
| 82 |
+
for each teacher crop `t` of this sample:
|
| 83 |
+
if ignore_diagonal and s == t:
|
| 84 |
+
continue
|
| 85 |
+
loss += cross_entropy(softmax(student_logits[s, b] / student_temp), teacher_probs[t, b])
|
| 86 |
+
count += 1
|
| 87 |
+
return loss / count
|
| 88 |
+
"""
|
| 89 |
+
student_crops, B, K = student_logits.shape
|
| 90 |
+
teacher_crops, _, _ = teacher_probs.shape
|
| 91 |
+
student_logits = F.log_softmax(student_logits.float() / self.student_temp, dim=-1)
|
| 92 |
+
if not ignore_diagonal:
|
| 93 |
+
loss = -torch.einsum("s b k, t b k -> ", student_logits, teacher_probs)
|
| 94 |
+
return loss / (B * student_crops * teacher_crops)
|
| 95 |
+
else:
|
| 96 |
+
loss = -torch.einsum("s b k, t b k -> s t", student_logits, teacher_probs)
|
| 97 |
+
min_st = min(student_crops, teacher_crops)
|
| 98 |
+
loss = torch.diagonal_scatter(loss, loss.new_zeros(min_st))
|
| 99 |
+
return loss.sum() / (B * student_crops * teacher_crops - B * min_st)
|
| 100 |
+
|
| 101 |
+
@torch.no_grad()
|
| 102 |
+
def update_center(self, teacher_output):
|
| 103 |
+
self.reduce_center_update(teacher_output)
|
| 104 |
+
|
| 105 |
+
@torch.no_grad()
|
| 106 |
+
def reduce_center_update(self, teacher_output):
|
| 107 |
+
self.updated = False
|
| 108 |
+
self.len_teacher_output = len(teacher_output)
|
| 109 |
+
self.async_batch_center = torch.sum(teacher_output, dim=0, keepdim=True)
|
| 110 |
+
if dist.is_initialized():
|
| 111 |
+
self.reduce_handle = dist.all_reduce(self.async_batch_center, async_op=True, group=get_process_subgroup())
|
| 112 |
+
|
| 113 |
+
@torch.no_grad()
|
| 114 |
+
def apply_center_update(self):
|
| 115 |
+
if self.updated is False:
|
| 116 |
+
world_size = get_subgroup_size() if dist.is_initialized() else 1
|
| 117 |
+
|
| 118 |
+
if self.reduce_handle is not None:
|
| 119 |
+
self.reduce_handle.wait()
|
| 120 |
+
_t = self.async_batch_center / (self.len_teacher_output * world_size)
|
| 121 |
+
|
| 122 |
+
self.center = self.center * self.center_momentum + _t * (1 - self.center_momentum)
|
| 123 |
+
|
| 124 |
+
self.updated = True
|
starVLA/dinov3/dinov3/loss/gram_loss.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class GramLoss(nn.Module):
|
| 12 |
+
"""Implementation of the gram loss"""
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
apply_norm=True,
|
| 17 |
+
img_level=True,
|
| 18 |
+
remove_neg=True,
|
| 19 |
+
remove_only_teacher_neg=False,
|
| 20 |
+
):
|
| 21 |
+
super().__init__()
|
| 22 |
+
|
| 23 |
+
# Loss
|
| 24 |
+
self.mse_loss = torch.nn.MSELoss()
|
| 25 |
+
|
| 26 |
+
# Parameters
|
| 27 |
+
self.apply_norm = apply_norm
|
| 28 |
+
self.remove_neg = remove_neg
|
| 29 |
+
self.remove_only_teacher_neg = remove_only_teacher_neg
|
| 30 |
+
|
| 31 |
+
if self.remove_neg or self.remove_only_teacher_neg:
|
| 32 |
+
assert self.remove_neg != self.remove_only_teacher_neg
|
| 33 |
+
|
| 34 |
+
def forward(self, output_feats, target_feats, img_level=True):
|
| 35 |
+
"""Compute the MSE loss between the gram matrix of the input and target features.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
output_feats: Pytorch tensor (B, N, dim) or (B*N, dim) if img_level == False
|
| 39 |
+
target_feats: Pytorch tensor (B, N, dim) or (B*N, dim) if img_level == False
|
| 40 |
+
img_level: bool, if true gram computed at the image level only else over the entire batch
|
| 41 |
+
Returns:
|
| 42 |
+
loss: scalar
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
# Dimensions of the tensor should be (B, N, dim)
|
| 46 |
+
if img_level:
|
| 47 |
+
assert len(target_feats.shape) == 3 and len(output_feats.shape) == 3
|
| 48 |
+
|
| 49 |
+
# Float casting
|
| 50 |
+
output_feats = output_feats.float()
|
| 51 |
+
target_feats = target_feats.float()
|
| 52 |
+
|
| 53 |
+
# SSL correlation
|
| 54 |
+
if self.apply_norm:
|
| 55 |
+
target_feats = F.normalize(target_feats, dim=-1)
|
| 56 |
+
|
| 57 |
+
if not img_level and len(target_feats.shape) == 3:
|
| 58 |
+
# Flatten (B, N, D) into (B*N, D)
|
| 59 |
+
target_feats = target_feats.flatten(0, 1)
|
| 60 |
+
|
| 61 |
+
# Compute similarities
|
| 62 |
+
target_sim = torch.matmul(target_feats, target_feats.transpose(-1, -2))
|
| 63 |
+
|
| 64 |
+
# Patch correlation
|
| 65 |
+
if self.apply_norm:
|
| 66 |
+
output_feats = F.normalize(output_feats, dim=-1)
|
| 67 |
+
|
| 68 |
+
if not img_level and len(output_feats.shape) == 3:
|
| 69 |
+
# Flatten (B, N, D) into (B*N, D)
|
| 70 |
+
output_feats = output_feats.flatten(0, 1)
|
| 71 |
+
|
| 72 |
+
# Compute similarities
|
| 73 |
+
student_sim = torch.matmul(output_feats, output_feats.transpose(-1, -2))
|
| 74 |
+
|
| 75 |
+
if self.remove_neg:
|
| 76 |
+
target_sim[target_sim < 0] = 0.0
|
| 77 |
+
student_sim[student_sim < 0] = 0.0
|
| 78 |
+
|
| 79 |
+
elif self.remove_only_teacher_neg:
|
| 80 |
+
# Remove only the negative sim values of the teacher
|
| 81 |
+
target_sim[target_sim < 0] = 0.0
|
| 82 |
+
student_sim[(student_sim < 0) & (target_sim < 0)] = 0.0
|
| 83 |
+
|
| 84 |
+
return self.mse_loss(student_sim, target_sim)
|
starVLA/dinov3/dinov3/loss/ibot_patch_loss.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed as dist
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch import nn
|
| 12 |
+
|
| 13 |
+
from dinov3.distributed import get_process_subgroup, get_subgroup_size
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def lossfunc(t, s, temp): # noqa: F811
|
| 17 |
+
return torch.sum(t.float() * F.log_softmax(s.float() / temp, dim=-1), dim=-1)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SinkhornKnoppTeacher(nn.Module):
|
| 21 |
+
"""
|
| 22 |
+
NOTE: This is a module and not a function in the `iBOTPatchLoss` class
|
| 23 |
+
This is because we want to torch.compile it, and torch.compil-ing a single
|
| 24 |
+
function with the `@torch.compile` decorator is bad.
|
| 25 |
+
It's better to `module.compile()` it, as we can control when we enable or
|
| 26 |
+
disable compilation globally.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
@torch.no_grad()
|
| 30 |
+
def forward(self, teacher_output, teacher_temp, n_masked_patches_tensor, n_iterations=3):
|
| 31 |
+
teacher_output = teacher_output.float()
|
| 32 |
+
# world_size = dist.get_world_size() if dist.is_initialized() else 1
|
| 33 |
+
Q = torch.exp(teacher_output / teacher_temp).t() # Q is K-by-B for consistency with notations from our paper
|
| 34 |
+
# B = Q.shape[1] * world_size # number of samples to assign
|
| 35 |
+
B = n_masked_patches_tensor
|
| 36 |
+
dist.all_reduce(B, group=get_process_subgroup())
|
| 37 |
+
K = Q.shape[0] # how many prototypes
|
| 38 |
+
|
| 39 |
+
# make the matrix sums to 1
|
| 40 |
+
sum_Q = torch.sum(Q)
|
| 41 |
+
if dist.is_initialized():
|
| 42 |
+
dist.all_reduce(sum_Q, group=get_process_subgroup())
|
| 43 |
+
Q /= sum_Q
|
| 44 |
+
|
| 45 |
+
for _ in range(n_iterations):
|
| 46 |
+
# normalize each row: total weight per prototype must be 1/K
|
| 47 |
+
sum_of_rows = torch.sum(Q, dim=1, keepdim=True)
|
| 48 |
+
if dist.is_initialized():
|
| 49 |
+
dist.all_reduce(sum_of_rows, group=get_process_subgroup())
|
| 50 |
+
Q /= sum_of_rows
|
| 51 |
+
Q /= K
|
| 52 |
+
|
| 53 |
+
# normalize each column: total weight per sample must be 1/B
|
| 54 |
+
Q /= torch.sum(Q, dim=0, keepdim=True)
|
| 55 |
+
Q /= B
|
| 56 |
+
|
| 57 |
+
Q *= B # the colomns must sum to 1 so that Q is an assignment
|
| 58 |
+
return Q.t()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class iBOTPatchLoss(nn.Module):
|
| 62 |
+
def __init__(self, patch_out_dim, student_temp=0.1, center_momentum=0.9):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.student_temp = student_temp
|
| 65 |
+
self.center_momentum = center_momentum
|
| 66 |
+
self.register_buffer("center", torch.full((1, 1, patch_out_dim), math.nan))
|
| 67 |
+
self.updated = True
|
| 68 |
+
self.reduce_handle = None
|
| 69 |
+
self.len_teacher_patch_tokens = None
|
| 70 |
+
self.async_batch_center = None
|
| 71 |
+
self.sinkhorn_knopp_teacher = SinkhornKnoppTeacher()
|
| 72 |
+
self.sinkhorn_knopp_teacher.compile()
|
| 73 |
+
|
| 74 |
+
def init_weights(self) -> None:
|
| 75 |
+
self.center.zero_()
|
| 76 |
+
|
| 77 |
+
@torch.no_grad()
|
| 78 |
+
def softmax_center_teacher(self, teacher_patch_tokens, teacher_temp, update_centers=True):
|
| 79 |
+
if update_centers:
|
| 80 |
+
self.apply_center_update()
|
| 81 |
+
return F.softmax((teacher_patch_tokens - self.center) / teacher_temp, dim=-1)
|
| 82 |
+
|
| 83 |
+
def forward(self, student_patch_tokens, teacher_patch_tokens, student_masks_flat):
|
| 84 |
+
"""
|
| 85 |
+
Cross-entropy between softmax outputs of the teacher and student networks.
|
| 86 |
+
student_patch_tokens: (B, N, D) tensor
|
| 87 |
+
teacher_patch_tokens: (B, N, D) tensor
|
| 88 |
+
student_masks_flat: (B, N) tensor
|
| 89 |
+
"""
|
| 90 |
+
t = teacher_patch_tokens
|
| 91 |
+
s = student_patch_tokens
|
| 92 |
+
loss = lossfunc(t, s, self.student_temp)
|
| 93 |
+
loss = torch.sum(loss * student_masks_flat.float(), dim=-1) / student_masks_flat.sum(dim=-1).clamp(min=1.0)
|
| 94 |
+
return -loss.mean()
|
| 95 |
+
|
| 96 |
+
def forward_masked(
|
| 97 |
+
self,
|
| 98 |
+
student_patch_tokens_masked,
|
| 99 |
+
teacher_patch_tokens_masked,
|
| 100 |
+
student_masks_flat,
|
| 101 |
+
n_masked_patches=None,
|
| 102 |
+
masks_weight=None,
|
| 103 |
+
):
|
| 104 |
+
t = teacher_patch_tokens_masked
|
| 105 |
+
s = student_patch_tokens_masked
|
| 106 |
+
# loss = torch.sum(t * F.log_softmax(s / self.student_temp, dim=-1), dim=-1)
|
| 107 |
+
loss = lossfunc(t, s, self.student_temp)
|
| 108 |
+
if masks_weight is None:
|
| 109 |
+
masks_weight = (
|
| 110 |
+
(1 / student_masks_flat.sum(-1).clamp(min=1.0))
|
| 111 |
+
.unsqueeze(-1)
|
| 112 |
+
.expand_as(student_masks_flat)[student_masks_flat]
|
| 113 |
+
)
|
| 114 |
+
if n_masked_patches is not None:
|
| 115 |
+
loss = loss[:n_masked_patches]
|
| 116 |
+
loss = loss * masks_weight
|
| 117 |
+
return -loss.sum() / student_masks_flat.shape[0]
|
| 118 |
+
|
| 119 |
+
@torch.no_grad()
|
| 120 |
+
def update_center(self, teacher_patch_tokens):
|
| 121 |
+
self.reduce_center_update(teacher_patch_tokens)
|
| 122 |
+
|
| 123 |
+
@torch.no_grad()
|
| 124 |
+
def reduce_center_update(self, teacher_patch_tokens):
|
| 125 |
+
self.updated = False
|
| 126 |
+
self.len_teacher_patch_tokens = len(teacher_patch_tokens)
|
| 127 |
+
self.async_batch_center = torch.sum(teacher_patch_tokens.mean(1), dim=0, keepdim=True)
|
| 128 |
+
if dist.is_initialized():
|
| 129 |
+
self.reduce_handle = dist.all_reduce(self.async_batch_center, async_op=True, group=get_process_subgroup())
|
| 130 |
+
|
| 131 |
+
@torch.no_grad()
|
| 132 |
+
def apply_center_update(self):
|
| 133 |
+
if self.updated is False:
|
| 134 |
+
world_size = get_subgroup_size() if dist.is_initialized() else 1
|
| 135 |
+
|
| 136 |
+
if self.reduce_handle is not None:
|
| 137 |
+
self.reduce_handle.wait()
|
| 138 |
+
_t = self.async_batch_center / (self.len_teacher_patch_tokens * world_size)
|
| 139 |
+
|
| 140 |
+
self.center = self.center * self.center_momentum + _t * (1 - self.center_momentum)
|
| 141 |
+
|
| 142 |
+
self.updated = True
|
starVLA/dinov3/dinov3/loss/koleo_loss.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.distributed as torch_dist
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
import dinov3.distributed as dist
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class KoLeoLoss(nn.Module):
|
| 15 |
+
"""Kozachenko-Leonenko entropic loss regularizer from Sablayrolles et al. - 2018 - Spreading vectors for similarity search"""
|
| 16 |
+
|
| 17 |
+
def __init__(self):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.pdist = nn.PairwiseDistance(2, eps=1e-8)
|
| 20 |
+
|
| 21 |
+
def pairwise_NNs_inner(self, x):
|
| 22 |
+
"""
|
| 23 |
+
Pairwise nearest neighbors for L2-normalized vectors.
|
| 24 |
+
Uses Torch rather than Faiss to remain on GPU.
|
| 25 |
+
"""
|
| 26 |
+
# parwise dot products (= inverse distance)
|
| 27 |
+
dots = torch.mm(x, x.t())
|
| 28 |
+
n = x.shape[0]
|
| 29 |
+
dots.view(-1)[:: (n + 1)].fill_(-1) # Trick to fill diagonal with -1
|
| 30 |
+
_, indices = torch.max(dots, dim=1) # max inner prod -> min distance
|
| 31 |
+
return indices
|
| 32 |
+
|
| 33 |
+
def forward(self, student_output, eps=1e-8):
|
| 34 |
+
"""
|
| 35 |
+
Args:
|
| 36 |
+
student_output (BxD): backbone output of student
|
| 37 |
+
"""
|
| 38 |
+
with torch.autocast("cuda", enabled=False):
|
| 39 |
+
student_output = F.normalize(student_output, eps=eps, p=2, dim=-1)
|
| 40 |
+
indices = self.pairwise_NNs_inner(student_output)
|
| 41 |
+
distances = self.pdist(student_output, student_output[indices]) # BxD, BxD -> B
|
| 42 |
+
loss = -torch.log(distances + eps).mean()
|
| 43 |
+
return loss
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class KoLeoLossDistributed(nn.Module):
|
| 47 |
+
"""Kozachenko-Leonenko entropic loss regularizer from Sablayrolles et al. - 2018 - Spreading vectors for similarity search"""
|
| 48 |
+
|
| 49 |
+
def __init__(self, topk=1, loss_group_size: int | None = None):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.pdist = nn.PairwiseDistance(2, eps=1e-8)
|
| 52 |
+
self.topk = topk
|
| 53 |
+
self.loss_group_size = loss_group_size # Size of the nearest neighbor set. If None, uses global batch size.
|
| 54 |
+
|
| 55 |
+
def pairwise_NNs_inner(self, x, all_x, rank):
|
| 56 |
+
"""
|
| 57 |
+
Pairwise nearest neighbors for L2-normalized vectors.
|
| 58 |
+
Uses Torch rather than Faiss to remain on GPU.
|
| 59 |
+
"""
|
| 60 |
+
# parwise dot products (= inverse distance)
|
| 61 |
+
dots = torch.mm(x, all_x.t()) # local_B x global_B
|
| 62 |
+
local_B, global_B = dots.shape
|
| 63 |
+
dots.view(-1)[rank * local_B :: (global_B + 1)].fill_(-1) # Trick to fill diagonal with -1
|
| 64 |
+
_, indices = torch.topk(dots, dim=1, k=self.topk) # max inner prod -> min distance
|
| 65 |
+
return indices
|
| 66 |
+
|
| 67 |
+
def forward(self, student_output, eps=1e-8):
|
| 68 |
+
"""
|
| 69 |
+
Args:
|
| 70 |
+
student_output (BxD): backbone output of student
|
| 71 |
+
"""
|
| 72 |
+
with torch.autocast("cuda", enabled=False):
|
| 73 |
+
student_output = F.normalize(student_output, eps=eps, p=2, dim=-1) # local_B x D
|
| 74 |
+
|
| 75 |
+
if dist.is_enabled():
|
| 76 |
+
all_student_outputs = torch.cat(torch_dist.nn.all_gather(student_output), dim=0) # global_B x D
|
| 77 |
+
world_size = dist.get_world_size()
|
| 78 |
+
rank = dist.get_rank()
|
| 79 |
+
else:
|
| 80 |
+
all_student_outputs = student_output
|
| 81 |
+
world_size = 1
|
| 82 |
+
rank = 0
|
| 83 |
+
|
| 84 |
+
# Group the global batch into groups of size `loss_group_size` and use the features of the group
|
| 85 |
+
# the local rank falls into as the nearest neighbor set for the local rank
|
| 86 |
+
local_B = len(student_output)
|
| 87 |
+
global_B = len(all_student_outputs)
|
| 88 |
+
loss_group_size = self.loss_group_size if self.loss_group_size is not None else global_B
|
| 89 |
+
if loss_group_size % local_B != 0:
|
| 90 |
+
raise ValueError(
|
| 91 |
+
f"Loss group size size {loss_group_size} must be a multiple of local batch size {local_B}."
|
| 92 |
+
)
|
| 93 |
+
if global_B % loss_group_size != 0:
|
| 94 |
+
raise ValueError(
|
| 95 |
+
f"Global batch size {global_B} must be divisible by loss group size {loss_group_size}."
|
| 96 |
+
)
|
| 97 |
+
n_groups = global_B // loss_group_size
|
| 98 |
+
ranks_per_group = world_size // n_groups
|
| 99 |
+
rank_in_group = rank % ranks_per_group
|
| 100 |
+
group = rank // ranks_per_group
|
| 101 |
+
all_student_outputs = all_student_outputs.view(n_groups, loss_group_size, student_output.shape[1])
|
| 102 |
+
all_student_outputs = all_student_outputs[group] # loss_group_size x D
|
| 103 |
+
|
| 104 |
+
with torch.no_grad():
|
| 105 |
+
indices = self.pairwise_NNs_inner(student_output, all_student_outputs, rank_in_group) # local_B x topk
|
| 106 |
+
|
| 107 |
+
student_output_expanded = (
|
| 108 |
+
student_output.unsqueeze(1).repeat(1, self.topk, 1).flatten(0, 1)
|
| 109 |
+
) # (local_B * topk) x D
|
| 110 |
+
distances = self.pdist(student_output_expanded, all_student_outputs[indices].flatten(0, 1)) # BxD, BxD -> B
|
| 111 |
+
loss = -torch.log(distances.float() + eps).mean()
|
| 112 |
+
|
| 113 |
+
return loss
|
starVLA/dinov3/dinov3/models/__init__.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from typing import Union
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
|
| 14 |
+
from dinov3.layers.fp8_linear import convert_linears_to_fp8
|
| 15 |
+
|
| 16 |
+
from . import vision_transformer as vits
|
| 17 |
+
from . import convnext
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger("dinov3")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def init_fp8(model: nn.Module, args) -> nn.Module:
|
| 23 |
+
if not args.fp8_enabled:
|
| 24 |
+
logger.info("fp8 matmuls: OFF (disabled in config)")
|
| 25 |
+
return model
|
| 26 |
+
logger.info("fp8 matmuls: ON")
|
| 27 |
+
# Multi-kernel makes Inductor auto-tune between a regular "streaming"-based
|
| 28 |
+
# reduction kernel and a "persistent" reduction kernel. Since fp8 has some
|
| 29 |
+
# multi-pass steps (e.g., first get amax, then scale), persistent kernels
|
| 30 |
+
# should perform better.
|
| 31 |
+
torch._inductor.config.triton.multi_kernel = 1
|
| 32 |
+
return convert_linears_to_fp8(model, filter=args.fp8_filter)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def build_model(args, only_teacher=False, img_size=224, device=None):
|
| 36 |
+
if "vit" in args.arch:
|
| 37 |
+
vit_kwargs = dict(
|
| 38 |
+
img_size=img_size,
|
| 39 |
+
patch_size=args.patch_size,
|
| 40 |
+
pos_embed_rope_base=args.pos_embed_rope_base,
|
| 41 |
+
pos_embed_rope_min_period=args.pos_embed_rope_min_period,
|
| 42 |
+
pos_embed_rope_max_period=args.pos_embed_rope_max_period,
|
| 43 |
+
pos_embed_rope_normalize_coords=args.pos_embed_rope_normalize_coords,
|
| 44 |
+
pos_embed_rope_shift_coords=args.pos_embed_rope_shift_coords,
|
| 45 |
+
pos_embed_rope_jitter_coords=args.pos_embed_rope_jitter_coords,
|
| 46 |
+
pos_embed_rope_rescale_coords=args.pos_embed_rope_rescale_coords,
|
| 47 |
+
qkv_bias=args.qkv_bias,
|
| 48 |
+
layerscale_init=args.layerscale,
|
| 49 |
+
norm_layer=args.norm_layer,
|
| 50 |
+
ffn_layer=args.ffn_layer,
|
| 51 |
+
ffn_bias=args.ffn_bias,
|
| 52 |
+
proj_bias=args.proj_bias,
|
| 53 |
+
n_storage_tokens=args.n_storage_tokens,
|
| 54 |
+
mask_k_bias=args.mask_k_bias,
|
| 55 |
+
untie_cls_and_patch_norms=args.untie_cls_and_patch_norms,
|
| 56 |
+
untie_global_and_local_cls_norm=args.untie_global_and_local_cls_norm,
|
| 57 |
+
device=device,
|
| 58 |
+
)
|
| 59 |
+
teacher = vits.__dict__[args.arch](**vit_kwargs)
|
| 60 |
+
teacher = init_fp8(teacher, args)
|
| 61 |
+
if only_teacher:
|
| 62 |
+
return teacher, teacher.embed_dim
|
| 63 |
+
student = vits.__dict__[args.arch](
|
| 64 |
+
**vit_kwargs,
|
| 65 |
+
drop_path_rate=args.drop_path_rate,
|
| 66 |
+
)
|
| 67 |
+
embed_dim = student.embed_dim
|
| 68 |
+
elif "convnext" in args.arch:
|
| 69 |
+
convnext_cls = convnext.get_convnext_arch(args.arch)
|
| 70 |
+
convnext_kwargs = dict(patch_size=args.patch_size)
|
| 71 |
+
teacher = convnext_cls(**convnext_kwargs)
|
| 72 |
+
if only_teacher:
|
| 73 |
+
return teacher, teacher.embed_dim
|
| 74 |
+
student = convnext_cls(**convnext_kwargs)
|
| 75 |
+
embed_dim = student.embed_dim
|
| 76 |
+
else:
|
| 77 |
+
raise NotImplementedError(f"Unrecognized architecture {args.arch}")
|
| 78 |
+
student = init_fp8(student, args)
|
| 79 |
+
return student, teacher, embed_dim
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def build_model_from_cfg(cfg, only_teacher: bool = False):
|
| 83 |
+
outputs = build_model(
|
| 84 |
+
cfg.student,
|
| 85 |
+
only_teacher=only_teacher,
|
| 86 |
+
img_size=cfg.crops.global_crops_size
|
| 87 |
+
if isinstance(cfg.crops.global_crops_size, int)
|
| 88 |
+
else max(cfg.crops.global_crops_size),
|
| 89 |
+
device="meta",
|
| 90 |
+
)
|
| 91 |
+
if only_teacher:
|
| 92 |
+
teacher, embed_dim = outputs
|
| 93 |
+
return teacher, embed_dim
|
| 94 |
+
else:
|
| 95 |
+
student, teacher, embed_dim = outputs
|
| 96 |
+
return student, teacher, embed_dim
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def build_model_for_eval(
|
| 100 |
+
config,
|
| 101 |
+
pretrained_weights: Union[str, Path] | None,
|
| 102 |
+
shard_unsharded_model: bool = False, # If the model is not sharded, shard it. No effect if already sharded on disk
|
| 103 |
+
):
|
| 104 |
+
model, _ = build_model_from_cfg(config, only_teacher=True)
|
| 105 |
+
if pretrained_weights is None or pretrained_weights == "":
|
| 106 |
+
logger.info("No pretrained weights")
|
| 107 |
+
model.init_weights()
|
| 108 |
+
elif Path(pretrained_weights).is_dir():
|
| 109 |
+
logger.info("PyTorch DCP checkpoint")
|
| 110 |
+
from dinov3.checkpointer import load_checkpoint
|
| 111 |
+
from dinov3.fsdp.ac_compile_parallelize import ac_compile_parallelize
|
| 112 |
+
|
| 113 |
+
moduledict = nn.ModuleDict({"backbone": model})
|
| 114 |
+
# Wrap with FSDP
|
| 115 |
+
ac_compile_parallelize(moduledict, inference_only_models=[], cfg=config)
|
| 116 |
+
# Move to CUDA
|
| 117 |
+
model.to_empty(device="cuda")
|
| 118 |
+
# Load checkpoint
|
| 119 |
+
load_checkpoint(pretrained_weights, model=moduledict, strict_loading=True)
|
| 120 |
+
shard_unsharded_model = False
|
| 121 |
+
else:
|
| 122 |
+
logger.info("PyTorch consolidated checkpoint")
|
| 123 |
+
from dinov3.checkpointer import init_model_from_checkpoint_for_evals
|
| 124 |
+
|
| 125 |
+
# consolidated checkpoint codepath
|
| 126 |
+
model.to_empty(device="cuda")
|
| 127 |
+
init_model_from_checkpoint_for_evals(model, pretrained_weights, "teacher")
|
| 128 |
+
if shard_unsharded_model:
|
| 129 |
+
logger.info("Sharding model")
|
| 130 |
+
moduledict = nn.ModuleDict({"backbone": model})
|
| 131 |
+
ac_compile_parallelize(moduledict, inference_only_models=[], cfg=config)
|
| 132 |
+
model.eval()
|
| 133 |
+
return model
|
starVLA/dinov3/dinov3/models/convnext.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from functools import partial
|
| 8 |
+
from typing import Dict, List, Optional, Sequence, Union
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import torch.nn.init
|
| 14 |
+
from torch import Tensor, nn
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("dinov3")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def drop_path(x: Tensor, drop_prob: float = 0.0, training: bool = False) -> Tensor:
|
| 21 |
+
if drop_prob == 0.0 or not training:
|
| 22 |
+
return x
|
| 23 |
+
keep_prob = 1 - drop_prob
|
| 24 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 25 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
|
| 26 |
+
random_tensor.floor_() # binarize
|
| 27 |
+
output = x.div(keep_prob) * random_tensor
|
| 28 |
+
return output
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DropPath(nn.Module):
|
| 32 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 33 |
+
|
| 34 |
+
def __init__(self, drop_prob=None) -> None:
|
| 35 |
+
super(DropPath, self).__init__()
|
| 36 |
+
self.drop_prob = drop_prob
|
| 37 |
+
|
| 38 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 39 |
+
return drop_path(x, self.drop_prob, self.training)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Block(nn.Module):
|
| 43 |
+
r"""ConvNeXt Block. There are two equivalent implementations:
|
| 44 |
+
(1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
|
| 45 |
+
(2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
|
| 46 |
+
We use (2) as we find it slightly faster in PyTorch
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
dim (int): Number of input channels.
|
| 50 |
+
drop_path (float): Stochastic depth rate. Default: 0.0
|
| 51 |
+
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
|
| 52 |
+
|
| 53 |
+
Source: https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(self, dim, drop_path=0.0, layer_scale_init_value=1e-6):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
|
| 59 |
+
self.norm = LayerNorm(dim, eps=1e-6)
|
| 60 |
+
self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
|
| 61 |
+
self.act = nn.GELU()
|
| 62 |
+
self.pwconv2 = nn.Linear(4 * dim, dim)
|
| 63 |
+
self.layer_scale_init_value = layer_scale_init_value
|
| 64 |
+
self.gamma = (
|
| 65 |
+
nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
|
| 66 |
+
if layer_scale_init_value > 0
|
| 67 |
+
else None
|
| 68 |
+
)
|
| 69 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 70 |
+
|
| 71 |
+
def forward(self, x):
|
| 72 |
+
input = x
|
| 73 |
+
x = self.dwconv(x)
|
| 74 |
+
x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
|
| 75 |
+
x = self.norm(x)
|
| 76 |
+
x = self.pwconv1(x)
|
| 77 |
+
x = self.act(x)
|
| 78 |
+
x = self.pwconv2(x)
|
| 79 |
+
if self.gamma is not None:
|
| 80 |
+
x = self.gamma * x
|
| 81 |
+
x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
|
| 82 |
+
|
| 83 |
+
x = input + self.drop_path(x)
|
| 84 |
+
return x
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class LayerNorm(nn.Module):
|
| 88 |
+
r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
|
| 89 |
+
The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
|
| 90 |
+
shape (batch_size, height, width, channels) while channels_first corresponds to inputs
|
| 91 |
+
with shape (batch_size, channels, height, width).
|
| 92 |
+
|
| 93 |
+
Source: https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.weight = nn.Parameter(torch.empty(normalized_shape))
|
| 99 |
+
self.bias = nn.Parameter(torch.empty(normalized_shape))
|
| 100 |
+
self.eps = eps
|
| 101 |
+
self.data_format = data_format
|
| 102 |
+
if self.data_format not in ["channels_last", "channels_first"]:
|
| 103 |
+
raise NotImplementedError
|
| 104 |
+
self.normalized_shape = (normalized_shape,)
|
| 105 |
+
|
| 106 |
+
def init_weights(self):
|
| 107 |
+
nn.init.ones_(self.weight)
|
| 108 |
+
nn.init.zeros_(self.bias)
|
| 109 |
+
|
| 110 |
+
def forward(self, x):
|
| 111 |
+
if self.data_format == "channels_last":
|
| 112 |
+
return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
|
| 113 |
+
elif self.data_format == "channels_first":
|
| 114 |
+
u = x.mean(1, keepdim=True)
|
| 115 |
+
s = (x - u).pow(2).mean(1, keepdim=True)
|
| 116 |
+
x = (x - u) / torch.sqrt(s + self.eps)
|
| 117 |
+
x = self.weight[:, None, None] * x + self.bias[:, None, None]
|
| 118 |
+
return x
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class ConvNeXt(nn.Module):
|
| 122 |
+
r"""
|
| 123 |
+
Code adapted from https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.pyConvNeXt
|
| 124 |
+
|
| 125 |
+
A PyTorch impl of : `A ConvNet for the 2020s` -
|
| 126 |
+
https://arxiv.org/pdf/2201.03545.pdf
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
in_chans (int): Number of input image channels. Default: 3
|
| 130 |
+
num_classes (int): Number of classes for classification head. Default: 1000
|
| 131 |
+
depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3]
|
| 132 |
+
dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768]
|
| 133 |
+
drop_path_rate (float): Stochastic depth rate. Default: 0.
|
| 134 |
+
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
|
| 135 |
+
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
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
# original ConvNeXt arguments
|
| 141 |
+
in_chans: int = 3,
|
| 142 |
+
depths: List[int] = [3, 3, 9, 3],
|
| 143 |
+
dims: List[int] = [96, 192, 384, 768],
|
| 144 |
+
drop_path_rate: float = 0.0,
|
| 145 |
+
layer_scale_init_value: float = 1e-6,
|
| 146 |
+
# DINO arguments
|
| 147 |
+
patch_size: int | None = None,
|
| 148 |
+
**ignored_kwargs,
|
| 149 |
+
):
|
| 150 |
+
super().__init__()
|
| 151 |
+
if len(ignored_kwargs) > 0:
|
| 152 |
+
logger.warning(f"Ignored kwargs: {ignored_kwargs}")
|
| 153 |
+
del ignored_kwargs
|
| 154 |
+
|
| 155 |
+
# ==== ConvNeXt's original init =====
|
| 156 |
+
self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers
|
| 157 |
+
stem = nn.Sequential(
|
| 158 |
+
nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4),
|
| 159 |
+
LayerNorm(dims[0], eps=1e-6, data_format="channels_first"),
|
| 160 |
+
)
|
| 161 |
+
self.downsample_layers.append(stem)
|
| 162 |
+
for i in range(3):
|
| 163 |
+
downsample_layer = nn.Sequential(
|
| 164 |
+
LayerNorm(dims[i], eps=1e-6, data_format="channels_first"),
|
| 165 |
+
nn.Conv2d(dims[i], dims[i + 1], kernel_size=2, stride=2),
|
| 166 |
+
)
|
| 167 |
+
self.downsample_layers.append(downsample_layer)
|
| 168 |
+
|
| 169 |
+
self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks
|
| 170 |
+
dp_rates = [x for x in np.linspace(0, drop_path_rate, sum(depths))]
|
| 171 |
+
cur = 0
|
| 172 |
+
for i in range(4):
|
| 173 |
+
stage = nn.Sequential(
|
| 174 |
+
*[
|
| 175 |
+
Block(dim=dims[i], drop_path=dp_rates[cur + j], layer_scale_init_value=layer_scale_init_value)
|
| 176 |
+
for j in range(depths[i])
|
| 177 |
+
]
|
| 178 |
+
)
|
| 179 |
+
self.stages.append(stage)
|
| 180 |
+
cur += depths[i]
|
| 181 |
+
|
| 182 |
+
self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer
|
| 183 |
+
# ==== End of ConvNeXt's original init =====
|
| 184 |
+
|
| 185 |
+
# ==== DINO adaptation ====
|
| 186 |
+
self.head = nn.Identity() # remove classification head
|
| 187 |
+
self.embed_dim = dims[-1]
|
| 188 |
+
self.embed_dims = dims # per layer dimensions
|
| 189 |
+
self.n_blocks = len(self.downsample_layers) # 4
|
| 190 |
+
self.chunked_blocks = False
|
| 191 |
+
self.n_storage_tokens = 0 # no registers
|
| 192 |
+
|
| 193 |
+
self.norms = nn.ModuleList([nn.Identity() for i in range(3)])
|
| 194 |
+
self.norms.append(self.norm)
|
| 195 |
+
|
| 196 |
+
self.patch_size = patch_size
|
| 197 |
+
self.input_pad_size = 4 # first convolution with kernel_size = 4, stride = 4
|
| 198 |
+
|
| 199 |
+
def init_weights(self):
|
| 200 |
+
self.apply(self._init_weights)
|
| 201 |
+
for stage_id, stage in enumerate(self.stages):
|
| 202 |
+
for block_id, block in enumerate(stage):
|
| 203 |
+
if block.gamma is not None:
|
| 204 |
+
nn.init.constant_(self.stages[stage_id][block_id].gamma, block.layer_scale_init_value)
|
| 205 |
+
|
| 206 |
+
def _init_weights(self, module):
|
| 207 |
+
if isinstance(module, nn.LayerNorm):
|
| 208 |
+
module.reset_parameters()
|
| 209 |
+
if isinstance(module, LayerNorm):
|
| 210 |
+
nn.init.ones_(module.weight)
|
| 211 |
+
nn.init.zeros_(module.bias)
|
| 212 |
+
if isinstance(module, (nn.Conv2d, nn.Linear)):
|
| 213 |
+
nn.init.trunc_normal_(module.weight, std=0.02)
|
| 214 |
+
if module.bias is not None:
|
| 215 |
+
nn.init.zeros_(module.bias)
|
| 216 |
+
|
| 217 |
+
def forward_features(self, x: Tensor | List[Tensor], masks: Optional[Tensor] = None) -> List[Dict[str, Tensor]]:
|
| 218 |
+
if isinstance(x, torch.Tensor):
|
| 219 |
+
return self.forward_features_list([x], [masks])[0]
|
| 220 |
+
else:
|
| 221 |
+
return self.forward_features_list(x, masks)
|
| 222 |
+
|
| 223 |
+
def forward_features_list(self, x_list: List[Tensor], masks_list: List[Tensor]) -> List[Dict[str, Tensor]]:
|
| 224 |
+
output = []
|
| 225 |
+
for x, masks in zip(x_list, masks_list):
|
| 226 |
+
h, w = x.shape[-2:]
|
| 227 |
+
for i in range(4):
|
| 228 |
+
x = self.downsample_layers[i](x)
|
| 229 |
+
x = self.stages[i](x)
|
| 230 |
+
x_pool = x.mean([-2, -1]) # global average pooling, (N, C, H, W) -> (N, C)
|
| 231 |
+
x = torch.flatten(x, 2).transpose(1, 2)
|
| 232 |
+
|
| 233 |
+
# concat [CLS] and patch tokens as (N, HW + 1, C), then normalize
|
| 234 |
+
x_norm = self.norm(torch.cat([x_pool.unsqueeze(1), x], dim=1))
|
| 235 |
+
output.append(
|
| 236 |
+
{
|
| 237 |
+
"x_norm_clstoken": x_norm[:, 0],
|
| 238 |
+
"x_storage_tokens": x_norm[:, 1 : self.n_storage_tokens + 1],
|
| 239 |
+
"x_norm_patchtokens": x_norm[:, self.n_storage_tokens + 1 :],
|
| 240 |
+
"x_prenorm": x,
|
| 241 |
+
"masks": masks,
|
| 242 |
+
}
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
return output
|
| 246 |
+
|
| 247 |
+
def forward(self, *args, is_training=False, **kwargs):
|
| 248 |
+
ret = self.forward_features(*args, **kwargs)
|
| 249 |
+
if is_training:
|
| 250 |
+
return ret
|
| 251 |
+
else:
|
| 252 |
+
return self.head(ret["x_norm_clstoken"])
|
| 253 |
+
|
| 254 |
+
def _get_intermediate_layers(self, x, n=1):
|
| 255 |
+
h, w = x.shape[-2:]
|
| 256 |
+
output, total_block_len = [], len(self.downsample_layers)
|
| 257 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 258 |
+
for i in range(total_block_len):
|
| 259 |
+
x = self.downsample_layers[i](x)
|
| 260 |
+
x = self.stages[i](x)
|
| 261 |
+
if i in blocks_to_take:
|
| 262 |
+
x_pool = x.mean([-2, -1])
|
| 263 |
+
x_patches = x
|
| 264 |
+
if self.patch_size is not None:
|
| 265 |
+
# Resize output feature maps to that of a ViT with given patch_size
|
| 266 |
+
x_patches = nn.functional.interpolate(
|
| 267 |
+
x,
|
| 268 |
+
size=(h // self.patch_size, w // self.patch_size),
|
| 269 |
+
mode="bilinear",
|
| 270 |
+
antialias=True,
|
| 271 |
+
)
|
| 272 |
+
output.append(
|
| 273 |
+
[
|
| 274 |
+
x_pool, # CLS (B x C)
|
| 275 |
+
x_patches, # B x C x H x W
|
| 276 |
+
]
|
| 277 |
+
)
|
| 278 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 279 |
+
return output
|
| 280 |
+
|
| 281 |
+
def get_intermediate_layers(
|
| 282 |
+
self,
|
| 283 |
+
x,
|
| 284 |
+
n: Union[int, Sequence] = 1, # Layers or n last layers to take,
|
| 285 |
+
reshape: bool = False,
|
| 286 |
+
return_class_token: bool = False,
|
| 287 |
+
norm: bool = True,
|
| 288 |
+
):
|
| 289 |
+
outputs = self._get_intermediate_layers(x, n)
|
| 290 |
+
|
| 291 |
+
if norm:
|
| 292 |
+
nchw_shapes = [out[-1].shape for out in outputs]
|
| 293 |
+
if isinstance(n, int):
|
| 294 |
+
norms = self.norms[-n:]
|
| 295 |
+
else:
|
| 296 |
+
norms = [self.norms[i] for i in n]
|
| 297 |
+
outputs = [
|
| 298 |
+
(
|
| 299 |
+
norm(cls_token), # N x C
|
| 300 |
+
norm(patches.flatten(-2, -1).permute(0, 2, 1)), # N x HW x C
|
| 301 |
+
)
|
| 302 |
+
for (cls_token, patches), norm in zip(outputs, norms)
|
| 303 |
+
]
|
| 304 |
+
if reshape:
|
| 305 |
+
outputs = [
|
| 306 |
+
(cls_token, patches.permute(0, 2, 1).reshape(*nchw).contiguous())
|
| 307 |
+
for (cls_token, patches), nchw in zip(outputs, nchw_shapes)
|
| 308 |
+
]
|
| 309 |
+
elif not reshape:
|
| 310 |
+
# force B x N x C format for patch tokens
|
| 311 |
+
outputs = [(cls_token, patches.flatten(-2, -1).permute(0, 2, 1)) for (cls_token, patches) in outputs]
|
| 312 |
+
class_tokens = [out[0] for out in outputs]
|
| 313 |
+
outputs = [out[1] for out in outputs]
|
| 314 |
+
if return_class_token:
|
| 315 |
+
return tuple(zip(outputs, class_tokens))
|
| 316 |
+
return tuple(outputs)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
convnext_sizes = {
|
| 320 |
+
"tiny": dict(
|
| 321 |
+
depths=[3, 3, 9, 3],
|
| 322 |
+
dims=[96, 192, 384, 768],
|
| 323 |
+
),
|
| 324 |
+
"small": dict(
|
| 325 |
+
depths=[3, 3, 27, 3],
|
| 326 |
+
dims=[96, 192, 384, 768],
|
| 327 |
+
),
|
| 328 |
+
"base": dict(
|
| 329 |
+
depths=[3, 3, 27, 3],
|
| 330 |
+
dims=[128, 256, 512, 1024],
|
| 331 |
+
),
|
| 332 |
+
"large": dict(
|
| 333 |
+
depths=[3, 3, 27, 3],
|
| 334 |
+
dims=[192, 384, 768, 1536],
|
| 335 |
+
),
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def get_convnext_arch(arch_name):
|
| 340 |
+
size_dict = None
|
| 341 |
+
query_sizename = arch_name.split("_")[1]
|
| 342 |
+
try:
|
| 343 |
+
size_dict = convnext_sizes[query_sizename]
|
| 344 |
+
except KeyError:
|
| 345 |
+
raise NotImplementedError("didn't recognize vit size string")
|
| 346 |
+
|
| 347 |
+
return partial(
|
| 348 |
+
ConvNeXt,
|
| 349 |
+
**size_dict,
|
| 350 |
+
)
|
starVLA/dinov3/dinov3/models/vision_transformer.py
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from functools import partial
|
| 8 |
+
from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.init
|
| 12 |
+
from torch import Tensor, nn
|
| 13 |
+
|
| 14 |
+
from dinov3.layers import LayerScale, Mlp, PatchEmbed, RMSNorm, RopePositionEmbedding, SelfAttentionBlock, SwiGLUFFN
|
| 15 |
+
from dinov3.utils import named_apply
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("dinov3")
|
| 18 |
+
|
| 19 |
+
ffn_layer_dict = {
|
| 20 |
+
"mlp": Mlp,
|
| 21 |
+
"swiglu": SwiGLUFFN,
|
| 22 |
+
"swiglu32": partial(SwiGLUFFN, align_to=32),
|
| 23 |
+
"swiglu64": partial(SwiGLUFFN, align_to=64),
|
| 24 |
+
"swiglu128": partial(SwiGLUFFN, align_to=128),
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
norm_layer_dict = {
|
| 28 |
+
"layernorm": partial(nn.LayerNorm, eps=1e-6),
|
| 29 |
+
"layernormbf16": partial(nn.LayerNorm, eps=1e-5),
|
| 30 |
+
"rmsnorm": RMSNorm,
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
dtype_dict = {
|
| 34 |
+
"fp32": torch.float32,
|
| 35 |
+
"fp16": torch.float16,
|
| 36 |
+
"bf16": torch.bfloat16,
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def init_weights_vit(module: nn.Module, name: str = ""):
|
| 41 |
+
if isinstance(module, nn.Linear):
|
| 42 |
+
torch.nn.init.trunc_normal_(module.weight, std=0.02)
|
| 43 |
+
if module.bias is not None:
|
| 44 |
+
nn.init.zeros_(module.bias)
|
| 45 |
+
if hasattr(module, "bias_mask") and module.bias_mask is not None:
|
| 46 |
+
o = module.out_features
|
| 47 |
+
module.bias_mask.fill_(1)
|
| 48 |
+
module.bias_mask[o // 3 : 2 * o // 3].fill_(0)
|
| 49 |
+
if isinstance(module, nn.LayerNorm):
|
| 50 |
+
module.reset_parameters()
|
| 51 |
+
if isinstance(module, LayerScale):
|
| 52 |
+
module.reset_parameters()
|
| 53 |
+
if isinstance(module, PatchEmbed):
|
| 54 |
+
module.reset_parameters()
|
| 55 |
+
if isinstance(module, RMSNorm):
|
| 56 |
+
module.reset_parameters()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class DinoVisionTransformer(nn.Module):
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
*,
|
| 63 |
+
img_size: int = 224,
|
| 64 |
+
patch_size: int = 16,
|
| 65 |
+
in_chans: int = 3,
|
| 66 |
+
pos_embed_rope_base: float = 100.0,
|
| 67 |
+
pos_embed_rope_min_period: float | None = None,
|
| 68 |
+
pos_embed_rope_max_period: float | None = None,
|
| 69 |
+
pos_embed_rope_normalize_coords: Literal["min", "max", "separate"] = "separate",
|
| 70 |
+
pos_embed_rope_shift_coords: float | None = None,
|
| 71 |
+
pos_embed_rope_jitter_coords: float | None = None,
|
| 72 |
+
pos_embed_rope_rescale_coords: float | None = None,
|
| 73 |
+
pos_embed_rope_dtype: str = "bf16",
|
| 74 |
+
embed_dim: int = 768,
|
| 75 |
+
depth: int = 12,
|
| 76 |
+
num_heads: int = 12,
|
| 77 |
+
ffn_ratio: float = 4.0,
|
| 78 |
+
qkv_bias: bool = True,
|
| 79 |
+
drop_path_rate: float = 0.0,
|
| 80 |
+
layerscale_init: float | None = None,
|
| 81 |
+
norm_layer: str = "layernorm",
|
| 82 |
+
ffn_layer: str = "mlp",
|
| 83 |
+
ffn_bias: bool = True,
|
| 84 |
+
proj_bias: bool = True,
|
| 85 |
+
n_storage_tokens: int = 0,
|
| 86 |
+
mask_k_bias: bool = False,
|
| 87 |
+
untie_cls_and_patch_norms: bool = False,
|
| 88 |
+
untie_global_and_local_cls_norm: bool = False,
|
| 89 |
+
device: Any | None = None,
|
| 90 |
+
**ignored_kwargs,
|
| 91 |
+
):
|
| 92 |
+
super().__init__()
|
| 93 |
+
if len(ignored_kwargs) > 0:
|
| 94 |
+
logger.warning(f"Ignored kwargs: {ignored_kwargs}")
|
| 95 |
+
del ignored_kwargs
|
| 96 |
+
|
| 97 |
+
norm_layer_cls = norm_layer_dict[norm_layer]
|
| 98 |
+
|
| 99 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
| 100 |
+
self.n_blocks = depth
|
| 101 |
+
self.num_heads = num_heads
|
| 102 |
+
self.patch_size = patch_size
|
| 103 |
+
|
| 104 |
+
self.patch_embed = PatchEmbed(
|
| 105 |
+
img_size=img_size,
|
| 106 |
+
patch_size=patch_size,
|
| 107 |
+
in_chans=in_chans,
|
| 108 |
+
embed_dim=embed_dim,
|
| 109 |
+
flatten_embedding=False,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.cls_token = nn.Parameter(torch.empty(1, 1, embed_dim, device=device))
|
| 113 |
+
self.n_storage_tokens = n_storage_tokens
|
| 114 |
+
if self.n_storage_tokens > 0:
|
| 115 |
+
self.storage_tokens = nn.Parameter(torch.empty(1, n_storage_tokens, embed_dim, device=device))
|
| 116 |
+
logger.info(f"using base={pos_embed_rope_base} for rope new")
|
| 117 |
+
logger.info(f"using min_period={pos_embed_rope_min_period} for rope new")
|
| 118 |
+
logger.info(f"using max_period={pos_embed_rope_max_period} for rope new")
|
| 119 |
+
logger.info(f"using normalize_coords={pos_embed_rope_normalize_coords} for rope new")
|
| 120 |
+
logger.info(f"using shift_coords={pos_embed_rope_shift_coords} for rope new")
|
| 121 |
+
logger.info(f"using rescale_coords={pos_embed_rope_rescale_coords} for rope new")
|
| 122 |
+
logger.info(f"using jitter_coords={pos_embed_rope_jitter_coords} for rope new")
|
| 123 |
+
logger.info(f"using dtype={pos_embed_rope_dtype} for rope new")
|
| 124 |
+
self.rope_embed = RopePositionEmbedding(
|
| 125 |
+
embed_dim=embed_dim,
|
| 126 |
+
num_heads=num_heads,
|
| 127 |
+
base=pos_embed_rope_base,
|
| 128 |
+
min_period=pos_embed_rope_min_period,
|
| 129 |
+
max_period=pos_embed_rope_max_period,
|
| 130 |
+
normalize_coords=pos_embed_rope_normalize_coords,
|
| 131 |
+
shift_coords=pos_embed_rope_shift_coords,
|
| 132 |
+
jitter_coords=pos_embed_rope_jitter_coords,
|
| 133 |
+
rescale_coords=pos_embed_rope_rescale_coords,
|
| 134 |
+
dtype=dtype_dict[pos_embed_rope_dtype],
|
| 135 |
+
device=device,
|
| 136 |
+
)
|
| 137 |
+
logger.info(f"using {ffn_layer} layer as FFN")
|
| 138 |
+
ffn_layer_cls = ffn_layer_dict[ffn_layer]
|
| 139 |
+
ffn_ratio_sequence = [ffn_ratio] * depth
|
| 140 |
+
blocks_list = [
|
| 141 |
+
SelfAttentionBlock(
|
| 142 |
+
dim=embed_dim,
|
| 143 |
+
num_heads=num_heads,
|
| 144 |
+
ffn_ratio=ffn_ratio_sequence[i],
|
| 145 |
+
qkv_bias=qkv_bias,
|
| 146 |
+
proj_bias=proj_bias,
|
| 147 |
+
ffn_bias=ffn_bias,
|
| 148 |
+
drop_path=drop_path_rate,
|
| 149 |
+
norm_layer=norm_layer_cls,
|
| 150 |
+
act_layer=nn.GELU,
|
| 151 |
+
ffn_layer=ffn_layer_cls,
|
| 152 |
+
init_values=layerscale_init,
|
| 153 |
+
mask_k_bias=mask_k_bias,
|
| 154 |
+
device=device,
|
| 155 |
+
)
|
| 156 |
+
for i in range(depth)
|
| 157 |
+
]
|
| 158 |
+
|
| 159 |
+
self.chunked_blocks = False
|
| 160 |
+
self.blocks = nn.ModuleList(blocks_list)
|
| 161 |
+
|
| 162 |
+
# This norm is applied to everything, or when untying, to patch and mask tokens.
|
| 163 |
+
self.norm = norm_layer_cls(embed_dim)
|
| 164 |
+
|
| 165 |
+
self.untie_cls_and_patch_norms = untie_cls_and_patch_norms
|
| 166 |
+
if untie_cls_and_patch_norms:
|
| 167 |
+
# When untying, this norm is applied to CLS tokens and registers.
|
| 168 |
+
self.cls_norm = norm_layer_cls(embed_dim)
|
| 169 |
+
else:
|
| 170 |
+
self.cls_norm = None
|
| 171 |
+
|
| 172 |
+
self.untie_global_and_local_cls_norm = untie_global_and_local_cls_norm
|
| 173 |
+
if untie_global_and_local_cls_norm:
|
| 174 |
+
# When untying, this norm is applied to local CLS tokens and registers.
|
| 175 |
+
# This norm is never used during eval.
|
| 176 |
+
self.local_cls_norm = norm_layer_cls(embed_dim)
|
| 177 |
+
else:
|
| 178 |
+
self.local_cls_norm = None
|
| 179 |
+
self.head = nn.Identity()
|
| 180 |
+
self.mask_token = nn.Parameter(torch.empty(1, embed_dim, device=device))
|
| 181 |
+
|
| 182 |
+
def init_weights(self):
|
| 183 |
+
self.rope_embed._init_weights()
|
| 184 |
+
nn.init.normal_(self.cls_token, std=0.02)
|
| 185 |
+
if self.n_storage_tokens > 0:
|
| 186 |
+
nn.init.normal_(self.storage_tokens, std=0.02)
|
| 187 |
+
nn.init.zeros_(self.mask_token)
|
| 188 |
+
named_apply(init_weights_vit, self)
|
| 189 |
+
|
| 190 |
+
def prepare_tokens_with_masks(self, x: Tensor, masks=None) -> Tuple[Tensor, Tuple[int]]:
|
| 191 |
+
x = self.patch_embed(x)
|
| 192 |
+
B, H, W, _ = x.shape
|
| 193 |
+
x = x.flatten(1, 2)
|
| 194 |
+
|
| 195 |
+
if masks is not None:
|
| 196 |
+
x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
|
| 197 |
+
cls_token = self.cls_token
|
| 198 |
+
else:
|
| 199 |
+
cls_token = self.cls_token + 0 * self.mask_token
|
| 200 |
+
if self.n_storage_tokens > 0:
|
| 201 |
+
storage_tokens = self.storage_tokens
|
| 202 |
+
else:
|
| 203 |
+
storage_tokens = torch.empty(
|
| 204 |
+
1,
|
| 205 |
+
0,
|
| 206 |
+
cls_token.shape[-1],
|
| 207 |
+
dtype=cls_token.dtype,
|
| 208 |
+
device=cls_token.device,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
x = torch.cat(
|
| 212 |
+
[
|
| 213 |
+
cls_token.expand(B, -1, -1),
|
| 214 |
+
storage_tokens.expand(B, -1, -1),
|
| 215 |
+
x,
|
| 216 |
+
],
|
| 217 |
+
dim=1,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
return x, (H, W)
|
| 221 |
+
|
| 222 |
+
def forward_features_list(self, x_list: List[Tensor], masks_list: List[Tensor]) -> List[Dict[str, Tensor]]:
|
| 223 |
+
x = []
|
| 224 |
+
rope = []
|
| 225 |
+
for t_x, t_masks in zip(x_list, masks_list):
|
| 226 |
+
t2_x, hw_tuple = self.prepare_tokens_with_masks(t_x, t_masks)
|
| 227 |
+
x.append(t2_x)
|
| 228 |
+
rope.append(hw_tuple)
|
| 229 |
+
for _, blk in enumerate(self.blocks):
|
| 230 |
+
if self.rope_embed is not None:
|
| 231 |
+
rope_sincos = [self.rope_embed(H=H, W=W) for H, W in rope]
|
| 232 |
+
else:
|
| 233 |
+
rope_sincos = [None for r in rope]
|
| 234 |
+
x = blk(x, rope_sincos)
|
| 235 |
+
all_x = x
|
| 236 |
+
output = []
|
| 237 |
+
for idx, (x, masks) in enumerate(zip(all_x, masks_list)):
|
| 238 |
+
if self.untie_cls_and_patch_norms or self.untie_global_and_local_cls_norm:
|
| 239 |
+
if self.untie_global_and_local_cls_norm and self.training and idx == 1:
|
| 240 |
+
# Assume second entry of list corresponds to local crops.
|
| 241 |
+
# We only ever apply this during training.
|
| 242 |
+
x_norm_cls_reg = self.local_cls_norm(x[:, : self.n_storage_tokens + 1])
|
| 243 |
+
elif self.untie_cls_and_patch_norms:
|
| 244 |
+
x_norm_cls_reg = self.cls_norm(x[:, : self.n_storage_tokens + 1])
|
| 245 |
+
else:
|
| 246 |
+
x_norm_cls_reg = self.norm(x[:, : self.n_storage_tokens + 1])
|
| 247 |
+
x_norm_patch = self.norm(x[:, self.n_storage_tokens + 1 :])
|
| 248 |
+
else:
|
| 249 |
+
x_norm = self.norm(x)
|
| 250 |
+
x_norm_cls_reg = x_norm[:, : self.n_storage_tokens + 1]
|
| 251 |
+
x_norm_patch = x_norm[:, self.n_storage_tokens + 1 :]
|
| 252 |
+
output.append(
|
| 253 |
+
{
|
| 254 |
+
"x_norm_clstoken": x_norm_cls_reg[:, 0],
|
| 255 |
+
"x_storage_tokens": x_norm_cls_reg[:, 1:],
|
| 256 |
+
"x_norm_patchtokens": x_norm_patch,
|
| 257 |
+
"x_prenorm": x,
|
| 258 |
+
"masks": masks,
|
| 259 |
+
}
|
| 260 |
+
)
|
| 261 |
+
return output
|
| 262 |
+
|
| 263 |
+
def forward_features(self, x: Tensor | List[Tensor], masks: Optional[Tensor] = None) -> List[Dict[str, Tensor]]:
|
| 264 |
+
if isinstance(x, torch.Tensor):
|
| 265 |
+
return self.forward_features_list([x], [masks])[0]
|
| 266 |
+
else:
|
| 267 |
+
return self.forward_features_list(x, masks)
|
| 268 |
+
|
| 269 |
+
def _get_intermediate_layers_not_chunked(self, x: Tensor, n: int = 1) -> List[Tensor]:
|
| 270 |
+
x, (H, W) = self.prepare_tokens_with_masks(x)
|
| 271 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
| 272 |
+
output, total_block_len = [], len(self.blocks)
|
| 273 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 274 |
+
for i, blk in enumerate(self.blocks):
|
| 275 |
+
if self.rope_embed is not None:
|
| 276 |
+
rope_sincos = self.rope_embed(H=H, W=W)
|
| 277 |
+
else:
|
| 278 |
+
rope_sincos = None
|
| 279 |
+
x = blk(x, rope_sincos)
|
| 280 |
+
if i in blocks_to_take:
|
| 281 |
+
output.append(x)
|
| 282 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 283 |
+
return output
|
| 284 |
+
|
| 285 |
+
def get_intermediate_layers(
|
| 286 |
+
self,
|
| 287 |
+
x: torch.Tensor,
|
| 288 |
+
*,
|
| 289 |
+
n: Union[int, Sequence] = 1, # Layers or n last layers to take
|
| 290 |
+
reshape: bool = False,
|
| 291 |
+
return_class_token: bool = False,
|
| 292 |
+
return_extra_tokens: bool = False,
|
| 293 |
+
norm: bool = True,
|
| 294 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor, ...]]]:
|
| 295 |
+
outputs = self._get_intermediate_layers_not_chunked(x, n)
|
| 296 |
+
if norm:
|
| 297 |
+
outputs_normed = []
|
| 298 |
+
for out in outputs:
|
| 299 |
+
if self.untie_cls_and_patch_norms:
|
| 300 |
+
x_norm_cls_reg = self.cls_norm(out[:, : self.n_storage_tokens + 1])
|
| 301 |
+
x_norm_patch = self.norm(out[:, self.n_storage_tokens + 1 :])
|
| 302 |
+
outputs_normed.append(torch.cat((x_norm_cls_reg, x_norm_patch), dim=1))
|
| 303 |
+
else:
|
| 304 |
+
outputs_normed.append(self.norm(out))
|
| 305 |
+
outputs = outputs_normed
|
| 306 |
+
class_tokens = [out[:, 0] for out in outputs]
|
| 307 |
+
extra_tokens = [out[:, 1 : self.n_storage_tokens + 1] for out in outputs]
|
| 308 |
+
outputs = [out[:, self.n_storage_tokens + 1 :] for out in outputs]
|
| 309 |
+
if reshape:
|
| 310 |
+
B, _, h, w = x.shape
|
| 311 |
+
outputs = [
|
| 312 |
+
out.reshape(B, h // self.patch_size, w // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
|
| 313 |
+
for out in outputs
|
| 314 |
+
]
|
| 315 |
+
if not return_class_token and not return_extra_tokens:
|
| 316 |
+
return tuple(outputs)
|
| 317 |
+
elif return_class_token and not return_extra_tokens:
|
| 318 |
+
return tuple(zip(outputs, class_tokens))
|
| 319 |
+
elif not return_class_token and return_extra_tokens:
|
| 320 |
+
return tuple(zip(outputs, extra_tokens))
|
| 321 |
+
elif return_class_token and return_extra_tokens:
|
| 322 |
+
return tuple(zip(outputs, class_tokens, extra_tokens))
|
| 323 |
+
|
| 324 |
+
def forward(self, *args, is_training: bool = False, **kwargs) -> List[Dict[str, Tensor]] | Tensor:
|
| 325 |
+
ret = self.forward_features(*args, **kwargs)
|
| 326 |
+
if is_training:
|
| 327 |
+
return ret
|
| 328 |
+
else:
|
| 329 |
+
return self.head(ret["x_norm_clstoken"])
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def vit_small(patch_size=16, **kwargs):
|
| 333 |
+
model = DinoVisionTransformer(
|
| 334 |
+
patch_size=patch_size,
|
| 335 |
+
embed_dim=384,
|
| 336 |
+
depth=12,
|
| 337 |
+
num_heads=6,
|
| 338 |
+
ffn_ratio=4,
|
| 339 |
+
**kwargs,
|
| 340 |
+
)
|
| 341 |
+
return model
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def vit_base(patch_size=16, **kwargs):
|
| 345 |
+
model = DinoVisionTransformer(
|
| 346 |
+
patch_size=patch_size,
|
| 347 |
+
embed_dim=768,
|
| 348 |
+
depth=12,
|
| 349 |
+
num_heads=12,
|
| 350 |
+
ffn_ratio=4,
|
| 351 |
+
**kwargs,
|
| 352 |
+
)
|
| 353 |
+
return model
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def vit_large(patch_size=16, **kwargs):
|
| 357 |
+
model = DinoVisionTransformer(
|
| 358 |
+
patch_size=patch_size,
|
| 359 |
+
embed_dim=1024,
|
| 360 |
+
depth=24,
|
| 361 |
+
num_heads=16,
|
| 362 |
+
ffn_ratio=4,
|
| 363 |
+
**kwargs,
|
| 364 |
+
)
|
| 365 |
+
return model
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def vit_so400m(patch_size=16, **kwargs):
|
| 369 |
+
model = DinoVisionTransformer(
|
| 370 |
+
patch_size=patch_size,
|
| 371 |
+
embed_dim=1152,
|
| 372 |
+
depth=27,
|
| 373 |
+
num_heads=18,
|
| 374 |
+
ffn_ratio=3.777777778,
|
| 375 |
+
**kwargs,
|
| 376 |
+
)
|
| 377 |
+
return model
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def vit_huge2(patch_size=16, **kwargs):
|
| 381 |
+
model = DinoVisionTransformer(
|
| 382 |
+
patch_size=patch_size,
|
| 383 |
+
embed_dim=1280,
|
| 384 |
+
depth=32,
|
| 385 |
+
num_heads=20,
|
| 386 |
+
ffn_ratio=4,
|
| 387 |
+
**kwargs,
|
| 388 |
+
)
|
| 389 |
+
return model
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def vit_giant2(patch_size=16, **kwargs):
|
| 393 |
+
"""
|
| 394 |
+
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
|
| 395 |
+
"""
|
| 396 |
+
model = DinoVisionTransformer(
|
| 397 |
+
patch_size=patch_size,
|
| 398 |
+
embed_dim=1536,
|
| 399 |
+
depth=40,
|
| 400 |
+
num_heads=24,
|
| 401 |
+
ffn_ratio=4,
|
| 402 |
+
**kwargs,
|
| 403 |
+
)
|
| 404 |
+
return model
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def vit_7b(patch_size=16, **kwargs):
|
| 408 |
+
model = DinoVisionTransformer(
|
| 409 |
+
patch_size=patch_size,
|
| 410 |
+
embed_dim=4096,
|
| 411 |
+
depth=40,
|
| 412 |
+
num_heads=32,
|
| 413 |
+
ffn_ratio=3,
|
| 414 |
+
**kwargs,
|
| 415 |
+
)
|
| 416 |
+
return model
|
starVLA/dinov3/dinov3/run/__init__.py
ADDED
|
File without changes
|
starVLA/dinov3/dinov3/run/init.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import contextlib
|
| 7 |
+
from datetime import timedelta
|
| 8 |
+
from typing import Optional
|
| 9 |
+
|
| 10 |
+
from dinov3.configs import exit_job, setup_job
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@contextlib.contextmanager
|
| 14 |
+
def job_context(
|
| 15 |
+
output_dir: Optional[str] = None,
|
| 16 |
+
distributed_enabled: bool = True,
|
| 17 |
+
logging_enabled: bool = True,
|
| 18 |
+
seed: Optional[int] = 0,
|
| 19 |
+
restrict_print_to_main_process: bool = True,
|
| 20 |
+
distributed_timeout: timedelta | None = None,
|
| 21 |
+
):
|
| 22 |
+
setup_job(
|
| 23 |
+
output_dir=output_dir,
|
| 24 |
+
distributed_enabled=distributed_enabled,
|
| 25 |
+
logging_enabled=logging_enabled,
|
| 26 |
+
seed=seed,
|
| 27 |
+
restrict_print_to_main_process=restrict_print_to_main_process,
|
| 28 |
+
distributed_timeout=distributed_timeout,
|
| 29 |
+
)
|
| 30 |
+
try:
|
| 31 |
+
yield
|
| 32 |
+
finally:
|
| 33 |
+
exit_job(distributed_enabled=distributed_enabled, logging_enabled=logging_enabled)
|
starVLA/dinov3/dinov3/run/submit.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from dinov3.logging import setup_logging
|
| 12 |
+
from dinov3.utils.cluster import (
|
| 13 |
+
get_slurm_account,
|
| 14 |
+
get_slurm_executor_parameters,
|
| 15 |
+
get_slurm_partition,
|
| 16 |
+
get_slurm_qos,
|
| 17 |
+
get_user_checkpoint_path,
|
| 18 |
+
)
|
| 19 |
+
from dinov3.utils.custom_callable import load_custom_callable
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger("dinov3")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_submitit_parser():
|
| 25 |
+
slurm_partition = get_slurm_partition()
|
| 26 |
+
slurm_account = get_slurm_account()
|
| 27 |
+
slurm_qos = get_slurm_qos()
|
| 28 |
+
parser = argparse.ArgumentParser("Submitit arguments", add_help=False)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--ngpus",
|
| 31 |
+
default=8,
|
| 32 |
+
type=int,
|
| 33 |
+
help="Number of gpus to request on each node, default: %(default)s",
|
| 34 |
+
)
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
"--nodes",
|
| 37 |
+
default=1,
|
| 38 |
+
type=int,
|
| 39 |
+
help="Number of nodes to request, default: %(default)s",
|
| 40 |
+
)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--timeout",
|
| 43 |
+
default=2800,
|
| 44 |
+
type=int,
|
| 45 |
+
help="Duration of the job, default: %(default)s",
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
"--slurm-partition",
|
| 49 |
+
default=slurm_partition,
|
| 50 |
+
type=str,
|
| 51 |
+
help="Partition where to submit, default: %(default)s",
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--slurm-qos",
|
| 55 |
+
default=slurm_qos,
|
| 56 |
+
metavar="SLURM_QOS",
|
| 57 |
+
type=str,
|
| 58 |
+
dest="slurm_qos",
|
| 59 |
+
help="slurm QoS to use for jobs in cluster environment, default: %(default)s",
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--slurm-array-parallelism",
|
| 63 |
+
default=256,
|
| 64 |
+
type=int,
|
| 65 |
+
help="Maximum number of jobs that will be executed in parallel, default: %(default)s",
|
| 66 |
+
)
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--slurm-nice",
|
| 69 |
+
default=0,
|
| 70 |
+
type=int,
|
| 71 |
+
help="Adjusted scheduling priority within Slurm, default: %(default)s",
|
| 72 |
+
)
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--slurm-account",
|
| 75 |
+
default=slurm_account,
|
| 76 |
+
type=str,
|
| 77 |
+
help="Slurm account name, default: %(default)s",
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--comment",
|
| 81 |
+
default="",
|
| 82 |
+
type=str,
|
| 83 |
+
help="Comment to pass to scheduler, e.g. priority message, default: '%(default)s'",
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--exclude",
|
| 87 |
+
default="",
|
| 88 |
+
type=str,
|
| 89 |
+
help="Nodes to exclude, default: '%(default)s'",
|
| 90 |
+
)
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
"--output-dir",
|
| 93 |
+
type=str,
|
| 94 |
+
help="output dir",
|
| 95 |
+
)
|
| 96 |
+
return parser
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_run_parser():
|
| 100 |
+
parser = argparse.ArgumentParser("Launcher arguments", parents=[get_submitit_parser()])
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"module_path",
|
| 103 |
+
type=str,
|
| 104 |
+
help="Full path to the program/script to be launched in parallel, "
|
| 105 |
+
"followed by all the arguments for the training script.",
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--callable-name",
|
| 109 |
+
type=str,
|
| 110 |
+
default="main",
|
| 111 |
+
help="Name of the callable to execute in the script",
|
| 112 |
+
)
|
| 113 |
+
return parser
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_shared_folder() -> Path:
|
| 117 |
+
user_checkpoint_path = get_user_checkpoint_path()
|
| 118 |
+
if user_checkpoint_path is None:
|
| 119 |
+
raise RuntimeError("Path to user checkpoint cannot be determined")
|
| 120 |
+
path = user_checkpoint_path / "experiments"
|
| 121 |
+
path.mkdir(exist_ok=True)
|
| 122 |
+
return path
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class CheckpointableSubmitter:
|
| 126 |
+
def __init__(self, module_path, callable_name, args, output_dir):
|
| 127 |
+
self.args = args
|
| 128 |
+
self.callable_name = callable_name
|
| 129 |
+
self.module_path = os.path.realpath(module_path)
|
| 130 |
+
self.output_dir = os.path.realpath(output_dir)
|
| 131 |
+
|
| 132 |
+
def __call__(self):
|
| 133 |
+
self._setup_args()
|
| 134 |
+
callable_ = load_custom_callable(self.module_path, self.callable_name)
|
| 135 |
+
callable_(self.args)
|
| 136 |
+
|
| 137 |
+
def checkpoint(self):
|
| 138 |
+
import submitit
|
| 139 |
+
|
| 140 |
+
logger.info(f"Requeuing {self.callable_name} from {self.module_path} with {self.args}")
|
| 141 |
+
empty_class = type(self)(self.module_path, self.callable_name, self.args, self.output_dir)
|
| 142 |
+
return submitit.helpers.DelayedSubmission(empty_class)
|
| 143 |
+
|
| 144 |
+
def _setup_args(self):
|
| 145 |
+
import submitit
|
| 146 |
+
|
| 147 |
+
job_env = submitit.JobEnvironment()
|
| 148 |
+
self.output_dir = str(self.output_dir).replace("%j", str(job_env.job_id))
|
| 149 |
+
if "--output-dir" not in self.args:
|
| 150 |
+
self.args.insert(0, f"--output-dir={self.output_dir}")
|
| 151 |
+
|
| 152 |
+
# Setup logging with exact same arguments as in fairvit/run/init.py
|
| 153 |
+
# to use lru_cache memoization and avoid setting up the logger twice
|
| 154 |
+
setup_logging(output=self.output_dir, level=logging.INFO)
|
| 155 |
+
logger.info(f"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}")
|
| 156 |
+
logger.info(f"Module Path: {self.module_path}")
|
| 157 |
+
logger.info(f"Callable Name: {self.callable_name}")
|
| 158 |
+
logger.info(f'Args: {" ".join(self.args)}')
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def submit_jobs(class_to_submit, output_dir, submitit_args, name="fairvit"):
|
| 162 |
+
import submitit
|
| 163 |
+
|
| 164 |
+
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
| 165 |
+
executor = submitit.AutoExecutor(folder=output_dir, slurm_max_num_timeout=30)
|
| 166 |
+
|
| 167 |
+
kwargs = {}
|
| 168 |
+
if submitit_args.comment:
|
| 169 |
+
kwargs["slurm_comment"] = submitit_args.comment
|
| 170 |
+
if submitit_args.exclude:
|
| 171 |
+
kwargs["slurm_exclude"] = submitit_args.exclude
|
| 172 |
+
|
| 173 |
+
executor_params = get_slurm_executor_parameters(
|
| 174 |
+
nodes=submitit_args.nodes,
|
| 175 |
+
num_gpus_per_node=submitit_args.ngpus,
|
| 176 |
+
timeout_min=submitit_args.timeout, # max is 60 * 72
|
| 177 |
+
slurm_signal_delay_s=120,
|
| 178 |
+
slurm_partition=submitit_args.slurm_partition,
|
| 179 |
+
slurm_qos=submitit_args.slurm_qos,
|
| 180 |
+
# slurm_account=submitit_args.slurm_account,
|
| 181 |
+
slurm_additional_parameters=dict(nice=submitit_args.slurm_nice),
|
| 182 |
+
**kwargs,
|
| 183 |
+
)
|
| 184 |
+
executor.update_parameters(name=name, **executor_params)
|
| 185 |
+
job = executor.submit(class_to_submit)
|
| 186 |
+
|
| 187 |
+
logger.info(f"Submitted job_id: {job.job_id}")
|
| 188 |
+
str_output_dir = os.path.abspath(output_dir).replace("%j", str(job.job_id))
|
| 189 |
+
logger.info(f"Logs and checkpoints will be saved at: {str_output_dir}")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def main():
|
| 193 |
+
setup_logging(level=logging.INFO)
|
| 194 |
+
args, script_args = get_run_parser().parse_known_args()
|
| 195 |
+
assert os.path.exists(args.module_path), "The module path does not exist"
|
| 196 |
+
|
| 197 |
+
file_name = os.path.splitext(os.path.split(args.module_path)[1])[0]
|
| 198 |
+
name = f"{file_name}:{args.callable_name}"
|
| 199 |
+
|
| 200 |
+
if args.output_dir is None:
|
| 201 |
+
args.output_dir = get_shared_folder() / "%j"
|
| 202 |
+
|
| 203 |
+
class_to_submit = CheckpointableSubmitter(args.module_path, args.callable_name, script_args, args.output_dir)
|
| 204 |
+
submit_jobs(class_to_submit, args.output_dir, args, name=name)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
main()
|
starVLA/dinov3/dinov3/thirdparty/CLIP/__init__.py
ADDED
|
File without changes
|
starVLA/dinov3/dinov3/thirdparty/CLIP/clip/__init__.py
ADDED
|
File without changes
|
starVLA/dinov3/dinov3/thirdparty/CLIP/clip/simple_tokenizer.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
# References:
|
| 7 |
+
# https://github.com/openai/CLIP/blob/main/clip/simple_tokenizer.py
|
| 8 |
+
|
| 9 |
+
import gzip
|
| 10 |
+
import html
|
| 11 |
+
import os
|
| 12 |
+
from functools import lru_cache
|
| 13 |
+
|
| 14 |
+
import ftfy
|
| 15 |
+
import regex as re
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@lru_cache()
|
| 19 |
+
def default_bpe():
|
| 20 |
+
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@lru_cache()
|
| 24 |
+
def bytes_to_unicode():
|
| 25 |
+
"""
|
| 26 |
+
Returns list of utf-8 byte and a corresponding list of unicode strings.
|
| 27 |
+
The reversible bpe codes work on unicode strings.
|
| 28 |
+
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
|
| 29 |
+
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
|
| 30 |
+
This is a signficant percentage of your normal, say, 32K bpe vocab.
|
| 31 |
+
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
| 32 |
+
And avoids mapping to whitespace/control characters the bpe code barfs on.
|
| 33 |
+
"""
|
| 34 |
+
bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
| 35 |
+
cs = bs[:]
|
| 36 |
+
n = 0
|
| 37 |
+
for b in range(2**8):
|
| 38 |
+
if b not in bs:
|
| 39 |
+
bs.append(b)
|
| 40 |
+
cs.append(2**8 + n)
|
| 41 |
+
n += 1
|
| 42 |
+
cs = [chr(n) for n in cs]
|
| 43 |
+
return dict(zip(bs, cs))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_pairs(word):
|
| 47 |
+
"""Return set of symbol pairs in a word.
|
| 48 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 49 |
+
"""
|
| 50 |
+
pairs = set()
|
| 51 |
+
prev_char = word[0]
|
| 52 |
+
for char in word[1:]:
|
| 53 |
+
pairs.add((prev_char, char))
|
| 54 |
+
prev_char = char
|
| 55 |
+
return pairs
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def basic_clean(text):
|
| 59 |
+
text = ftfy.fix_text(text)
|
| 60 |
+
text = html.unescape(html.unescape(text))
|
| 61 |
+
return text.strip()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def whitespace_clean(text):
|
| 65 |
+
text = re.sub(r"\s+", " ", text)
|
| 66 |
+
text = text.strip()
|
| 67 |
+
return text
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class SimpleTokenizer(object):
|
| 71 |
+
def __init__(self, bpe_path: str = default_bpe()):
|
| 72 |
+
self.byte_encoder = bytes_to_unicode()
|
| 73 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 74 |
+
merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
|
| 75 |
+
merges = merges[1 : 49152 - 256 - 2 + 1]
|
| 76 |
+
merges = [tuple(merge.split()) for merge in merges]
|
| 77 |
+
vocab = list(bytes_to_unicode().values())
|
| 78 |
+
vocab = vocab + [v + "</w>" for v in vocab]
|
| 79 |
+
for merge in merges:
|
| 80 |
+
vocab.append("".join(merge))
|
| 81 |
+
vocab.extend(["<|startoftext|>", "<|endoftext|>"])
|
| 82 |
+
self.encoder = dict(zip(vocab, range(len(vocab))))
|
| 83 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 84 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 85 |
+
self.cache = {"<|startoftext|>": "<|startoftext|>", "<|endoftext|>": "<|endoftext|>"}
|
| 86 |
+
self.pat = re.compile(
|
| 87 |
+
r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
|
| 88 |
+
re.IGNORECASE,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def bpe(self, token):
|
| 92 |
+
if token in self.cache:
|
| 93 |
+
return self.cache[token]
|
| 94 |
+
word = tuple(token[:-1]) + (token[-1] + "</w>",)
|
| 95 |
+
pairs = get_pairs(word)
|
| 96 |
+
|
| 97 |
+
if not pairs:
|
| 98 |
+
return token + "</w>"
|
| 99 |
+
|
| 100 |
+
while True:
|
| 101 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 102 |
+
if bigram not in self.bpe_ranks:
|
| 103 |
+
break
|
| 104 |
+
first, second = bigram
|
| 105 |
+
new_word = []
|
| 106 |
+
i = 0
|
| 107 |
+
while i < len(word):
|
| 108 |
+
try:
|
| 109 |
+
j = word.index(first, i)
|
| 110 |
+
new_word.extend(word[i:j])
|
| 111 |
+
i = j
|
| 112 |
+
except Exception:
|
| 113 |
+
new_word.extend(word[i:])
|
| 114 |
+
break
|
| 115 |
+
|
| 116 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 117 |
+
new_word.append(first + second)
|
| 118 |
+
i += 2
|
| 119 |
+
else:
|
| 120 |
+
new_word.append(word[i])
|
| 121 |
+
i += 1
|
| 122 |
+
new_word = tuple(new_word)
|
| 123 |
+
word = new_word
|
| 124 |
+
if len(word) == 1:
|
| 125 |
+
break
|
| 126 |
+
else:
|
| 127 |
+
pairs = get_pairs(word)
|
| 128 |
+
word = " ".join(word)
|
| 129 |
+
self.cache[token] = word
|
| 130 |
+
return word
|
| 131 |
+
|
| 132 |
+
def encode(self, text):
|
| 133 |
+
bpe_tokens = []
|
| 134 |
+
text = whitespace_clean(basic_clean(text)).lower()
|
| 135 |
+
for token in re.findall(self.pat, text):
|
| 136 |
+
token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
|
| 137 |
+
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" "))
|
| 138 |
+
return bpe_tokens
|
| 139 |
+
|
| 140 |
+
def decode(self, tokens):
|
| 141 |
+
text = "".join([self.decoder[token] for token in tokens])
|
| 142 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors="replace").replace("</w>", " ")
|
| 143 |
+
return text
|
starVLA/dinov3/dinov3/thirdparty/__init__.py
ADDED
|
File without changes
|
starVLA/dinov3/dinov3/train/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from .multidist_meta_arch import MultiDistillationMetaArch
|
| 7 |
+
from .ssl_meta_arch import SSLMetaArch
|
| 8 |
+
from .train import get_args_parser, main
|
starVLA/dinov3/dinov3/train/cosine_lr_scheduler.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger("dinov3")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class CosineScheduler(object):
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
base_value,
|
| 17 |
+
final_value,
|
| 18 |
+
total_iters,
|
| 19 |
+
warmup_iters=0,
|
| 20 |
+
start_warmup_value=0,
|
| 21 |
+
freeze_iters=0,
|
| 22 |
+
trunc_extra=0.0,
|
| 23 |
+
):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.final_value = np.float64(final_value)
|
| 26 |
+
self.total_iters = total_iters
|
| 27 |
+
|
| 28 |
+
freeze_schedule = np.zeros((freeze_iters))
|
| 29 |
+
|
| 30 |
+
warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
|
| 31 |
+
|
| 32 |
+
if trunc_extra == 0.0:
|
| 33 |
+
iters = np.arange(total_iters - warmup_iters - freeze_iters)
|
| 34 |
+
schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters)))
|
| 35 |
+
else:
|
| 36 |
+
cosine_steps = total_iters - warmup_iters - freeze_iters
|
| 37 |
+
iters = np.linspace(0, np.pi, int((1 + trunc_extra) * cosine_steps))[:cosine_steps]
|
| 38 |
+
schedule = np.cos(iters)
|
| 39 |
+
schedule = (schedule + 1) / 2
|
| 40 |
+
schedule = (schedule - schedule[-1]) / (1 - schedule[-1])
|
| 41 |
+
schedule = schedule * (base_value - final_value) + final_value
|
| 42 |
+
|
| 43 |
+
self.schedule = np.concatenate((freeze_schedule, warmup_schedule, schedule), dtype=np.float64)
|
| 44 |
+
|
| 45 |
+
assert len(self.schedule) == self.total_iters
|
| 46 |
+
|
| 47 |
+
def __getitem__(self, it):
|
| 48 |
+
if it >= self.total_iters:
|
| 49 |
+
return self.final_value
|
| 50 |
+
else:
|
| 51 |
+
return self.schedule[it]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def linear_warmup_cosine_decay(
|
| 55 |
+
start: float,
|
| 56 |
+
peak: float,
|
| 57 |
+
end: float,
|
| 58 |
+
warmup_iterations: int,
|
| 59 |
+
total_iterations: int,
|
| 60 |
+
cosine_iterations: int | None = None,
|
| 61 |
+
) -> np.ndarray:
|
| 62 |
+
"""
|
| 63 |
+
Create a learning rate schedule with linear warmup, a cosine, and an optional constant part in the end.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
start (float): Initial learning rate.
|
| 67 |
+
peak (float): Learning rate after linear warmup.
|
| 68 |
+
end (float): Final learning rate after cosine.
|
| 69 |
+
warmup_iterations (int): Number of iterations for linear warmup.
|
| 70 |
+
total_iterations (int): Total number of iterations for the schedule.
|
| 71 |
+
cosine_iterations (int | None): Number of iterations for cosine.
|
| 72 |
+
If None, cosine part will be over remaining iterations after warmup.
|
| 73 |
+
Returns:
|
| 74 |
+
np.ndarray: Learning rate schedule as a numpy array.
|
| 75 |
+
"""
|
| 76 |
+
linear = np.linspace(start, peak, warmup_iterations, endpoint=False)
|
| 77 |
+
if cosine_iterations is None:
|
| 78 |
+
cosine_iterations = total_iterations - warmup_iterations
|
| 79 |
+
cosine = np.cos(np.linspace(0, np.pi, cosine_iterations))
|
| 80 |
+
cosine = (cosine + 1) / 2
|
| 81 |
+
cosine = (peak - end) * cosine + end
|
| 82 |
+
remaining_iterations = total_iterations - cosine_iterations - warmup_iterations
|
| 83 |
+
assert remaining_iterations >= 0
|
| 84 |
+
constant = np.full((remaining_iterations,), fill_value=end)
|
| 85 |
+
return np.concatenate([linear, cosine, constant])
|
starVLA/dinov3/dinov3/train/multidist_meta_arch.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
|
| 11 |
+
from .ssl_meta_arch import SSLMetaArch
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger("dinov3")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MultiDistillationMetaArch(SSLMetaArch):
|
| 17 |
+
"""
|
| 18 |
+
Multidistillation version of SSLMetaArchCompilableGram:
|
| 19 |
+
- baked-in scales for DINO, KOLEO, and IBOT losses
|
| 20 |
+
- always global and local crops
|
| 21 |
+
- always separate heads for DINO and IBOT
|
| 22 |
+
- always sinkhorn-knopp centering for DINO and IBOT
|
| 23 |
+
- always per-GPU computation of KOLEO loss (non-distributed)
|
| 24 |
+
- DINO, IBOT, and KOLEO are always computed even if their weight is 0.0
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def forward_backward(
|
| 28 |
+
self, data, *, teacher_temp, iteration: int = 0, **ignored_kwargs
|
| 29 |
+
) -> tuple[Tensor, dict[str, float | Tensor]]:
|
| 30 |
+
del ignored_kwargs
|
| 31 |
+
metrics_dict = {}
|
| 32 |
+
|
| 33 |
+
# Shapes
|
| 34 |
+
n_global_crops = 2
|
| 35 |
+
n_local_crops = self.n_local_crops # self.cfg.crops.local_crops_number
|
| 36 |
+
B_teacher = B = data["collated_local_crops"].shape[0] // n_local_crops
|
| 37 |
+
assert data["collated_global_crops"].shape[0] == n_global_crops * B
|
| 38 |
+
metrics_dict["batch_size"] = B
|
| 39 |
+
|
| 40 |
+
global_crops = data["collated_global_crops"].cuda(non_blocking=True)
|
| 41 |
+
local_crops = data["collated_local_crops"].cuda(non_blocking=True)
|
| 42 |
+
masks = data["collated_masks"].cuda(non_blocking=True)
|
| 43 |
+
mask_indices_list = data["mask_indices_list"].cuda(non_blocking=True)
|
| 44 |
+
masks_weight = data["masks_weight"].cuda(non_blocking=True)
|
| 45 |
+
n_masked_patches_tensor = data["n_masked_patches"].cuda(non_blocking=True)
|
| 46 |
+
global_batch_size = data["global_batch_size"]
|
| 47 |
+
|
| 48 |
+
# Multidistillation codepath:
|
| 49 |
+
|
| 50 |
+
# Downsample teacher crops to match student resolution
|
| 51 |
+
downsampling_factor = getattr(self, "crops.teacher_to_student_resolution_scale", 1.0)
|
| 52 |
+
if downsampling_factor != 1.0:
|
| 53 |
+
global_crops = torch.nn.functional.interpolate(
|
| 54 |
+
global_crops,
|
| 55 |
+
scale_factor=1.0 / downsampling_factor,
|
| 56 |
+
mode="bilinear",
|
| 57 |
+
antialias=True,
|
| 58 |
+
)
|
| 59 |
+
global_crops_subgroup = self.broadcast_to_subgroups(
|
| 60 |
+
global_crops.view(n_global_crops, -1, *global_crops.shape[1:]),
|
| 61 |
+
1,
|
| 62 |
+
global_batch_size=global_batch_size,
|
| 63 |
+
).view(-1, *global_crops.shape[1:])
|
| 64 |
+
local_crops_subgroup = self.broadcast_to_subgroups(
|
| 65 |
+
local_crops.view(n_local_crops, -1, *local_crops.shape[1:]),
|
| 66 |
+
1,
|
| 67 |
+
global_batch_size=global_batch_size,
|
| 68 |
+
).view(-1, *local_crops.shape[1:])
|
| 69 |
+
B = local_crops_subgroup.shape[0] // n_local_crops
|
| 70 |
+
|
| 71 |
+
# Teacher output (will trigger an all-gather to unshard)
|
| 72 |
+
teacher_global = self.get_teacher_output(
|
| 73 |
+
global_crops.unflatten(0, (n_global_crops, B_teacher)),
|
| 74 |
+
teacher_temp=teacher_temp,
|
| 75 |
+
n_masked_patches_tensor=n_masked_patches_tensor,
|
| 76 |
+
mask_indices_list=mask_indices_list,
|
| 77 |
+
upperbound=data["upperbound"],
|
| 78 |
+
global_batch_size=global_batch_size,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# Student output (will trigger an all-gather to unshard)
|
| 82 |
+
student_global, student_local = self.get_student_output(
|
| 83 |
+
global_crops=global_crops_subgroup.unflatten(0, (n_global_crops, B)),
|
| 84 |
+
local_crops=local_crops_subgroup.unflatten(0, (n_local_crops, B)),
|
| 85 |
+
upperbound=data["upperbound"],
|
| 86 |
+
masks=masks,
|
| 87 |
+
mask_indices_list=mask_indices_list,
|
| 88 |
+
)
|
| 89 |
+
# End of multidistillation codepath
|
| 90 |
+
|
| 91 |
+
# Compute losses and backprop
|
| 92 |
+
loss_accumulator, loss_dict = self.compute_losses(
|
| 93 |
+
teacher_global=teacher_global,
|
| 94 |
+
student_global=student_global,
|
| 95 |
+
student_local=student_local,
|
| 96 |
+
masks=masks,
|
| 97 |
+
mask_indices_list=mask_indices_list,
|
| 98 |
+
masks_weight=masks_weight,
|
| 99 |
+
gram_global=None,
|
| 100 |
+
iteration=iteration,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
self.backprop_loss(loss_accumulator)
|
| 104 |
+
|
| 105 |
+
# Return total weighted loss and a dict of metrics to log
|
| 106 |
+
return loss_accumulator, metrics_dict | loss_dict
|
| 107 |
+
|
| 108 |
+
@torch.no_grad()
|
| 109 |
+
def get_teacher_output(
|
| 110 |
+
self,
|
| 111 |
+
images,
|
| 112 |
+
*,
|
| 113 |
+
upperbound,
|
| 114 |
+
mask_indices_list,
|
| 115 |
+
teacher_temp,
|
| 116 |
+
n_masked_patches_tensor,
|
| 117 |
+
global_batch_size,
|
| 118 |
+
):
|
| 119 |
+
n_crops, B_teacher, rgb, H, W = images.shape
|
| 120 |
+
|
| 121 |
+
backbone_out = self.teacher.backbone(images.flatten(0, 1), is_training=True)
|
| 122 |
+
cls = backbone_out["x_norm_clstoken"] # [n_crops * B, D]
|
| 123 |
+
reg = backbone_out["x_storage_tokens"] # [n_crops * B, R, D]
|
| 124 |
+
ibot_patch = backbone_out["x_norm_patchtokens"] # [n_crops * B, P, D]
|
| 125 |
+
|
| 126 |
+
R, D = reg.shape[-2:]
|
| 127 |
+
|
| 128 |
+
# Multidistillation codepath:
|
| 129 |
+
# IBOT head only on patches that are masked for the student
|
| 130 |
+
n_tokens = ibot_patch.shape[1]
|
| 131 |
+
masked_patch_after_head = self.teacher.ibot_head(ibot_patch.flatten(0, 1), no_last_layer=True)
|
| 132 |
+
masked_patch_after_head = masked_patch_after_head.view(n_crops, -1, *masked_patch_after_head.shape[1:])
|
| 133 |
+
masked_patch_after_head = self.broadcast_to_subgroups(
|
| 134 |
+
masked_patch_after_head,
|
| 135 |
+
over_dim=1,
|
| 136 |
+
global_batch_size=global_batch_size * n_tokens,
|
| 137 |
+
)
|
| 138 |
+
buffer = torch.index_select(masked_patch_after_head.flatten(0, 1), dim=0, index=mask_indices_list)
|
| 139 |
+
masked_patch_after_head = self.teacher.ibot_head(buffer, only_last_layer=True)
|
| 140 |
+
|
| 141 |
+
# DINO head on CLS tokens
|
| 142 |
+
cls_after_head = self.teacher.dino_head(cls, no_last_layer=True) # [n_crops * B, K]
|
| 143 |
+
cls_after_head = cls_after_head.view(n_crops, -1, *cls_after_head.shape[1:])
|
| 144 |
+
cls_after_head = self.broadcast_to_subgroups(cls_after_head, over_dim=1, global_batch_size=global_batch_size)
|
| 145 |
+
B = cls_after_head.shape[1]
|
| 146 |
+
cls_after_head = cls_after_head.flatten(0, 1)
|
| 147 |
+
cls_after_head = self.teacher.dino_head(cls_after_head, only_last_layer=True) # [n_crops * B, K]
|
| 148 |
+
# End of multidistillation codepath
|
| 149 |
+
|
| 150 |
+
# Center with sinkhorn-knopp
|
| 151 |
+
cls_centered = self.dino_loss.sinkhorn_knopp_teacher(
|
| 152 |
+
cls_after_head, teacher_temp=teacher_temp
|
| 153 |
+
) # [n_crops * B, K]
|
| 154 |
+
cls_centered = cls_centered.unflatten(0, (n_crops, B)) # [n_crops, B, K]
|
| 155 |
+
masked_patch_centered = self.ibot_patch_loss.sinkhorn_knopp_teacher(
|
| 156 |
+
masked_patch_after_head,
|
| 157 |
+
teacher_temp=teacher_temp,
|
| 158 |
+
n_masked_patches_tensor=n_masked_patches_tensor,
|
| 159 |
+
) # [n_masked_patches, K]
|
| 160 |
+
|
| 161 |
+
return {
|
| 162 |
+
"cls_after_head": cls_after_head.unflatten(0, [n_crops, B]), # [n_crops, B, K]
|
| 163 |
+
"cls_centered": cls_centered, # [n_crops, B, K]
|
| 164 |
+
"masked_patch_centered": masked_patch_centered, # [n_masked_patches, K]
|
| 165 |
+
}
|
starVLA/dinov3/dinov3/train/param_groups.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger("dinov3")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_vit_lr_decay_rate(
|
| 13 |
+
name,
|
| 14 |
+
lr_decay_rate=1.0,
|
| 15 |
+
num_layers=12,
|
| 16 |
+
force_is_backbone=False,
|
| 17 |
+
chunked_blocks=False,
|
| 18 |
+
):
|
| 19 |
+
"""
|
| 20 |
+
Calculate lr decay rate for different ViT blocks.
|
| 21 |
+
Args:
|
| 22 |
+
name (string): parameter name.
|
| 23 |
+
lr_decay_rate (float): base lr decay rate.
|
| 24 |
+
num_layers (int): number of ViT blocks.
|
| 25 |
+
Returns:
|
| 26 |
+
lr decay rate for the given parameter.
|
| 27 |
+
"""
|
| 28 |
+
layer_id = num_layers + 1
|
| 29 |
+
if name.startswith("backbone") or force_is_backbone:
|
| 30 |
+
if (
|
| 31 |
+
".pos_embed" in name
|
| 32 |
+
or ".patch_embed" in name
|
| 33 |
+
or ".mask_token" in name
|
| 34 |
+
or ".cls_token" in name
|
| 35 |
+
or ".storage_tokens" in name
|
| 36 |
+
):
|
| 37 |
+
layer_id = 0
|
| 38 |
+
elif force_is_backbone and (
|
| 39 |
+
"pos_embed" in name
|
| 40 |
+
or "patch_embed" in name
|
| 41 |
+
or "mask_token" in name
|
| 42 |
+
or "cls_token" in name
|
| 43 |
+
or "storage_tokens" in name
|
| 44 |
+
):
|
| 45 |
+
layer_id = 0
|
| 46 |
+
elif ".blocks." in name and ".residual." not in name:
|
| 47 |
+
layer_id = int(name[name.find(".blocks.") :].split(".")[2]) + 1
|
| 48 |
+
elif chunked_blocks and "blocks." in name and "residual." not in name:
|
| 49 |
+
layer_id = int(name[name.find("blocks.") :].split(".")[2]) + 1
|
| 50 |
+
elif "blocks." in name and "residual." not in name:
|
| 51 |
+
layer_id = int(name[name.find("blocks.") :].split(".")[1]) + 1
|
| 52 |
+
|
| 53 |
+
return lr_decay_rate ** (num_layers + 1 - layer_id)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_params_groups_with_decay(model, lr_decay_rate=1.0, patch_embed_lr_mult=1.0, dino_head_wd_multiplier=1.0):
|
| 57 |
+
chunked_blocks = False
|
| 58 |
+
if hasattr(model, "n_blocks"):
|
| 59 |
+
logger.info("chunked fsdp")
|
| 60 |
+
n_blocks = model.n_blocks
|
| 61 |
+
chunked_blocks = model.chunked_blocks
|
| 62 |
+
elif hasattr(model, "blocks"):
|
| 63 |
+
logger.info("first code branch")
|
| 64 |
+
n_blocks = len(model.blocks)
|
| 65 |
+
elif hasattr(model, "backbone"):
|
| 66 |
+
logger.info("second code branch")
|
| 67 |
+
n_blocks = len(model.backbone.blocks)
|
| 68 |
+
else:
|
| 69 |
+
logger.info("else code branch")
|
| 70 |
+
n_blocks = 0
|
| 71 |
+
all_param_groups = []
|
| 72 |
+
|
| 73 |
+
for name, param in model.named_parameters():
|
| 74 |
+
name = remove_fsdp_compile_names(name)
|
| 75 |
+
if not param.requires_grad:
|
| 76 |
+
continue
|
| 77 |
+
decay_rate = get_vit_lr_decay_rate(
|
| 78 |
+
name,
|
| 79 |
+
lr_decay_rate,
|
| 80 |
+
num_layers=n_blocks,
|
| 81 |
+
force_is_backbone=n_blocks > 0,
|
| 82 |
+
chunked_blocks=chunked_blocks,
|
| 83 |
+
)
|
| 84 |
+
d = {
|
| 85 |
+
"name": name,
|
| 86 |
+
"params": param,
|
| 87 |
+
"is_last_layer": False,
|
| 88 |
+
"lr_multiplier": decay_rate,
|
| 89 |
+
"wd_multiplier": 1.0,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
if "dino_head" in name:
|
| 93 |
+
d["wd_multiplier"] = dino_head_wd_multiplier
|
| 94 |
+
|
| 95 |
+
if "last_layer" in name:
|
| 96 |
+
d["is_last_layer"] = True
|
| 97 |
+
|
| 98 |
+
# No weight-decay on biases, norm parameters, layer scale gamma, learned tokens and embeddings
|
| 99 |
+
if name.endswith("bias") or "norm" in name or "gamma" in name or "fourier_w" in name:
|
| 100 |
+
d["wd_multiplier"] = 0.0
|
| 101 |
+
|
| 102 |
+
if "patch_embed" in name:
|
| 103 |
+
d["lr_multiplier"] *= patch_embed_lr_mult
|
| 104 |
+
|
| 105 |
+
all_param_groups.append(d)
|
| 106 |
+
logger.info(f"{name}: lr_multiplier: {d['lr_multiplier']}, wd_multiplier: {d['wd_multiplier']}")
|
| 107 |
+
|
| 108 |
+
return all_param_groups
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def fuse_params_groups(all_params_groups, keys=("lr_multiplier", "wd_multiplier", "is_last_layer")):
|
| 112 |
+
fused_params_groups = defaultdict(lambda: {"params": []})
|
| 113 |
+
for d in all_params_groups:
|
| 114 |
+
identifier = ""
|
| 115 |
+
for k in keys:
|
| 116 |
+
identifier += k + str(d[k]) + "_"
|
| 117 |
+
|
| 118 |
+
for k in keys:
|
| 119 |
+
fused_params_groups[identifier][k] = d[k]
|
| 120 |
+
fused_params_groups[identifier]["params"].append(d["params"])
|
| 121 |
+
|
| 122 |
+
return fused_params_groups.values()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
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):
|
| 126 |
+
if hasattr(model, "module"): # SimpleFSDP
|
| 127 |
+
is_backbone = hasattr(model.module, "blocks")
|
| 128 |
+
n_blocks = len(model.module.blocks) if is_backbone else 0
|
| 129 |
+
else: # FSDP2
|
| 130 |
+
is_backbone = hasattr(model, "blocks")
|
| 131 |
+
n_blocks = len(model.blocks) if is_backbone else 0
|
| 132 |
+
|
| 133 |
+
all_param_groups = []
|
| 134 |
+
|
| 135 |
+
for name, param in model.named_parameters():
|
| 136 |
+
name = remove_fsdp_compile_names(name)
|
| 137 |
+
if not param.requires_grad:
|
| 138 |
+
continue
|
| 139 |
+
decay_rate = get_vit_lr_decay_rate(
|
| 140 |
+
name,
|
| 141 |
+
lr_decay_rate,
|
| 142 |
+
num_layers=n_blocks,
|
| 143 |
+
force_is_backbone=n_blocks > 0,
|
| 144 |
+
chunked_blocks=False,
|
| 145 |
+
)
|
| 146 |
+
d = {
|
| 147 |
+
"name": name,
|
| 148 |
+
"params": param,
|
| 149 |
+
"is_last_layer": False,
|
| 150 |
+
"lr_multiplier": decay_rate,
|
| 151 |
+
"wd_multiplier": 1.0,
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
if "dino_head" in name:
|
| 155 |
+
d["wd_multiplier"] = dino_head_wd_multiplier
|
| 156 |
+
|
| 157 |
+
if "last_layer" in name:
|
| 158 |
+
d["is_last_layer"] = True
|
| 159 |
+
|
| 160 |
+
# No weight-decay on biases, norm parameters, layer scale gamma, learned tokens and embeddings
|
| 161 |
+
if name.endswith("bias") or "norm" in name or "gamma" in name or "fourier_w" in name:
|
| 162 |
+
d["wd_multiplier"] = 0.0
|
| 163 |
+
|
| 164 |
+
if "patch_embed" in name:
|
| 165 |
+
d["lr_multiplier"] *= patch_embed_lr_mult
|
| 166 |
+
|
| 167 |
+
all_param_groups.append(d)
|
| 168 |
+
logger.info(f"{name}: lr_multiplier: {d['lr_multiplier']}, wd_multiplier: {d['wd_multiplier']}")
|
| 169 |
+
|
| 170 |
+
return all_param_groups
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def remove_fsdp_compile_names(name: str):
|
| 174 |
+
name = name.replace("_fsdp_wrapped_module.", "") # Added by FSDP
|
| 175 |
+
name = name.replace("_checkpoint_wrapped_module.", "") # Added by activation checkpointing for xFSDP
|
| 176 |
+
name = name.replace("parametrizations.", "") # Added by xFSDP
|
| 177 |
+
name = name.removesuffix(".original") # Added by xFSDP
|
| 178 |
+
name = name.replace("module.", "") # Added by xFSDP
|
| 179 |
+
name = name.replace("_orig_mod.", "") # Added by torch.compile
|
| 180 |
+
return name
|
starVLA/dinov3/dinov3/train/ssl_meta_arch.py
ADDED
|
@@ -0,0 +1,820 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import gc
|
| 7 |
+
import logging
|
| 8 |
+
from functools import partial
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from omegaconf import OmegaConf
|
| 12 |
+
from torch import Tensor, nn
|
| 13 |
+
|
| 14 |
+
import dinov3.distributed as distributed
|
| 15 |
+
from dinov3.checkpointer import init_fsdp_model_from_checkpoint
|
| 16 |
+
from dinov3.configs import get_default_config
|
| 17 |
+
from dinov3.data import DataAugmentationDINO
|
| 18 |
+
from dinov3.fsdp.ac_compile_parallelize import ac_compile_parallelize
|
| 19 |
+
from dinov3.layers.dino_head import DINOHead
|
| 20 |
+
from dinov3.loss import DINOLoss, GramLoss, KoLeoLoss, KoLeoLossDistributed, iBOTPatchLoss
|
| 21 |
+
from dinov3.models import build_model_from_cfg
|
| 22 |
+
from dinov3.train.cosine_lr_scheduler import linear_warmup_cosine_decay
|
| 23 |
+
from dinov3.train.param_groups import fuse_params_groups, get_params_groups_with_decay_fsdp
|
| 24 |
+
from dinov3.utils import count_parameters
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger("dinov3")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SSLMetaArch(nn.Module):
|
| 30 |
+
"""
|
| 31 |
+
Modified version of SSLMetaArchCompilable including gram loss:
|
| 32 |
+
- Gram loss is used only if gram.use_loss is set to true
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, cfg):
|
| 36 |
+
super().__init__()
|
| 37 |
+
|
| 38 |
+
# assert cfg.multidistillation.enabled is False
|
| 39 |
+
assert cfg.crops.local_crops_number > 0
|
| 40 |
+
assert cfg.ibot.separate_head is True
|
| 41 |
+
assert cfg.train.centering == "sinkhorn_knopp"
|
| 42 |
+
|
| 43 |
+
# For some reason FULL_SHARD doesn't work
|
| 44 |
+
assert cfg.compute_precision.sharding_strategy == "SHARD_GRAD_OP"
|
| 45 |
+
|
| 46 |
+
self.cfg = cfg
|
| 47 |
+
|
| 48 |
+
student_model_dict = dict()
|
| 49 |
+
teacher_model_dict = dict()
|
| 50 |
+
gram_model_dict = dict()
|
| 51 |
+
|
| 52 |
+
student_backbone, teacher_backbone, embed_dim = build_model_from_cfg(cfg)
|
| 53 |
+
torch.cuda.empty_cache()
|
| 54 |
+
gc.collect()
|
| 55 |
+
gram_backbone, _ = build_model_from_cfg(cfg, only_teacher=True)
|
| 56 |
+
logger.info(f"Number of parameters: {count_parameters(student_backbone)}")
|
| 57 |
+
student_model_dict["backbone"] = student_backbone
|
| 58 |
+
teacher_model_dict["backbone"] = teacher_backbone
|
| 59 |
+
gram_model_dict["backbone"] = gram_backbone
|
| 60 |
+
logger.info(f"OPTIONS -- architecture : embed_dim: {embed_dim}")
|
| 61 |
+
|
| 62 |
+
self.embed_dim = embed_dim # D
|
| 63 |
+
self.dino_out_dim = cfg.dino.head_n_prototypes # K
|
| 64 |
+
|
| 65 |
+
logger.info("OPTIONS -- DINO")
|
| 66 |
+
logger.info(f"OPTIONS -- DINO -- loss_weight: {cfg.dino.loss_weight}")
|
| 67 |
+
logger.info(f"OPTIONS -- DINO -- global_ignore_diagonal: {cfg.dino.global_ignore_diagonal}")
|
| 68 |
+
logger.info(f"OPTIONS -- DINO -- head_n_prototypes: {cfg.dino.head_n_prototypes}")
|
| 69 |
+
logger.info(f"OPTIONS -- DINO -- head_bottleneck_dim: {cfg.dino.head_bottleneck_dim}")
|
| 70 |
+
logger.info(f"OPTIONS -- DINO -- head_hidden_dim: {cfg.dino.head_hidden_dim}")
|
| 71 |
+
logger.info(f"OPTIONS -- DINO -- head_norm_last_layer: {cfg.dino.head_norm_last_layer}")
|
| 72 |
+
dino_head_class = partial(
|
| 73 |
+
DINOHead,
|
| 74 |
+
in_dim=embed_dim,
|
| 75 |
+
out_dim=cfg.dino.head_n_prototypes,
|
| 76 |
+
hidden_dim=cfg.dino.head_hidden_dim,
|
| 77 |
+
bottleneck_dim=cfg.dino.head_bottleneck_dim,
|
| 78 |
+
nlayers=cfg.dino.head_nlayers,
|
| 79 |
+
)
|
| 80 |
+
student_model_dict["dino_head"] = dino_head_class()
|
| 81 |
+
teacher_model_dict["dino_head"] = dino_head_class()
|
| 82 |
+
self.dino_loss = DINOLoss(self.dino_out_dim)
|
| 83 |
+
|
| 84 |
+
logger.info("OPTIONS -- KOLEO")
|
| 85 |
+
logger.info(f"OPTIONS -- KOLEO -- loss_weight: {cfg.dino.koleo_loss_weight}")
|
| 86 |
+
logger.info(f"OPTIONS -- KOLEO -- distributed: {cfg.dino.koleo_loss_distributed}")
|
| 87 |
+
if cfg.dino.koleo_loss_distributed:
|
| 88 |
+
logger.info(f"OPTIONS -- KOLEO -- topk: {cfg.dino.koleo_topk}")
|
| 89 |
+
logger.info(
|
| 90 |
+
f"OPTIONS -- KOLEO -- distributed_loss_group_size: {cfg.dino.koleo_distributed_loss_group_size}"
|
| 91 |
+
)
|
| 92 |
+
assert cfg.dino.koleo_distributed_replicas == 0, (
|
| 93 |
+
"Option `dino.koleo_distributed_replicas` is no longer supported"
|
| 94 |
+
)
|
| 95 |
+
self.koleo_loss = KoLeoLossDistributed(
|
| 96 |
+
topk=cfg.dino.koleo_topk,
|
| 97 |
+
loss_group_size=cfg.dino.koleo_distributed_loss_group_size,
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
assert cfg.dino.koleo_topk == 1, "Non-distributed KoLeo loss only supports `dino.koleo_topk=1`"
|
| 101 |
+
self.koleo_loss = KoLeoLoss()
|
| 102 |
+
|
| 103 |
+
logger.info("OPTIONS -- IBOT")
|
| 104 |
+
logger.info(f"OPTIONS -- IBOT -- loss_weight: {cfg.ibot.loss_weight}")
|
| 105 |
+
logger.info(f"OPTIONS -- IBOT masking -- ibot_mask_ratio_tuple: {cfg.ibot.mask_ratio_min_max}")
|
| 106 |
+
logger.info(f"OPTIONS -- IBOT masking -- ibot_mask_sample_probability: {cfg.ibot.mask_sample_probability}")
|
| 107 |
+
|
| 108 |
+
assert 0 <= cfg.ibot.mask_ratio_min_max[0] < cfg.ibot.mask_ratio_min_max[1] <= 1, (
|
| 109 |
+
"provide a valid cfg.ibot.mask_ratio_min_max"
|
| 110 |
+
)
|
| 111 |
+
assert 0 <= cfg.ibot.mask_sample_probability <= 1, "provide a positive mask probability for ibot"
|
| 112 |
+
logger.info(f"OPTIONS -- IBOT -- head_n_prototypes: {cfg.ibot.head_n_prototypes}")
|
| 113 |
+
logger.info(f"OPTIONS -- IBOT -- head_bottleneck_dim: {cfg.ibot.head_bottleneck_dim}")
|
| 114 |
+
logger.info(f"OPTIONS -- IBOT -- head_hidden_dim: {cfg.ibot.head_hidden_dim}")
|
| 115 |
+
logger.info(f"OPTIONS -- IBOT -- head_norm_last_layer: {cfg.ibot.head_norm_last_layer}")
|
| 116 |
+
ibot_head_class = partial(
|
| 117 |
+
DINOHead,
|
| 118 |
+
in_dim=embed_dim,
|
| 119 |
+
out_dim=cfg.ibot.head_n_prototypes,
|
| 120 |
+
hidden_dim=cfg.ibot.head_hidden_dim,
|
| 121 |
+
bottleneck_dim=cfg.ibot.head_bottleneck_dim,
|
| 122 |
+
nlayers=cfg.ibot.head_nlayers,
|
| 123 |
+
)
|
| 124 |
+
student_model_dict["ibot_head"] = ibot_head_class()
|
| 125 |
+
teacher_model_dict["ibot_head"] = ibot_head_class()
|
| 126 |
+
self.ibot_patch_loss = iBOTPatchLoss(cfg.ibot.head_n_prototypes)
|
| 127 |
+
|
| 128 |
+
# Build student and teacher models
|
| 129 |
+
self.student = nn.ModuleDict(student_model_dict)
|
| 130 |
+
self.teacher = nn.ModuleDict(teacher_model_dict)
|
| 131 |
+
self.model_ema = self.teacher # this may be overwritten for distillation
|
| 132 |
+
logger.info(f"Student and Teacher are built: they are both {cfg.student.arch} network.")
|
| 133 |
+
|
| 134 |
+
if cfg.distillation.enabled:
|
| 135 |
+
self._setup_distillation()
|
| 136 |
+
# No grad is needed for these two
|
| 137 |
+
self.teacher.requires_grad_(False)
|
| 138 |
+
self.model_ema.requires_grad_(False)
|
| 139 |
+
self.ema_params_lists = None
|
| 140 |
+
|
| 141 |
+
# getting config params fixed:
|
| 142 |
+
self.n_local_crops = self.cfg.crops.local_crops_number
|
| 143 |
+
self.is_distillation_enabled = self.cfg.distillation.enabled
|
| 144 |
+
self.dino_global_ignore_diagonal = self.cfg.dino.global_ignore_diagonal
|
| 145 |
+
self.dino_loss_weight = self.cfg.dino.loss_weight
|
| 146 |
+
self.dino_koleo_loss_weight = self.cfg.dino.koleo_loss_weight
|
| 147 |
+
self.ibot_loss_weight = self.cfg.ibot.loss_weight
|
| 148 |
+
|
| 149 |
+
# Local loss reweighting
|
| 150 |
+
if self.cfg.dino.reweight_dino_local_loss:
|
| 151 |
+
iter_per_epoch = cfg.train.OFFICIAL_EPOCH_LENGTH
|
| 152 |
+
total_iterations = iter_per_epoch * cfg.optim.epochs
|
| 153 |
+
schedule_cfg = cfg.dino.local_loss_weight_schedule
|
| 154 |
+
self.dino_local_loss_schedule = linear_warmup_cosine_decay(
|
| 155 |
+
start=schedule_cfg.start,
|
| 156 |
+
peak=schedule_cfg.peak,
|
| 157 |
+
end=schedule_cfg.end,
|
| 158 |
+
warmup_iterations=iter_per_epoch * schedule_cfg.warmup_epochs,
|
| 159 |
+
total_iterations=total_iterations,
|
| 160 |
+
cosine_iterations=(
|
| 161 |
+
iter_per_epoch * schedule_cfg.cosine_epochs if "cosine_epochs" in schedule_cfg else None
|
| 162 |
+
),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
# Gram
|
| 166 |
+
self.gram_use_loss = self.cfg.gram.use_loss
|
| 167 |
+
self.gram_ema_teacher = False
|
| 168 |
+
self.has_gram_teacher = False
|
| 169 |
+
self.gram_teacher_initialized = False
|
| 170 |
+
if self.gram_use_loss:
|
| 171 |
+
# Gram regularization
|
| 172 |
+
self.gram_loss = GramLoss(
|
| 173 |
+
apply_norm=self.cfg.gram.normalized,
|
| 174 |
+
remove_only_teacher_neg=self.cfg.gram.remove_only_teacher_neg,
|
| 175 |
+
remove_neg=self.cfg.gram.remove_neg,
|
| 176 |
+
)
|
| 177 |
+
# Construct gram teacher
|
| 178 |
+
self.has_gram_teacher = True if not cfg.gram.ema_teacher else False
|
| 179 |
+
if self.has_gram_teacher:
|
| 180 |
+
self.gram_teacher = nn.ModuleDict(gram_model_dict)
|
| 181 |
+
self.gram_teacher.requires_grad_(False)
|
| 182 |
+
logger.info(f"Gram teacher parameter at init: {next(self.gram_teacher.named_parameters())}")
|
| 183 |
+
else:
|
| 184 |
+
self.gram_teacher = None
|
| 185 |
+
|
| 186 |
+
self.gram_loss_weight = self.cfg.gram.loss_weight
|
| 187 |
+
if self.cfg.gram.get("loss_weight_schedule"):
|
| 188 |
+
iter_per_epoch = cfg.train.OFFICIAL_EPOCH_LENGTH
|
| 189 |
+
total_iterations = iter_per_epoch * cfg.optim.epochs
|
| 190 |
+
schedule_cfg = self.cfg.gram.loss_weight_schedule
|
| 191 |
+
self.gram_loss_schedule = linear_warmup_cosine_decay(
|
| 192 |
+
start=schedule_cfg.start,
|
| 193 |
+
peak=schedule_cfg.peak,
|
| 194 |
+
end=schedule_cfg.end,
|
| 195 |
+
warmup_iterations=iter_per_epoch * schedule_cfg.warmup_epochs,
|
| 196 |
+
total_iterations=total_iterations,
|
| 197 |
+
cosine_iterations=(
|
| 198 |
+
iter_per_epoch * schedule_cfg.cosine_epochs if "cosine_epochs" in schedule_cfg else None
|
| 199 |
+
),
|
| 200 |
+
)
|
| 201 |
+
logger.info(f"Applying gram loss weight schedule instead of `cfg.gram.loss_weight`: {schedule_cfg}")
|
| 202 |
+
else:
|
| 203 |
+
self.gram_loss_schedule = None
|
| 204 |
+
self.gram_ema_teacher = self.cfg.gram.ema_teacher # If true use the EMA_teacher as gram_teacher
|
| 205 |
+
self.gram_ckpt = self.cfg.gram.ckpt # Checkpoint to the first gram teacher model
|
| 206 |
+
self.gram_img_level = self.cfg.gram.img_level # Apply the loss on the image, if false on the batch
|
| 207 |
+
self.gram_tokens_used = self.cfg.gram.tokens_used # Any value in ["all", "masked", "unmasked"]
|
| 208 |
+
# Update the teacher frequently
|
| 209 |
+
self.gram_rep_update = self.cfg.gram.rep_update # bool, if yes the gram teacher will be updated at the freq
|
| 210 |
+
self.gram_update_frequency = self.cfg.gram.update_frequency # defined by this var update_frequency
|
| 211 |
+
self.gram_it_first_update = self.cfg.gram.it_first_update # after iteration it_first_update is passed.
|
| 212 |
+
self.gram_it_load_ema_teacher = (
|
| 213 |
+
self.cfg.gram.it_load_ema_teacher
|
| 214 |
+
) # after iteration it_load_ema the ema teacher is loaded into the gram teacher
|
| 215 |
+
self.gram_compute_stats = self.cfg.gram.compute_stats # whether to compute auxiliary stats
|
| 216 |
+
self.gram_params_lists = None
|
| 217 |
+
|
| 218 |
+
if self.gram_ema_teacher and self.gram_ckpt is not None:
|
| 219 |
+
raise ValueError(
|
| 220 |
+
"Cannot use both `gram.ema_teacher` and `gram.ckpt` at the same time. Please set one of them to False."
|
| 221 |
+
)
|
| 222 |
+
if self.gram_ckpt is None and self.gram_it_load_ema_teacher < 0:
|
| 223 |
+
raise ValueError(
|
| 224 |
+
"If no gram checkpoint is provided, `gram.it_load_ema_teacher` must be set to a non-negative value."
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
assert not (self.gram_ema_teacher and self.gram_rep_update)
|
| 228 |
+
assert self.gram_tokens_used in ["all", "masked", "unmasked"]
|
| 229 |
+
# Currently using masked/unmasked not handle at the image-level
|
| 230 |
+
if self.gram_tokens_used in ["masked", "unmasked"]:
|
| 231 |
+
assert self.gram_img_level is False
|
| 232 |
+
|
| 233 |
+
logger.info("OPTIONS -- GRAM")
|
| 234 |
+
logger.info(f"OPTIONS -- GRAM -- loss_weight: {cfg.gram.loss_weight}")
|
| 235 |
+
logger.info(f"OPTIONS -- GRAM -- ema teacher: {cfg.gram.ema_teacher}")
|
| 236 |
+
logger.info(f"OPTIONS -- GRAM -- ckpt: {cfg.gram.ckpt}")
|
| 237 |
+
if self.cfg.gram.rep_update:
|
| 238 |
+
logger.info(f"OPTIONS -- GRAM -- repeated update: {cfg.gram.rep_update}")
|
| 239 |
+
logger.info(f"OPTIONS -- GRAM -- update freq: {cfg.gram.update_frequency}")
|
| 240 |
+
logger.info(f"OPTIONS -- GRAM -- iteration first update: {cfg.gram.it_first_update}")
|
| 241 |
+
|
| 242 |
+
logger.info(f"OPTIONS -- GRAM -- tokens_used: {cfg.gram.tokens_used}")
|
| 243 |
+
logger.info(f"OPTIONS -- GRAM -- apply normalization: {cfg.gram.normalized}")
|
| 244 |
+
logger.info(f"OPTIONS -- GRAM -- img_level: {cfg.gram.img_level}")
|
| 245 |
+
logger.info(f"OPTIONS -- GRAM -- remove_neg: {cfg.gram.remove_neg}")
|
| 246 |
+
logger.info(f"OPTIONS -- GRAM -- remove_only_teacher_neg: {cfg.gram.remove_only_teacher_neg}")
|
| 247 |
+
|
| 248 |
+
if cfg.crops.gram_teacher_crops_size is None and self.has_gram_teacher:
|
| 249 |
+
raise ValueError("cfg.crops.gram_teacher_crops_size must be set to use gram loss")
|
| 250 |
+
if cfg.crops.gram_teacher_crops_size is not None and self.gram_ema_teacher:
|
| 251 |
+
raise ValueError("cfg.crops.gram_teacher_crops_size shoud be None when gram.ema_teacher=True")
|
| 252 |
+
|
| 253 |
+
self.student_crop_size = cfg.crops.global_crops_size
|
| 254 |
+
self.gram_global_teacher_resize_method = cfg.gram.global_teacher_resize_method
|
| 255 |
+
self.gram_global_teacher_resize_antialias = cfg.gram.global_teacher_resize_antialias
|
| 256 |
+
logger.info(f"OPTIONS -- global crops student/teacher size: {self.student_crop_size}")
|
| 257 |
+
logger.info(f"OPTIONS -- global crops GRAM teacher size: {cfg.crops.gram_teacher_crops_size}")
|
| 258 |
+
logger.info(f"OPTIONS -- global crops GRAM teacher resize method: {cfg.gram.global_teacher_resize_method}")
|
| 259 |
+
logger.info(
|
| 260 |
+
f"OPTIONS -- global crops GRAM teacher resize antialias: {cfg.gram.global_teacher_resize_antialias}"
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
def _setup_distillation(self):
|
| 264 |
+
logger.info(f"Performing distillation from {self.cfg.distillation.full_cfg_path}")
|
| 265 |
+
|
| 266 |
+
default_cfg = get_default_config()
|
| 267 |
+
distillation_cfg = OmegaConf.load(self.cfg.distillation.full_cfg_path)
|
| 268 |
+
distillation_cfg = OmegaConf.merge(default_cfg, distillation_cfg)
|
| 269 |
+
|
| 270 |
+
assert distillation_cfg.ibot.separate_head is True
|
| 271 |
+
assert distillation_cfg.ibot.head_n_prototypes == self.cfg.ibot.head_n_prototypes, (
|
| 272 |
+
f"{distillation_cfg.ibot.head_n_prototypes} != {self.cfg.ibot.head_n_prototypes}"
|
| 273 |
+
)
|
| 274 |
+
assert distillation_cfg.dino.head_n_prototypes == self.cfg.dino.head_n_prototypes, (
|
| 275 |
+
f"{distillation_cfg.dino.head_n_prototypes} != {self.cfg.dino.head_n_prototypes}"
|
| 276 |
+
)
|
| 277 |
+
assert distillation_cfg.student.patch_size == self.cfg.student.patch_size
|
| 278 |
+
|
| 279 |
+
teacher_model_dict = dict()
|
| 280 |
+
|
| 281 |
+
backbone, embed_dim = build_model_from_cfg(distillation_cfg, only_teacher=True)
|
| 282 |
+
teacher_model_dict["backbone"] = backbone
|
| 283 |
+
|
| 284 |
+
teacher_model_dict["dino_head"] = DINOHead(
|
| 285 |
+
in_dim=embed_dim,
|
| 286 |
+
out_dim=distillation_cfg.dino.head_n_prototypes,
|
| 287 |
+
hidden_dim=distillation_cfg.dino.head_hidden_dim,
|
| 288 |
+
bottleneck_dim=distillation_cfg.dino.head_bottleneck_dim,
|
| 289 |
+
nlayers=distillation_cfg.dino.head_nlayers,
|
| 290 |
+
)
|
| 291 |
+
teacher_model_dict["ibot_head"] = DINOHead(
|
| 292 |
+
in_dim=embed_dim,
|
| 293 |
+
out_dim=distillation_cfg.ibot.head_n_prototypes,
|
| 294 |
+
hidden_dim=distillation_cfg.ibot.head_hidden_dim,
|
| 295 |
+
bottleneck_dim=distillation_cfg.ibot.head_bottleneck_dim,
|
| 296 |
+
nlayers=distillation_cfg.ibot.head_nlayers,
|
| 297 |
+
)
|
| 298 |
+
self.teacher = nn.ModuleDict(teacher_model_dict)
|
| 299 |
+
|
| 300 |
+
def init_weights(self) -> None:
|
| 301 |
+
# All weights are set to `nan` to ensure we initialize everything explicitly
|
| 302 |
+
self.student.backbone.init_weights()
|
| 303 |
+
self.student.dino_head.init_weights()
|
| 304 |
+
self.student.ibot_head.init_weights()
|
| 305 |
+
self.dino_loss.init_weights()
|
| 306 |
+
self.ibot_patch_loss.init_weights()
|
| 307 |
+
self.model_ema.load_state_dict(self.student.state_dict())
|
| 308 |
+
if self.has_gram_teacher:
|
| 309 |
+
if self.gram_ckpt is not None:
|
| 310 |
+
logger.info(f"Loading pretrained weights from {self.gram_ckpt}")
|
| 311 |
+
init_fsdp_model_from_checkpoint(
|
| 312 |
+
self.gram_teacher,
|
| 313 |
+
self.gram_ckpt,
|
| 314 |
+
skip_load_keys=[
|
| 315 |
+
"dino_head",
|
| 316 |
+
"ibot_head",
|
| 317 |
+
"dino_loss.center",
|
| 318 |
+
"ibot_patch_loss.center",
|
| 319 |
+
],
|
| 320 |
+
keys_not_sharded=["backbone.rope_embed.periods", "qkv.bias_mask"],
|
| 321 |
+
process_group=distributed.get_default_process_group(),
|
| 322 |
+
)
|
| 323 |
+
self.gram_teacher_initialized = True
|
| 324 |
+
else:
|
| 325 |
+
raise ValueError(f"Provide a correct path to {self.gram_ckpt}")
|
| 326 |
+
self.gram_teacher.requires_grad_(False)
|
| 327 |
+
self.gram_teacher.eval()
|
| 328 |
+
if self.cfg.student.resume_from_teacher_chkpt:
|
| 329 |
+
logger.info(f"Loading pretrained weights from {self.cfg.student.resume_from_teacher_chkpt}")
|
| 330 |
+
init_fsdp_model_from_checkpoint(
|
| 331 |
+
self.student,
|
| 332 |
+
self.cfg.student.resume_from_teacher_chkpt,
|
| 333 |
+
skip_load_keys=["dino_loss.center", "ibot_patch_loss.center"],
|
| 334 |
+
keys_not_sharded=["backbone.rope_embed.periods", "qkv.bias_mask"],
|
| 335 |
+
process_group=distributed.get_process_subgroup(),
|
| 336 |
+
)
|
| 337 |
+
self.model_ema.load_state_dict(self.student.state_dict())
|
| 338 |
+
if self.cfg.distillation.enabled:
|
| 339 |
+
if self.cfg.distillation.checkpoint_path != "ignore":
|
| 340 |
+
logger.info(f"Loading teacher to distil from : {self.cfg.distillation.checkpoint_path}")
|
| 341 |
+
init_fsdp_model_from_checkpoint(
|
| 342 |
+
self.teacher,
|
| 343 |
+
self.cfg.distillation.checkpoint_path,
|
| 344 |
+
skip_load_keys=["dino_loss.center", "ibot_patch_loss.center"],
|
| 345 |
+
keys_not_sharded=["backbone.rope_embed.periods", "qkv.bias_mask"],
|
| 346 |
+
process_group=distributed.get_default_process_group(),
|
| 347 |
+
)
|
| 348 |
+
else:
|
| 349 |
+
logger.info("Init teacher to distil from, used for testing purpose only")
|
| 350 |
+
self.teacher.backbone.init_weights()
|
| 351 |
+
self.teacher.dino_head.init_weights()
|
| 352 |
+
self.teacher.ibot_head.init_weights()
|
| 353 |
+
logger.info(f"Performing distillation from: {self.teacher}")
|
| 354 |
+
|
| 355 |
+
def forward_backward(
|
| 356 |
+
self, data, *, teacher_temp, iteration=0, **ignored_kwargs
|
| 357 |
+
) -> tuple[Tensor, dict[str, float | Tensor]]:
|
| 358 |
+
del ignored_kwargs
|
| 359 |
+
metrics_dict = {}
|
| 360 |
+
|
| 361 |
+
# Shapes
|
| 362 |
+
n_global_crops = 2
|
| 363 |
+
n_local_crops = self.n_local_crops # self.cfg.crops.local_crops_number
|
| 364 |
+
B = data["collated_local_crops"].shape[0] // n_local_crops
|
| 365 |
+
assert data["collated_global_crops"].shape[0] == n_global_crops * B
|
| 366 |
+
metrics_dict["local_batch_size"] = B
|
| 367 |
+
metrics_dict["global_batch_size"] = data["global_batch_size"]
|
| 368 |
+
|
| 369 |
+
global_crops = data["collated_global_crops"].cuda(non_blocking=True)
|
| 370 |
+
local_crops = data["collated_local_crops"].cuda(non_blocking=True)
|
| 371 |
+
masks = data["collated_masks"].cuda(non_blocking=True)
|
| 372 |
+
mask_indices_list = data["mask_indices_list"].cuda(non_blocking=True)
|
| 373 |
+
masks_weight = data["masks_weight"].cuda(non_blocking=True)
|
| 374 |
+
n_masked_patches_tensor = data["n_masked_patches"].cuda(non_blocking=True)
|
| 375 |
+
|
| 376 |
+
if self.has_gram_teacher:
|
| 377 |
+
assert "collated_gram_teacher_crops" in data, (
|
| 378 |
+
"no gram teacher crops in the data, have you set cfg.crops.gram_teacher_crops_size?"
|
| 379 |
+
)
|
| 380 |
+
gram_teacher_crops = data["collated_gram_teacher_crops"].cuda(non_blocking=True)
|
| 381 |
+
else:
|
| 382 |
+
gram_teacher_crops = None
|
| 383 |
+
|
| 384 |
+
# Teacher output (will trigger an all-gather to unshard)
|
| 385 |
+
teacher_global = self.get_teacher_output(
|
| 386 |
+
global_crops.unflatten(0, (n_global_crops, B)),
|
| 387 |
+
teacher_temp=teacher_temp,
|
| 388 |
+
n_masked_patches_tensor=n_masked_patches_tensor,
|
| 389 |
+
mask_indices_list=mask_indices_list,
|
| 390 |
+
upperbound=data["upperbound"],
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
# Student output (will trigger an all-gather to unshard)
|
| 394 |
+
student_global, student_local = self.get_student_output(
|
| 395 |
+
global_crops=global_crops.unflatten(0, (n_global_crops, B)),
|
| 396 |
+
local_crops=local_crops.unflatten(0, (n_local_crops, B)),
|
| 397 |
+
upperbound=data["upperbound"],
|
| 398 |
+
masks=masks,
|
| 399 |
+
mask_indices_list=mask_indices_list,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
# Gram output
|
| 403 |
+
if self.gram_use_loss:
|
| 404 |
+
gram_global = self.get_gram_teacher_output(
|
| 405 |
+
gram_teacher_crops.unflatten(0, (n_global_crops, B)) if gram_teacher_crops is not None else None,
|
| 406 |
+
masks=masks,
|
| 407 |
+
teacher_global=teacher_global,
|
| 408 |
+
student_global=student_global,
|
| 409 |
+
student_global_crops_size=global_crops.shape[-1],
|
| 410 |
+
)
|
| 411 |
+
else:
|
| 412 |
+
gram_global = {}
|
| 413 |
+
|
| 414 |
+
# Compute losses and backprop
|
| 415 |
+
loss_accumulator, loss_dict = self.compute_losses(
|
| 416 |
+
teacher_global=teacher_global,
|
| 417 |
+
student_global=student_global,
|
| 418 |
+
student_local=student_local,
|
| 419 |
+
gram_global=gram_global,
|
| 420 |
+
masks=masks,
|
| 421 |
+
mask_indices_list=mask_indices_list,
|
| 422 |
+
masks_weight=masks_weight,
|
| 423 |
+
iteration=iteration,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
self.backprop_loss(loss_accumulator)
|
| 427 |
+
|
| 428 |
+
# Return total weighted loss and a dict of metrics to log
|
| 429 |
+
return loss_accumulator, metrics_dict | loss_dict
|
| 430 |
+
|
| 431 |
+
@torch.no_grad()
|
| 432 |
+
def get_teacher_output(
|
| 433 |
+
self,
|
| 434 |
+
images,
|
| 435 |
+
*,
|
| 436 |
+
upperbound,
|
| 437 |
+
mask_indices_list,
|
| 438 |
+
teacher_temp,
|
| 439 |
+
n_masked_patches_tensor,
|
| 440 |
+
):
|
| 441 |
+
n_crops, B, rgb, H, W = images.shape
|
| 442 |
+
images = images.flatten(0, 1)
|
| 443 |
+
|
| 444 |
+
backbone_out = self.teacher.backbone(images, is_training=True)
|
| 445 |
+
cls = backbone_out["x_norm_clstoken"] # [n_crops * B, D]
|
| 446 |
+
reg = backbone_out["x_storage_tokens"] # [n_crops * B, R, D]
|
| 447 |
+
ibot_patch = backbone_out["x_norm_patchtokens"] # [n_crops * B, P, D]
|
| 448 |
+
|
| 449 |
+
# IBOT head only on patches that are masked for the student
|
| 450 |
+
buffer = torch.index_select(ibot_patch.flatten(0, 1), dim=0, index=mask_indices_list)
|
| 451 |
+
masked_patch_after_head = self.teacher.ibot_head(buffer)
|
| 452 |
+
|
| 453 |
+
# DINO head on CLS tokens
|
| 454 |
+
cls_after_head = self.teacher.dino_head(cls) # [n_crops * B, K]
|
| 455 |
+
|
| 456 |
+
# Center with sinkhorn-knopp
|
| 457 |
+
cls_centered = self.dino_loss.sinkhorn_knopp_teacher(
|
| 458 |
+
cls_after_head, teacher_temp=teacher_temp
|
| 459 |
+
) # [n_crops * B, K]
|
| 460 |
+
cls_centered = cls_centered.unflatten(0, (n_crops, B)) # [n_crops, B, K]
|
| 461 |
+
masked_patch_centered = self.ibot_patch_loss.sinkhorn_knopp_teacher(
|
| 462 |
+
masked_patch_after_head,
|
| 463 |
+
teacher_temp=teacher_temp,
|
| 464 |
+
n_masked_patches_tensor=n_masked_patches_tensor,
|
| 465 |
+
) # [n_masked_patches, K]
|
| 466 |
+
|
| 467 |
+
return {
|
| 468 |
+
"cls_pre_head": cls.unflatten(0, [n_crops, B]), # [n_crops, B, D]
|
| 469 |
+
"reg_pre_head": reg.unflatten(0, [n_crops, B]), # [n_crops, B, R, D]
|
| 470 |
+
"patch_pre_head": ibot_patch.unflatten(0, [n_crops, B]), # [n_crops, B, P, D]
|
| 471 |
+
"cls_after_head": cls_after_head.unflatten(0, [n_crops, B]), # [n_crops, B, K]
|
| 472 |
+
"cls_centered": cls_centered, # [n_crops, B, K]
|
| 473 |
+
"masked_patch_centered": masked_patch_centered, # [n_masked_patches, K]
|
| 474 |
+
}
|
| 475 |
+
|
| 476 |
+
def get_gram_teacher_output(self, images, *, masks, teacher_global, student_global, student_global_crops_size):
|
| 477 |
+
# Get student patch features
|
| 478 |
+
student_patches = student_global["patch_pre_head"].flatten(0, 1) # [n_crops * B, P, D]
|
| 479 |
+
|
| 480 |
+
# Get gram targets
|
| 481 |
+
if self.gram_ema_teacher:
|
| 482 |
+
teacher_patches = teacher_global["patch_pre_head"].flatten(0, 1) # [n_crops * B, P, D]
|
| 483 |
+
else:
|
| 484 |
+
if not self.gram_teacher_initialized:
|
| 485 |
+
raise ValueError("Gram teacher has not been initialized. Load a checkpoint or from the EMA teacher.")
|
| 486 |
+
n_crops, B, rgb, H, W = images.shape
|
| 487 |
+
images = images.flatten(0, 1) # [n_crops * B, rgb, H, W]
|
| 488 |
+
|
| 489 |
+
with torch.no_grad():
|
| 490 |
+
backbone_out = self.gram_teacher.backbone(images, is_training=True)
|
| 491 |
+
teacher_patches = backbone_out["x_norm_patchtokens"] # [n_crops * B, P_T, D]
|
| 492 |
+
|
| 493 |
+
# Downsample Gram teacher features if needed
|
| 494 |
+
if teacher_patches.shape[1] != student_patches.shape[1]:
|
| 495 |
+
N = H // self.cfg.student.patch_size
|
| 496 |
+
assert teacher_patches.shape[1] == N**2
|
| 497 |
+
N_student = student_global_crops_size // self.cfg.student.patch_size
|
| 498 |
+
assert student_patches.shape[1] == N_student**2
|
| 499 |
+
patches_hw = teacher_patches.transpose(-2, -1).unflatten(-1, (N, N)) # [n_crops * B, D, N, N]
|
| 500 |
+
patches_hw = torch.nn.functional.interpolate(
|
| 501 |
+
patches_hw,
|
| 502 |
+
size=(N_student, N_student),
|
| 503 |
+
mode=self.gram_global_teacher_resize_method,
|
| 504 |
+
align_corners=False,
|
| 505 |
+
antialias=self.gram_global_teacher_resize_antialias,
|
| 506 |
+
)
|
| 507 |
+
teacher_patches = patches_hw.flatten(-2, -1).transpose(
|
| 508 |
+
-2, -1
|
| 509 |
+
) # [n_crops * B, N_student * N_student, D]
|
| 510 |
+
assert teacher_patches.shape == student_patches.shape
|
| 511 |
+
|
| 512 |
+
# Select the patches to be considered in the loss
|
| 513 |
+
orig_student_patches = student_patches
|
| 514 |
+
orig_teacher_patches = teacher_patches
|
| 515 |
+
if self.gram_tokens_used == "masked":
|
| 516 |
+
student_patches = student_patches[masks]
|
| 517 |
+
teacher_patches = teacher_patches[masks]
|
| 518 |
+
elif self.gram_tokens_used == "unmasked":
|
| 519 |
+
student_patches = student_patches[~masks]
|
| 520 |
+
teacher_patches = teacher_patches[~masks]
|
| 521 |
+
|
| 522 |
+
return {
|
| 523 |
+
"student_patches": student_patches, # [n_crops * B, P, D] or [n_selected_patches, D]
|
| 524 |
+
"teacher_patches": teacher_patches, # [n_crops * B, P, D] or [n_selected_patches, D]
|
| 525 |
+
# Unmasked patches, for computing statistics
|
| 526 |
+
"orig_student_patches": orig_student_patches, # [n_crops * B, P, D]
|
| 527 |
+
"orig_teacher_patches": orig_teacher_patches, # [n_crops * B, P, D]
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
def get_student_output(self, *, global_crops, local_crops, upperbound, masks, mask_indices_list):
|
| 531 |
+
n_global_crops, B, rgb, H, W = global_crops.shape
|
| 532 |
+
n_local_crops, B, rgb, H, W = local_crops.shape
|
| 533 |
+
|
| 534 |
+
global_crops = global_crops.flatten(0, 1)
|
| 535 |
+
|
| 536 |
+
# Forward global and local crops through the student backbone jointly
|
| 537 |
+
global_out, local_out = self.student.backbone(
|
| 538 |
+
[global_crops, local_crops.flatten(0, 1)],
|
| 539 |
+
masks=[masks if not self.is_distillation_enabled else None, None],
|
| 540 |
+
is_training=True,
|
| 541 |
+
)
|
| 542 |
+
g_cls, g_reg, g_patch = (
|
| 543 |
+
global_out["x_norm_clstoken"],
|
| 544 |
+
global_out["x_storage_tokens"],
|
| 545 |
+
global_out["x_norm_patchtokens"],
|
| 546 |
+
)
|
| 547 |
+
l_cls, l_reg, l_patch = (
|
| 548 |
+
local_out["x_norm_clstoken"],
|
| 549 |
+
local_out["x_storage_tokens"],
|
| 550 |
+
local_out["x_norm_patchtokens"],
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
# IBOT head only on masked patches
|
| 554 |
+
masked_patches_pre_head = torch.index_select(g_patch.flatten(0, 1), dim=0, index=mask_indices_list)
|
| 555 |
+
global_masked_patch_after_head = self.student.ibot_head(masked_patches_pre_head)
|
| 556 |
+
|
| 557 |
+
# DINO head on CLS tokens (all in one pass)
|
| 558 |
+
buffer = [
|
| 559 |
+
g_cls, # [n_global_crops * B, D]
|
| 560 |
+
l_cls, # [n_local_crops * B, D]
|
| 561 |
+
]
|
| 562 |
+
sizes = [x.shape[0] for x in buffer]
|
| 563 |
+
buffer = torch.cat(buffer, dim=0) # [n_global_crops * B + n_local_crops * B, D]
|
| 564 |
+
buffer = self.student.dino_head(buffer) # [n_global_crops * B + n_local_crops * B, K]
|
| 565 |
+
buffer = torch.split_with_sizes(buffer, sizes, dim=0)
|
| 566 |
+
|
| 567 |
+
global_out = {
|
| 568 |
+
"cls_pre_head": g_cls.unflatten(0, [n_global_crops, B]), # [n_global_crops, B, D]
|
| 569 |
+
"reg_pre_head": g_reg.unflatten(0, [n_global_crops, B]), # [n_global_crops, B, R, D]
|
| 570 |
+
"patch_pre_head": g_patch.unflatten(0, [n_global_crops, B]), # [n_global_crops, B, P, D]
|
| 571 |
+
"cls_after_head": buffer[0].unflatten(0, [n_global_crops, B]), # [n_global_crops, B, K],
|
| 572 |
+
"masked_patch_after_head": global_masked_patch_after_head, # [n_masked_patches, K]
|
| 573 |
+
"masked_patch_pre_head": masked_patches_pre_head, # [n_masked_patches, D]
|
| 574 |
+
}
|
| 575 |
+
local_out = {
|
| 576 |
+
"cls_pre_head": l_cls.unflatten(0, [n_local_crops, B]), # [n_local_crops, B, D]
|
| 577 |
+
"reg_pre_head": l_reg.unflatten(0, [n_local_crops, B]), # [n_local_crops, B, R, D]
|
| 578 |
+
"patch_pre_head": l_patch.unflatten(0, [n_local_crops, B]), # [n_local_crops, B, P, D]
|
| 579 |
+
"cls_after_head": buffer[1].unflatten(0, [n_local_crops, B]), # [n_local_crops, B, K],
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
return global_out, local_out
|
| 583 |
+
|
| 584 |
+
def compute_losses(
|
| 585 |
+
self,
|
| 586 |
+
*,
|
| 587 |
+
teacher_global,
|
| 588 |
+
student_global,
|
| 589 |
+
student_local,
|
| 590 |
+
gram_global,
|
| 591 |
+
masks,
|
| 592 |
+
mask_indices_list,
|
| 593 |
+
masks_weight,
|
| 594 |
+
iteration,
|
| 595 |
+
):
|
| 596 |
+
n_global_crops = student_global["cls_after_head"].shape[0]
|
| 597 |
+
n_local_crops = student_local["cls_after_head"].shape[0]
|
| 598 |
+
loss_dict = {}
|
| 599 |
+
loss_accumulator = 0.0
|
| 600 |
+
|
| 601 |
+
# Loss scales like in DINOv2, these are multiplied with the loss weights from the config
|
| 602 |
+
dino_global_terms = (
|
| 603 |
+
n_global_crops * (n_global_crops - 1) if self.dino_global_ignore_diagonal else n_global_crops**2
|
| 604 |
+
)
|
| 605 |
+
dino_local_terms = n_global_crops * n_local_crops
|
| 606 |
+
dino_global_scale = dino_global_terms / (dino_global_terms + dino_local_terms)
|
| 607 |
+
dino_local_scale = dino_local_terms / (dino_global_terms + dino_local_terms)
|
| 608 |
+
koleo_scale = n_global_crops
|
| 609 |
+
|
| 610 |
+
# DINO local loss: compare post-head CLS tokens: student(local crops) vs. teacher(global crops)
|
| 611 |
+
dino_local_crops_loss = self.dino_loss(
|
| 612 |
+
student_logits=student_local["cls_after_head"],
|
| 613 |
+
teacher_probs=teacher_global["cls_centered"],
|
| 614 |
+
)
|
| 615 |
+
loss_dict["dino_local_crops_loss"] = dino_local_crops_loss
|
| 616 |
+
|
| 617 |
+
# Reweighting of DINO loss
|
| 618 |
+
if self.cfg.dino.reweight_dino_local_loss:
|
| 619 |
+
local_weight = self.dino_local_loss_schedule[iteration]
|
| 620 |
+
else:
|
| 621 |
+
local_weight = 1.0
|
| 622 |
+
|
| 623 |
+
loss_dict["dino_local_loss_weight"] = local_weight
|
| 624 |
+
loss_accumulator += self.dino_loss_weight * dino_local_scale * local_weight * dino_local_crops_loss
|
| 625 |
+
|
| 626 |
+
# DINO global loss: compare post-head CLS tokens: student(global crops) vs. teacher(global crops)
|
| 627 |
+
dino_global_crops_loss = self.dino_loss(
|
| 628 |
+
student_logits=student_global["cls_after_head"],
|
| 629 |
+
teacher_probs=teacher_global["cls_centered"],
|
| 630 |
+
ignore_diagonal=self.dino_global_ignore_diagonal,
|
| 631 |
+
)
|
| 632 |
+
loss_dict["dino_global_crops_loss"] = dino_global_crops_loss
|
| 633 |
+
loss_accumulator += self.dino_loss_weight * dino_global_scale * dino_global_crops_loss
|
| 634 |
+
|
| 635 |
+
# Koleo: regularize pre-head CLS tokens of student(global crops)
|
| 636 |
+
koleo_loss = sum(self.koleo_loss(x) for x in student_global["cls_pre_head"]) / n_global_crops
|
| 637 |
+
loss_dict["koleo_loss"] = koleo_loss
|
| 638 |
+
loss_accumulator += self.dino_koleo_loss_weight * koleo_scale * koleo_loss
|
| 639 |
+
|
| 640 |
+
# IBOT loss
|
| 641 |
+
ibot_patch_loss = self.ibot_patch_loss.forward_masked(
|
| 642 |
+
student_global["masked_patch_after_head"],
|
| 643 |
+
teacher_global["masked_patch_centered"],
|
| 644 |
+
student_masks_flat=masks,
|
| 645 |
+
n_masked_patches=mask_indices_list.shape[0],
|
| 646 |
+
masks_weight=masks_weight,
|
| 647 |
+
)
|
| 648 |
+
loss_dict["ibot_loss"] = ibot_patch_loss
|
| 649 |
+
loss_accumulator += self.ibot_loss_weight * ibot_patch_loss
|
| 650 |
+
|
| 651 |
+
# Gram loss
|
| 652 |
+
if self.gram_use_loss:
|
| 653 |
+
gram_loss = self.gram_loss(
|
| 654 |
+
gram_global["student_patches"],
|
| 655 |
+
gram_global["teacher_patches"],
|
| 656 |
+
img_level=self.gram_img_level,
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
if self.gram_loss_schedule is not None:
|
| 660 |
+
gram_loss_weight = self.gram_loss_schedule[iteration]
|
| 661 |
+
else:
|
| 662 |
+
gram_loss_weight = self.gram_loss_weight
|
| 663 |
+
|
| 664 |
+
loss_dict["gram_loss_weight"] = gram_loss_weight
|
| 665 |
+
loss_accumulator += gram_loss * gram_loss_weight
|
| 666 |
+
loss_dict["gram_loss"] = gram_loss
|
| 667 |
+
|
| 668 |
+
if self.gram_compute_stats:
|
| 669 |
+
with torch.no_grad():
|
| 670 |
+
# Save stats over masked / unmasked tokens
|
| 671 |
+
gram_loss_masked = self.gram_loss(
|
| 672 |
+
gram_global["orig_student_patches"][masks].detach(),
|
| 673 |
+
gram_global["orig_teacher_patches"][masks],
|
| 674 |
+
img_level=False,
|
| 675 |
+
)
|
| 676 |
+
loss_dict["stats_only/masked_gram_loss"] = gram_loss_masked
|
| 677 |
+
gram_loss_unmasked = self.gram_loss(
|
| 678 |
+
gram_global["orig_student_patches"][~masks].detach(),
|
| 679 |
+
gram_global["orig_teacher_patches"][~masks],
|
| 680 |
+
img_level=False,
|
| 681 |
+
)
|
| 682 |
+
loss_dict["stats_only/unmasked_gram_loss"] = gram_loss_unmasked
|
| 683 |
+
|
| 684 |
+
return loss_accumulator, loss_dict
|
| 685 |
+
|
| 686 |
+
@torch.no_grad()
|
| 687 |
+
def gram_load_ema_teacher(self):
|
| 688 |
+
if self.has_gram_teacher:
|
| 689 |
+
skip_load_prefixes = ["dino_head.", "ibot_head."]
|
| 690 |
+
self.gram_teacher.load_state_dict(
|
| 691 |
+
{
|
| 692 |
+
k: v
|
| 693 |
+
for k, v in self.model_ema.state_dict().items()
|
| 694 |
+
if not any(k.startswith(prefix) for prefix in skip_load_prefixes)
|
| 695 |
+
}
|
| 696 |
+
)
|
| 697 |
+
self.gram_teacher.requires_grad_(False)
|
| 698 |
+
self.gram_teacher.eval()
|
| 699 |
+
self.gram_teacher_initialized = True
|
| 700 |
+
|
| 701 |
+
def train(self):
|
| 702 |
+
super().train()
|
| 703 |
+
self.teacher.eval()
|
| 704 |
+
if self.has_gram_teacher:
|
| 705 |
+
self.gram_teacher.eval()
|
| 706 |
+
|
| 707 |
+
def forward(self, inputs):
|
| 708 |
+
raise NotImplementedError
|
| 709 |
+
|
| 710 |
+
def backprop_loss(self, loss):
|
| 711 |
+
loss.backward()
|
| 712 |
+
|
| 713 |
+
def update_ema(self, m):
|
| 714 |
+
if self.ema_params_lists is None:
|
| 715 |
+
student_param_list = []
|
| 716 |
+
teacher_param_list = []
|
| 717 |
+
for k in self.student.keys():
|
| 718 |
+
for ms, mt in zip(self.student[k].parameters(), self.model_ema[k].parameters()):
|
| 719 |
+
student_param_list += [ms]
|
| 720 |
+
teacher_param_list += [mt]
|
| 721 |
+
self.ema_params_lists = (student_param_list, teacher_param_list)
|
| 722 |
+
else:
|
| 723 |
+
student_param_list, teacher_param_list = self.ema_params_lists
|
| 724 |
+
with torch.no_grad():
|
| 725 |
+
torch._foreach_mul_(teacher_param_list, m)
|
| 726 |
+
torch._foreach_add_(teacher_param_list, student_param_list, alpha=1 - m)
|
| 727 |
+
|
| 728 |
+
def update_gram(self, m=0):
|
| 729 |
+
if not self.has_gram_teacher:
|
| 730 |
+
return
|
| 731 |
+
logger.info("Updating gram teacher with teacher weights.")
|
| 732 |
+
if self.gram_params_lists is None:
|
| 733 |
+
teacher_param_list = []
|
| 734 |
+
gramteacher_param_list = []
|
| 735 |
+
for k in self.gram_teacher.keys():
|
| 736 |
+
for mgt, mt in zip(self.gram_teacher[k].parameters(), self.teacher[k].parameters()):
|
| 737 |
+
gramteacher_param_list += [mgt]
|
| 738 |
+
teacher_param_list += [mt]
|
| 739 |
+
self.gram_params_lists = (gramteacher_param_list, teacher_param_list)
|
| 740 |
+
else:
|
| 741 |
+
gramteacher_param_list, teacher_param_list = self.gram_params_lists
|
| 742 |
+
|
| 743 |
+
with torch.no_grad():
|
| 744 |
+
torch._foreach_mul_(gramteacher_param_list, m)
|
| 745 |
+
torch._foreach_add_(gramteacher_param_list, teacher_param_list, alpha=1 - m)
|
| 746 |
+
|
| 747 |
+
def build_data_augmentation_dino(self, cfg):
|
| 748 |
+
return DataAugmentationDINO(
|
| 749 |
+
cfg.crops.global_crops_scale,
|
| 750 |
+
cfg.crops.local_crops_scale,
|
| 751 |
+
cfg.crops.local_crops_number,
|
| 752 |
+
global_crops_size=cfg.crops.global_crops_size,
|
| 753 |
+
local_crops_size=cfg.crops.local_crops_size,
|
| 754 |
+
gram_teacher_crops_size=cfg.crops.gram_teacher_crops_size,
|
| 755 |
+
gram_teacher_no_distortions=cfg.crops.gram_teacher_no_distortions,
|
| 756 |
+
local_crops_subset_of_global_crops=cfg.crops.localcrops_subset_of_globalcrops,
|
| 757 |
+
share_color_jitter=cfg.crops.share_color_jitter,
|
| 758 |
+
horizontal_flips=cfg.crops.horizontal_flips,
|
| 759 |
+
mean=cfg.crops.rgb_mean,
|
| 760 |
+
std=cfg.crops.rgb_std,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
def get_maybe_fused_params_for_submodel(self, m: nn.Module):
|
| 764 |
+
params_groups = get_params_groups_with_decay_fsdp(
|
| 765 |
+
model=m,
|
| 766 |
+
lr_decay_rate=self.cfg.optim.layerwise_decay,
|
| 767 |
+
patch_embed_lr_mult=self.cfg.optim.patch_embed_lr_mult,
|
| 768 |
+
dino_head_wd_multiplier=self.cfg.optim.dino_head_wd_multiplier,
|
| 769 |
+
)
|
| 770 |
+
if self.cfg.optim.multi_tensor_optim:
|
| 771 |
+
fused_params_groups = fuse_params_groups(params_groups)
|
| 772 |
+
logger.info("fusing param groups")
|
| 773 |
+
|
| 774 |
+
for g in fused_params_groups:
|
| 775 |
+
g["foreach"] = True
|
| 776 |
+
g["fused"] = True
|
| 777 |
+
return fused_params_groups
|
| 778 |
+
else:
|
| 779 |
+
return params_groups
|
| 780 |
+
|
| 781 |
+
def get_params_groups(self):
|
| 782 |
+
all_params_groups = []
|
| 783 |
+
for name, m in self.student.items():
|
| 784 |
+
logger.info(f"Getting paramer groups for {name}")
|
| 785 |
+
all_params_groups += self.get_maybe_fused_params_for_submodel(m)
|
| 786 |
+
return all_params_groups
|
| 787 |
+
|
| 788 |
+
def prepare_for_distributed_training(self) -> None:
|
| 789 |
+
process_subgroup = distributed.get_process_subgroup()
|
| 790 |
+
default_process_group = distributed.get_default_process_group()
|
| 791 |
+
inference_only_models = [self.model_ema]
|
| 792 |
+
inference_only_models_process_groups = [process_subgroup]
|
| 793 |
+
if self.has_gram_teacher:
|
| 794 |
+
inference_only_models.append(self.gram_teacher)
|
| 795 |
+
inference_only_models_process_groups.append(default_process_group)
|
| 796 |
+
if self.cfg.distillation.enabled:
|
| 797 |
+
inference_only_models.append(self.teacher)
|
| 798 |
+
inference_only_models_process_groups.append(default_process_group)
|
| 799 |
+
ac_compile_parallelize(
|
| 800 |
+
trained_model=self.student,
|
| 801 |
+
inference_only_models=inference_only_models,
|
| 802 |
+
cfg=self.cfg,
|
| 803 |
+
trained_model_process_group=process_subgroup,
|
| 804 |
+
inference_only_models_process_groups=inference_only_models_process_groups,
|
| 805 |
+
)
|
| 806 |
+
|
| 807 |
+
def broadcast_to_subgroups(self, tensor, over_dim, global_batch_size=None):
|
| 808 |
+
"""
|
| 809 |
+
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
|
| 810 |
+
"""
|
| 811 |
+
world_size = distributed.get_world_size()
|
| 812 |
+
subgroup_size = distributed.get_subgroup_size()
|
| 813 |
+
gathered = [torch.zeros_like(tensor) for _ in range(world_size)]
|
| 814 |
+
|
| 815 |
+
torch.distributed.all_gather(gathered, tensor)
|
| 816 |
+
catted = torch.cat(gathered, dim=over_dim)
|
| 817 |
+
if global_batch_size is not None:
|
| 818 |
+
catted = catted.narrow(dim=over_dim, start=0, length=global_batch_size)
|
| 819 |
+
|
| 820 |
+
return catted.chunk(subgroup_size, dim=over_dim)[distributed.get_subgroup_rank()].clone()
|
starVLA/dinov3/dinov3/train/train.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import copy
|
| 8 |
+
import gc
|
| 9 |
+
import logging
|
| 10 |
+
import math
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
from functools import partial
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.distributed
|
| 18 |
+
from torch.distributed._tensor import DTensor
|
| 19 |
+
|
| 20 |
+
import dinov3.distributed as distributed
|
| 21 |
+
from dinov3.checkpointer import (
|
| 22 |
+
find_latest_checkpoint,
|
| 23 |
+
keep_checkpoint_copy,
|
| 24 |
+
keep_last_n_checkpoints,
|
| 25 |
+
load_checkpoint,
|
| 26 |
+
register_dont_save_hooks,
|
| 27 |
+
save_checkpoint,
|
| 28 |
+
)
|
| 29 |
+
from dinov3.configs import setup_config, setup_job, setup_multidistillation
|
| 30 |
+
from dinov3.data import (
|
| 31 |
+
MaskingGenerator,
|
| 32 |
+
SamplerType,
|
| 33 |
+
collate_data_and_cast,
|
| 34 |
+
make_data_loader,
|
| 35 |
+
make_dataset,
|
| 36 |
+
CombinedDataLoader,
|
| 37 |
+
)
|
| 38 |
+
from dinov3.logging import MetricLogger, setup_logging
|
| 39 |
+
from dinov3.train.cosine_lr_scheduler import CosineScheduler, linear_warmup_cosine_decay
|
| 40 |
+
from dinov3.train.multidist_meta_arch import MultiDistillationMetaArch
|
| 41 |
+
from dinov3.train.ssl_meta_arch import SSLMetaArch
|
| 42 |
+
|
| 43 |
+
assert torch.__version__ >= (2, 1)
|
| 44 |
+
torch.backends.cuda.matmul.allow_tf32 = True # pytorch 1.12 sets this to false by default
|
| 45 |
+
torch.backends.cudnn.benchmark = False # True
|
| 46 |
+
|
| 47 |
+
logger = logging.getLogger("dinov3")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_args_parser(add_help: bool = True):
|
| 51 |
+
parser = argparse.ArgumentParser("DINOv3 training", add_help=add_help)
|
| 52 |
+
parser.add_argument("--config-file", default="", metavar="FILE", help="path to config file")
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--no-resume",
|
| 55 |
+
action="store_true",
|
| 56 |
+
help="Whether to not attempt to resume from the checkpoint directory. ",
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument("--eval-only", action="store_true", help="perform evaluation only")
|
| 59 |
+
parser.add_argument("--eval", type=str, default="", help="Eval type to perform")
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--eval_pretrained_weights",
|
| 62 |
+
type=str,
|
| 63 |
+
default="",
|
| 64 |
+
help="Path to pretrained weights",
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument(
|
| 67 |
+
"opts",
|
| 68 |
+
help="""
|
| 69 |
+
Modify config options at the end of the command. For Yacs configs, use
|
| 70 |
+
space-separated "PATH.KEY VALUE" pairs.
|
| 71 |
+
For python-based LazyConfig, use "path.key=value".
|
| 72 |
+
""".strip(),
|
| 73 |
+
default=None,
|
| 74 |
+
nargs=argparse.REMAINDER,
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--output-dir",
|
| 78 |
+
default="./local_dino",
|
| 79 |
+
type=str,
|
| 80 |
+
help="Path to save logs and checkpoints.",
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument("--seed", default=0, type=int, help="RNG seed")
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
"--benchmark-codebase",
|
| 85 |
+
action="store_true",
|
| 86 |
+
help="test the codebase for a few iters",
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument("--test-ibot", action="store_true", help="test ibot")
|
| 89 |
+
parser.add_argument("--profiling", action="store_true", help="do profiling")
|
| 90 |
+
parser.add_argument("--dump-fsdp-weights", action="store_true", help="dump fsdp weights")
|
| 91 |
+
parser.add_argument("--record_ref_losses", action="store_true", help="record reference losses")
|
| 92 |
+
parser.add_argument("--ref_losses_path", default="", type=str)
|
| 93 |
+
parser.add_argument("--multi-distillation", action="store_true", help="run multi-distillation")
|
| 94 |
+
|
| 95 |
+
return parser
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def build_optimizer(cfg, params_groups):
|
| 99 |
+
return torch.optim.AdamW(params_groups, betas=(cfg.optim.adamw_beta1, cfg.optim.adamw_beta2))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def build_schedulers(cfg):
|
| 103 |
+
if "schedules" in cfg:
|
| 104 |
+
logger.info("Using schedules v2")
|
| 105 |
+
return build_schedulers_v2(cfg)
|
| 106 |
+
|
| 107 |
+
OFFICIAL_EPOCH_LENGTH = cfg.train.OFFICIAL_EPOCH_LENGTH
|
| 108 |
+
lr = dict(
|
| 109 |
+
base_value=cfg.optim["lr"],
|
| 110 |
+
final_value=cfg.optim["min_lr"],
|
| 111 |
+
total_iters=cfg.optim["epochs"] * OFFICIAL_EPOCH_LENGTH,
|
| 112 |
+
warmup_iters=cfg.optim["warmup_epochs"] * OFFICIAL_EPOCH_LENGTH,
|
| 113 |
+
start_warmup_value=0,
|
| 114 |
+
trunc_extra=cfg.optim["schedule_trunc_extra"],
|
| 115 |
+
)
|
| 116 |
+
wd = dict(
|
| 117 |
+
base_value=cfg.optim["weight_decay"],
|
| 118 |
+
final_value=cfg.optim["weight_decay_end"],
|
| 119 |
+
total_iters=cfg.optim["epochs"] * OFFICIAL_EPOCH_LENGTH,
|
| 120 |
+
trunc_extra=cfg.optim["schedule_trunc_extra"],
|
| 121 |
+
)
|
| 122 |
+
momentum = dict(
|
| 123 |
+
base_value=cfg.teacher["momentum_teacher"],
|
| 124 |
+
final_value=cfg.teacher["final_momentum_teacher"],
|
| 125 |
+
total_iters=cfg.optim["epochs"] * OFFICIAL_EPOCH_LENGTH,
|
| 126 |
+
trunc_extra=cfg.optim["schedule_trunc_extra"],
|
| 127 |
+
)
|
| 128 |
+
teacher_temp = dict(
|
| 129 |
+
base_value=cfg.teacher["teacher_temp"],
|
| 130 |
+
final_value=cfg.teacher["teacher_temp"],
|
| 131 |
+
total_iters=cfg.teacher["warmup_teacher_temp_epochs"] * OFFICIAL_EPOCH_LENGTH,
|
| 132 |
+
warmup_iters=cfg.teacher["warmup_teacher_temp_epochs"] * OFFICIAL_EPOCH_LENGTH,
|
| 133 |
+
start_warmup_value=cfg.teacher["warmup_teacher_temp"],
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
lr_schedule = CosineScheduler(**lr)
|
| 137 |
+
wd_schedule = CosineScheduler(**wd)
|
| 138 |
+
momentum_schedule = CosineScheduler(**momentum)
|
| 139 |
+
teacher_temp_schedule = CosineScheduler(**teacher_temp)
|
| 140 |
+
last_layer_lr_schedule = CosineScheduler(**lr)
|
| 141 |
+
|
| 142 |
+
last_layer_lr_schedule.schedule[: cfg.optim["freeze_last_layer_epochs"] * OFFICIAL_EPOCH_LENGTH] = (
|
| 143 |
+
0 # mimicking the original schedules
|
| 144 |
+
)
|
| 145 |
+
logger.info("Schedulers ready.")
|
| 146 |
+
return (
|
| 147 |
+
lr_schedule,
|
| 148 |
+
wd_schedule,
|
| 149 |
+
momentum_schedule,
|
| 150 |
+
teacher_temp_schedule,
|
| 151 |
+
last_layer_lr_schedule,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def build_schedulers_v2(cfg):
|
| 156 |
+
iter_per_epoch = cfg.train.OFFICIAL_EPOCH_LENGTH
|
| 157 |
+
total_iterations = cfg.train.OFFICIAL_EPOCH_LENGTH * cfg.optim.epochs
|
| 158 |
+
logger.info(f"Total training iterations {total_iterations}")
|
| 159 |
+
|
| 160 |
+
# LR scaling rules
|
| 161 |
+
lr_peak = cfg.schedules.lr.peak
|
| 162 |
+
lr_end = cfg.schedules.lr.end
|
| 163 |
+
if cfg.optim.scaling_rule == "linear_wrt_256":
|
| 164 |
+
lr_peak *= cfg.train.batch_size_per_gpu * distributed.get_world_size() / 256.0
|
| 165 |
+
lr_end *= cfg.train.batch_size_per_gpu * distributed.get_world_size() / 256.0
|
| 166 |
+
logger.info(
|
| 167 |
+
f"Scaling rule {cfg.optim.scaling_rule}, LR peak {cfg.schedules.lr.peak} -> {lr_peak}, LR end {cfg.schedules.lr.end} -> {lr_end}"
|
| 168 |
+
)
|
| 169 |
+
elif cfg.optim.scaling_rule == "sqrt_wrt_1024":
|
| 170 |
+
lr_peak *= 4 * math.sqrt(cfg.train.batch_size_per_gpu * distributed.get_world_size() / 1024.0)
|
| 171 |
+
lr_end *= 4 * math.sqrt(cfg.train.batch_size_per_gpu * distributed.get_world_size() / 1024.0)
|
| 172 |
+
logger.info(
|
| 173 |
+
f"Scaling rule {cfg.optim.scaling_rule}, LR peak {cfg.schedules.lr.peak} -> {lr_peak}, LR end {cfg.schedules.lr.end} -> {lr_end}"
|
| 174 |
+
)
|
| 175 |
+
else:
|
| 176 |
+
logger.info(f"No scaling rule for {cfg.optim.scaling_rule=}")
|
| 177 |
+
|
| 178 |
+
lr = linear_warmup_cosine_decay(
|
| 179 |
+
start=cfg.schedules.lr.start,
|
| 180 |
+
peak=lr_peak,
|
| 181 |
+
end=lr_end,
|
| 182 |
+
warmup_iterations=iter_per_epoch * cfg.schedules.lr.warmup_epochs,
|
| 183 |
+
total_iterations=total_iterations,
|
| 184 |
+
cosine_iterations=(
|
| 185 |
+
iter_per_epoch * cfg.schedules.lr.cosine_epochs if "cosine_epochs" in cfg.schedules.lr else None
|
| 186 |
+
),
|
| 187 |
+
)
|
| 188 |
+
last_layer_lr = lr.copy()
|
| 189 |
+
last_layer_lr[: iter_per_epoch * cfg.schedules.lr.freeze_last_layer_epochs] = 0
|
| 190 |
+
weight_decay = linear_warmup_cosine_decay(
|
| 191 |
+
start=cfg.schedules.weight_decay.start,
|
| 192 |
+
peak=cfg.schedules.weight_decay.peak,
|
| 193 |
+
end=cfg.schedules.weight_decay.end,
|
| 194 |
+
warmup_iterations=iter_per_epoch * cfg.schedules.weight_decay.warmup_epochs,
|
| 195 |
+
total_iterations=total_iterations,
|
| 196 |
+
cosine_iterations=(
|
| 197 |
+
iter_per_epoch * cfg.schedules.weight_decay.cosine_epochs
|
| 198 |
+
if "cosine_epochs" in cfg.schedules.weight_decay
|
| 199 |
+
else None
|
| 200 |
+
),
|
| 201 |
+
)
|
| 202 |
+
momentum = linear_warmup_cosine_decay(
|
| 203 |
+
start=cfg.schedules.momentum.start,
|
| 204 |
+
peak=cfg.schedules.momentum.peak,
|
| 205 |
+
end=cfg.schedules.momentum.end,
|
| 206 |
+
warmup_iterations=iter_per_epoch * cfg.schedules.momentum.warmup_epochs,
|
| 207 |
+
total_iterations=total_iterations,
|
| 208 |
+
cosine_iterations=(
|
| 209 |
+
iter_per_epoch * cfg.schedules.momentum.cosine_epochs if "cosine_epochs" in cfg.schedules.momentum else None
|
| 210 |
+
),
|
| 211 |
+
)
|
| 212 |
+
teacher_temp = linear_warmup_cosine_decay(
|
| 213 |
+
start=cfg.schedules.teacher_temp.start,
|
| 214 |
+
peak=cfg.schedules.teacher_temp.peak,
|
| 215 |
+
end=cfg.schedules.teacher_temp.end,
|
| 216 |
+
warmup_iterations=iter_per_epoch * cfg.schedules.teacher_temp.warmup_epochs,
|
| 217 |
+
total_iterations=total_iterations,
|
| 218 |
+
cosine_iterations=(
|
| 219 |
+
iter_per_epoch * cfg.schedules.teacher_temp.cosine_epochs
|
| 220 |
+
if "cosine_epochs" in cfg.schedules.teacher_temp
|
| 221 |
+
else None
|
| 222 |
+
),
|
| 223 |
+
)
|
| 224 |
+
return lr, weight_decay, momentum, teacher_temp, last_layer_lr
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def apply_optim_scheduler(optimizer, lr, wd, last_layer_lr):
|
| 228 |
+
for param_group in optimizer.param_groups:
|
| 229 |
+
is_last_layer = param_group["is_last_layer"]
|
| 230 |
+
lr_multiplier = param_group["lr_multiplier"]
|
| 231 |
+
wd_multiplier = param_group["wd_multiplier"]
|
| 232 |
+
param_group["weight_decay"] = wd * wd_multiplier
|
| 233 |
+
if is_last_layer:
|
| 234 |
+
param_group["lr"] = last_layer_lr * lr_multiplier
|
| 235 |
+
else:
|
| 236 |
+
param_group["lr"] = lr * lr_multiplier
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def do_test(cfg, model, iteration, process_group, do_low_freq=False):
|
| 240 |
+
# dump a sharded checkpoint
|
| 241 |
+
eval_dir = Path(cfg.train.output_dir) / "eval" / str(iteration)
|
| 242 |
+
if distributed.is_subgroup_main_process():
|
| 243 |
+
eval_dir.mkdir(parents=True, exist_ok=True)
|
| 244 |
+
if cfg.train.sharded_eval_checkpoint:
|
| 245 |
+
ckpt_path = eval_dir / "sharded_teacher_checkpoint"
|
| 246 |
+
if distributed.is_subgroup_main_process():
|
| 247 |
+
ckpt_path.mkdir(parents=True, exist_ok=True)
|
| 248 |
+
torch.distributed.barrier()
|
| 249 |
+
teacher_backbone = model.model_ema
|
| 250 |
+
save_checkpoint(
|
| 251 |
+
ckpt_dir=ckpt_path, iteration=iteration, model=teacher_backbone, overwrite=True, process_group=process_group
|
| 252 |
+
)
|
| 253 |
+
if not distributed.is_subgroup_main_process():
|
| 254 |
+
return
|
| 255 |
+
else:
|
| 256 |
+
new_state_dict = model.model_ema.state_dict()
|
| 257 |
+
for k, tensor in list(new_state_dict.items()):
|
| 258 |
+
if isinstance(tensor, DTensor):
|
| 259 |
+
new_state_dict[k] = tensor.full_tensor()
|
| 260 |
+
if not distributed.is_subgroup_main_process():
|
| 261 |
+
return
|
| 262 |
+
# save teacher checkpoint
|
| 263 |
+
ckpt_path = eval_dir / "teacher_checkpoint.pth"
|
| 264 |
+
torch.save({"teacher": new_state_dict}, ckpt_path)
|
| 265 |
+
logger.info("Saved eval checkpoint: %s", ckpt_path)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def build_data_loader_from_cfg(
|
| 269 |
+
cfg,
|
| 270 |
+
model,
|
| 271 |
+
start_iter,
|
| 272 |
+
):
|
| 273 |
+
# Collate function
|
| 274 |
+
img_size = cfg.crops.global_crops_size
|
| 275 |
+
patch_size = int(cfg.student.patch_size * cfg.crops.teacher_to_student_resolution_scale)
|
| 276 |
+
n_tokens = (img_size // patch_size) ** 2
|
| 277 |
+
mask_generator = MaskingGenerator(
|
| 278 |
+
input_size=(img_size // patch_size, img_size // patch_size),
|
| 279 |
+
max_num_patches=0.5 * img_size // patch_size * img_size // patch_size,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
if cfg.multidistillation.enabled:
|
| 283 |
+
assert cfg.multidistillation.global_batch_size % distributed.get_subgroup_size() == 0
|
| 284 |
+
local_batch_size = cfg.multidistillation.global_batch_size // distributed.get_subgroup_size()
|
| 285 |
+
dataloader_batch_size_per_gpu = (
|
| 286 |
+
cfg.multidistillation.global_batch_size + (distributed.get_world_size() - 1)
|
| 287 |
+
) // distributed.get_world_size()
|
| 288 |
+
else:
|
| 289 |
+
local_batch_size = None # will default to the standard local batch size matching the data batch size
|
| 290 |
+
dataloader_batch_size_per_gpu = cfg.train.batch_size_per_gpu
|
| 291 |
+
|
| 292 |
+
collate_fn = partial(
|
| 293 |
+
collate_data_and_cast,
|
| 294 |
+
mask_ratio_tuple=cfg.ibot.mask_ratio_min_max,
|
| 295 |
+
mask_probability=cfg.ibot.mask_sample_probability,
|
| 296 |
+
dtype={
|
| 297 |
+
"fp32": torch.float32,
|
| 298 |
+
"fp16": torch.float16,
|
| 299 |
+
"bf16": torch.bfloat16,
|
| 300 |
+
}[cfg.compute_precision.param_dtype],
|
| 301 |
+
n_tokens=n_tokens,
|
| 302 |
+
mask_generator=mask_generator,
|
| 303 |
+
random_circular_shift=cfg.ibot.mask_random_circular_shift,
|
| 304 |
+
local_batch_size=local_batch_size,
|
| 305 |
+
)
|
| 306 |
+
batch_size = dataloader_batch_size_per_gpu
|
| 307 |
+
num_workers = cfg.train.num_workers
|
| 308 |
+
dataset_path = cfg.train.dataset_path
|
| 309 |
+
dataset = make_dataset(
|
| 310 |
+
dataset_str=dataset_path,
|
| 311 |
+
transform=model.build_data_augmentation_dino(cfg),
|
| 312 |
+
target_transform=lambda _: (),
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
if isinstance(dataset, torch.utils.data.IterableDataset):
|
| 316 |
+
sampler_type = SamplerType.INFINITE
|
| 317 |
+
else:
|
| 318 |
+
sampler_type = SamplerType.SHARDED_INFINITE if cfg.train.cache_dataset else SamplerType.INFINITE
|
| 319 |
+
|
| 320 |
+
data_loader = make_data_loader(
|
| 321 |
+
dataset=dataset,
|
| 322 |
+
batch_size=batch_size,
|
| 323 |
+
num_workers=num_workers,
|
| 324 |
+
shuffle=True,
|
| 325 |
+
seed=cfg.train.seed + start_iter + 1,
|
| 326 |
+
sampler_type=sampler_type,
|
| 327 |
+
sampler_advance=start_iter * dataloader_batch_size_per_gpu,
|
| 328 |
+
drop_last=True,
|
| 329 |
+
collate_fn=collate_fn,
|
| 330 |
+
)
|
| 331 |
+
return data_loader
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def build_multi_resolution_data_loader_from_cfg(
|
| 335 |
+
cfg,
|
| 336 |
+
model,
|
| 337 |
+
start_iter,
|
| 338 |
+
seed=65537,
|
| 339 |
+
):
|
| 340 |
+
global_crops_sizes = (
|
| 341 |
+
[cfg.crops.global_crops_size] if isinstance(cfg.crops.global_crops_size, int) else cfg.crops.global_crops_size
|
| 342 |
+
)
|
| 343 |
+
local_crops_sizes = (
|
| 344 |
+
[cfg.crops.local_crops_size] if isinstance(cfg.crops.local_crops_size, int) else cfg.crops.local_crops_size
|
| 345 |
+
)
|
| 346 |
+
gram_teacher_crops_sizes = (
|
| 347 |
+
[cfg.crops.gram_teacher_crops_size]
|
| 348 |
+
if cfg.crops.gram_teacher_crops_size is None or isinstance(cfg.crops.gram_teacher_crops_size, int)
|
| 349 |
+
else cfg.crops.gram_teacher_crops_size
|
| 350 |
+
)
|
| 351 |
+
loader_ratios = (
|
| 352 |
+
[cfg.crops.global_local_crop_pairs_ratios]
|
| 353 |
+
if type(cfg.crops.global_local_crop_pairs_ratios) in [int, float]
|
| 354 |
+
else cfg.crops.global_local_crop_pairs_ratios
|
| 355 |
+
)
|
| 356 |
+
assert len(global_crops_sizes) == len(local_crops_sizes) == len(gram_teacher_crops_sizes) == len(loader_ratios)
|
| 357 |
+
|
| 358 |
+
loaders = []
|
| 359 |
+
for increment, (global_crops_size_i, local_crops_size_i, gram_teacher_crops_size_i) in enumerate(
|
| 360 |
+
zip(global_crops_sizes, local_crops_sizes, gram_teacher_crops_sizes)
|
| 361 |
+
):
|
| 362 |
+
cfg_i = copy.deepcopy(cfg)
|
| 363 |
+
cfg_i.crops.global_crops_size = global_crops_size_i
|
| 364 |
+
cfg_i.crops.local_crops_size = local_crops_size_i
|
| 365 |
+
cfg_i.crops.gram_teacher_crops_size = gram_teacher_crops_size_i
|
| 366 |
+
cfg_i.train.seed = cfg.train.seed + increment + 1
|
| 367 |
+
loaders.append(build_data_loader_from_cfg(cfg=cfg_i, model=model, start_iter=start_iter))
|
| 368 |
+
|
| 369 |
+
if len(loaders) == 1:
|
| 370 |
+
data_loader = loaders[0]
|
| 371 |
+
else:
|
| 372 |
+
data_loader = CombinedDataLoader(
|
| 373 |
+
loaders_with_ratios=zip(loaders, loader_ratios),
|
| 374 |
+
batch_size=cfg.train.batch_size_per_gpu,
|
| 375 |
+
combining_mode=0,
|
| 376 |
+
seed=seed,
|
| 377 |
+
name="MultiResDL",
|
| 378 |
+
)
|
| 379 |
+
return data_loader
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def do_train(cfg, model, resume=False):
|
| 383 |
+
process_subgroup = distributed.get_process_subgroup()
|
| 384 |
+
ckpt_dir = Path(cfg.train.output_dir, "ckpt").expanduser()
|
| 385 |
+
ckpt_dir.mkdir(parents=True, exist_ok=True)
|
| 386 |
+
|
| 387 |
+
model.train()
|
| 388 |
+
# Optimizer
|
| 389 |
+
optimizer = build_optimizer(cfg, model.get_params_groups())
|
| 390 |
+
(
|
| 391 |
+
lr_schedule,
|
| 392 |
+
wd_schedule,
|
| 393 |
+
momentum_schedule,
|
| 394 |
+
teacher_temp_schedule,
|
| 395 |
+
last_layer_lr_schedule,
|
| 396 |
+
) = build_schedulers(cfg)
|
| 397 |
+
if cfg.multidistillation.enabled:
|
| 398 |
+
register_dont_save_hooks(
|
| 399 |
+
model,
|
| 400 |
+
dont_save=[k for k, _ in model.state_dict().items() if k.startswith("teacher")],
|
| 401 |
+
)
|
| 402 |
+
model.init_weights()
|
| 403 |
+
start_iter = 0
|
| 404 |
+
if resume and (last_checkpoint_dir := find_latest_checkpoint(ckpt_dir)):
|
| 405 |
+
logger.info(f"Checkpoint found {last_checkpoint_dir}")
|
| 406 |
+
start_iter = (
|
| 407 |
+
load_checkpoint(
|
| 408 |
+
last_checkpoint_dir,
|
| 409 |
+
model=model,
|
| 410 |
+
optimizer=optimizer,
|
| 411 |
+
strict_loading=False,
|
| 412 |
+
process_group=process_subgroup,
|
| 413 |
+
)
|
| 414 |
+
+ 1
|
| 415 |
+
)
|
| 416 |
+
OFFICIAL_EPOCH_LENGTH = cfg.train.OFFICIAL_EPOCH_LENGTH
|
| 417 |
+
max_iter = cfg.optim.epochs * OFFICIAL_EPOCH_LENGTH
|
| 418 |
+
if cfg.multidistillation.enabled:
|
| 419 |
+
global_batch_size = cfg.multidistillation.global_batch_size
|
| 420 |
+
else:
|
| 421 |
+
global_batch_size = cfg.train.batch_size_per_gpu * distributed.get_world_size()
|
| 422 |
+
|
| 423 |
+
# Build data loader
|
| 424 |
+
data_loader = build_multi_resolution_data_loader_from_cfg(
|
| 425 |
+
cfg=cfg,
|
| 426 |
+
model=model,
|
| 427 |
+
start_iter=start_iter,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
# Metric logging
|
| 431 |
+
logger.info("Starting training from iteration %d", start_iter)
|
| 432 |
+
metrics_file = os.path.join(cfg.train.output_dir, "training_metrics.json")
|
| 433 |
+
metric_logger = MetricLogger(delimiter=" ", output_file=metrics_file)
|
| 434 |
+
# Manual garbage collection
|
| 435 |
+
gc.disable()
|
| 436 |
+
gc.collect()
|
| 437 |
+
|
| 438 |
+
# Training loop
|
| 439 |
+
student = model.student
|
| 440 |
+
iteration = start_iter
|
| 441 |
+
num_gram_updates = 0
|
| 442 |
+
if (
|
| 443 |
+
cfg.gram.use_loss
|
| 444 |
+
and model.has_gram_teacher
|
| 445 |
+
and cfg.gram.rep_update
|
| 446 |
+
and start_iter > 0
|
| 447 |
+
and start_iter >= cfg.gram.it_first_update
|
| 448 |
+
):
|
| 449 |
+
# If `start_iter == it_first_update`, we have performed one gram teacher update after
|
| 450 |
+
# iteration `start_iter - 1`, except if we are starting training from scratch and `start_iter == 0`.
|
| 451 |
+
num_gram_updates = math.ceil((start_iter + 1 - cfg.gram.it_first_update) / cfg.gram.update_frequency)
|
| 452 |
+
logger.info(f"Gram was updated {num_gram_updates} times before iteration {start_iter}")
|
| 453 |
+
consecutive_nan_count = 0
|
| 454 |
+
for data in metric_logger.log_every(
|
| 455 |
+
data_loader,
|
| 456 |
+
print_freq=10,
|
| 457 |
+
header="Training",
|
| 458 |
+
n_iterations=max_iter,
|
| 459 |
+
start_iteration=start_iter,
|
| 460 |
+
):
|
| 461 |
+
it = iteration
|
| 462 |
+
data["global_batch_size"] = global_batch_size
|
| 463 |
+
if iteration > max_iter:
|
| 464 |
+
return
|
| 465 |
+
|
| 466 |
+
# Garbage collection (trigger manually so it happens on all ranks at the same time)
|
| 467 |
+
if (iteration + 1) % 150 == 0:
|
| 468 |
+
logger.info("Garbage collection")
|
| 469 |
+
gc.collect()
|
| 470 |
+
|
| 471 |
+
if cfg.gram.use_loss and model.gram_it_load_ema_teacher == it:
|
| 472 |
+
logger.info(f"Loading EMA teacher into Gram teacher before iteration {it}")
|
| 473 |
+
model.gram_load_ema_teacher()
|
| 474 |
+
|
| 475 |
+
# Learning rates and other schedules
|
| 476 |
+
lr = lr_schedule[it]
|
| 477 |
+
wd = wd_schedule[it]
|
| 478 |
+
mom = momentum_schedule[it]
|
| 479 |
+
teacher_temp = teacher_temp_schedule[it]
|
| 480 |
+
last_layer_lr = last_layer_lr_schedule[it]
|
| 481 |
+
apply_optim_scheduler(optimizer, lr, wd, last_layer_lr)
|
| 482 |
+
|
| 483 |
+
# Forward backward
|
| 484 |
+
optimizer.zero_grad(set_to_none=True)
|
| 485 |
+
total_loss, metrics_dict = model.forward_backward(data, teacher_temp=teacher_temp, iteration=it)
|
| 486 |
+
|
| 487 |
+
# Gradient clipping
|
| 488 |
+
if cfg.optim.clip_grad:
|
| 489 |
+
for k, v in student.items():
|
| 490 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(
|
| 491 |
+
v.parameters(),
|
| 492 |
+
max_norm=cfg.optim.clip_grad,
|
| 493 |
+
)
|
| 494 |
+
metrics_dict[f"{k}_grad_norm"] = (
|
| 495 |
+
grad_norm.full_tensor().item()
|
| 496 |
+
if isinstance(grad_norm, torch.distributed.tensor.DTensor)
|
| 497 |
+
else grad_norm.item()
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
# Reduce total_loss to check for NaNs, reduce metrics for logging
|
| 501 |
+
total_loss_all_ranks = total_loss.new_empty(distributed.get_subgroup_size())
|
| 502 |
+
torch.distributed.all_gather_into_tensor(
|
| 503 |
+
total_loss_all_ranks,
|
| 504 |
+
total_loss.detach(),
|
| 505 |
+
group=distributed.get_process_subgroup(),
|
| 506 |
+
)
|
| 507 |
+
total_loss = total_loss_all_ranks.mean()
|
| 508 |
+
metrics_values = torch.stack(
|
| 509 |
+
[torch.as_tensor(v, dtype=torch.float32, device=total_loss.device).detach() for v in metrics_dict.values()]
|
| 510 |
+
)
|
| 511 |
+
torch.distributed.all_reduce(
|
| 512 |
+
metrics_values,
|
| 513 |
+
op=torch.distributed.ReduceOp.AVG,
|
| 514 |
+
group=distributed.get_process_subgroup(),
|
| 515 |
+
)
|
| 516 |
+
metrics_dict = dict(zip(metrics_dict.keys(), metrics_values))
|
| 517 |
+
if total_loss_all_ranks.isnan().any():
|
| 518 |
+
consecutive_nan_count += 1
|
| 519 |
+
which_ranks = total_loss_all_ranks.isnan().nonzero().flatten().tolist()
|
| 520 |
+
logger.warning("NaN loss detected on ranks: %s", which_ranks)
|
| 521 |
+
logger.warning("Consecutive NaNs: %d", consecutive_nan_count)
|
| 522 |
+
metrics_dict_str = "\n".join([f"{k}: {v}" for k, v in metrics_dict.items()])
|
| 523 |
+
logger.warning("All-reduced metrics:\n%s", metrics_dict_str)
|
| 524 |
+
if consecutive_nan_count > 2 and not cfg.multidistillation.enabled:
|
| 525 |
+
msg = "Too many consecutive nans detected in loss, aborting..."
|
| 526 |
+
logger.error(msg)
|
| 527 |
+
raise RuntimeError(msg)
|
| 528 |
+
else:
|
| 529 |
+
consecutive_nan_count = 0
|
| 530 |
+
# Step optimizer
|
| 531 |
+
optimizer.step()
|
| 532 |
+
model.update_ema(mom)
|
| 533 |
+
|
| 534 |
+
# [GRAM] Update gram teacher when using gram teacher and frequent updates
|
| 535 |
+
if (
|
| 536 |
+
cfg.gram.use_loss
|
| 537 |
+
and model.gram_rep_update
|
| 538 |
+
and (it + 1) >= model.gram_it_first_update
|
| 539 |
+
and (it + 1) % model.gram_update_frequency == 0
|
| 540 |
+
and (cfg.gram.max_updates is None or num_gram_updates < cfg.gram.max_updates)
|
| 541 |
+
):
|
| 542 |
+
logger.info(f"Updating Gram teacher from EMA teacher after iteration {it}")
|
| 543 |
+
model.update_gram()
|
| 544 |
+
num_gram_updates += 1
|
| 545 |
+
|
| 546 |
+
# Log metrics
|
| 547 |
+
metric_logger.update(lr=lr)
|
| 548 |
+
metric_logger.update(wd=wd)
|
| 549 |
+
metric_logger.update(mom=mom)
|
| 550 |
+
metric_logger.update(last_layer_lr=last_layer_lr)
|
| 551 |
+
metric_logger.update(total_loss=total_loss, **metrics_dict)
|
| 552 |
+
|
| 553 |
+
# Submit evaluation jobs
|
| 554 |
+
if (
|
| 555 |
+
cfg.evaluation.eval_period_iterations > 0 and (iteration + 1) % cfg.evaluation.eval_period_iterations == 0
|
| 556 |
+
# and iteration != max_iter - 1
|
| 557 |
+
):
|
| 558 |
+
do_test(cfg, model, f"training_{iteration}", process_group=process_subgroup)
|
| 559 |
+
torch.cuda.synchronize()
|
| 560 |
+
|
| 561 |
+
# Checkpointing
|
| 562 |
+
if (iteration + 1) % cfg.checkpointing.period == 0:
|
| 563 |
+
torch.cuda.synchronize()
|
| 564 |
+
save_checkpoint(
|
| 565 |
+
ckpt_dir / str(iteration),
|
| 566 |
+
iteration=iteration,
|
| 567 |
+
model=model,
|
| 568 |
+
optimizer=optimizer,
|
| 569 |
+
overwrite=True,
|
| 570 |
+
process_group=process_subgroup,
|
| 571 |
+
)
|
| 572 |
+
if distributed.is_subgroup_main_process():
|
| 573 |
+
keep_last_n_checkpoints(ckpt_dir, cfg.checkpointing.max_to_keep)
|
| 574 |
+
if "keep_every" in cfg.checkpointing and (iteration + 1) % cfg.checkpointing.keep_every == 0:
|
| 575 |
+
keep_checkpoint_copy(ckpt_dir / str(iteration))
|
| 576 |
+
|
| 577 |
+
iteration = iteration + 1
|
| 578 |
+
metric_logger.synchronize_between_processes()
|
| 579 |
+
|
| 580 |
+
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def main(argv=None):
|
| 584 |
+
if argv is None:
|
| 585 |
+
args = get_args_parser().parse_args()
|
| 586 |
+
else:
|
| 587 |
+
args = get_args_parser().parse_args(argv[1:])
|
| 588 |
+
args.output_dir = sys.argv[1]
|
| 589 |
+
if args.multi_distillation:
|
| 590 |
+
print("performing multidistillation run")
|
| 591 |
+
cfg = setup_multidistillation(args)
|
| 592 |
+
torch.distributed.barrier()
|
| 593 |
+
logger.info("setup_multidistillation done")
|
| 594 |
+
assert cfg.MODEL.META_ARCHITECTURE == "MultiDistillationMetaArch"
|
| 595 |
+
else:
|
| 596 |
+
setup_job(output_dir=args.output_dir, seed=args.seed)
|
| 597 |
+
cfg = setup_config(args, strict_cfg=False)
|
| 598 |
+
logger.info(cfg)
|
| 599 |
+
setup_logging(
|
| 600 |
+
output=os.path.join(os.path.abspath(args.output_dir), "nan_logs"),
|
| 601 |
+
name="nan_logger",
|
| 602 |
+
)
|
| 603 |
+
meta_arch = {
|
| 604 |
+
"SSLMetaArch": SSLMetaArch,
|
| 605 |
+
"MultiDistillationMetaArch": MultiDistillationMetaArch,
|
| 606 |
+
}.get(cfg.MODEL.META_ARCHITECTURE, None)
|
| 607 |
+
if meta_arch is None:
|
| 608 |
+
raise ValueError(f"Unknown MODEL.META_ARCHITECTURE {cfg.MODEL.META_ARCHITECTURE}")
|
| 609 |
+
logger.info(f"Making meta arch {meta_arch.__name__}")
|
| 610 |
+
with torch.device("meta"):
|
| 611 |
+
model = meta_arch(cfg)
|
| 612 |
+
model.prepare_for_distributed_training()
|
| 613 |
+
# Fill all values with `nans` so that we identify
|
| 614 |
+
# non-initialized values
|
| 615 |
+
model._apply(
|
| 616 |
+
lambda t: torch.full_like(
|
| 617 |
+
t,
|
| 618 |
+
fill_value=math.nan if t.dtype.is_floating_point else (2 ** (t.dtype.itemsize * 8 - 1)),
|
| 619 |
+
device="cuda",
|
| 620 |
+
),
|
| 621 |
+
recurse=True,
|
| 622 |
+
)
|
| 623 |
+
logger.info(f"Model after distributed:\n{model}")
|
| 624 |
+
if args.eval_only:
|
| 625 |
+
model.init_weights()
|
| 626 |
+
iteration = (
|
| 627 |
+
model.get_checkpointer_class()(model, save_dir=cfg.train.output_dir)
|
| 628 |
+
.resume_or_load(cfg.MODEL.WEIGHTS, resume=not args.no_resume)
|
| 629 |
+
.get("iteration", -1)
|
| 630 |
+
+ 1
|
| 631 |
+
)
|
| 632 |
+
return do_test(cfg, model, f"manual_{iteration}")
|
| 633 |
+
do_train(cfg, model, resume=not args.no_resume)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
if __name__ == "__main__":
|
| 637 |
+
main()
|
starVLA/dinov3/dinov3/utils/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
from .dtype import as_torch_dtype
|
| 7 |
+
from .utils import (
|
| 8 |
+
cat_keep_shapes,
|
| 9 |
+
count_parameters,
|
| 10 |
+
fix_random_seeds,
|
| 11 |
+
get_conda_env,
|
| 12 |
+
get_sha,
|
| 13 |
+
named_apply,
|
| 14 |
+
named_replace,
|
| 15 |
+
uncat_with_shapes,
|
| 16 |
+
)
|
starVLA/dinov3/dinov3/utils/cluster.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This software may be used and distributed in accordance with
|
| 4 |
+
# the terms of the DINOv3 License Agreement.
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from enum import Enum
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Dict, Optional
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ClusterType(Enum):
|
| 13 |
+
CW = "cw"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _guess_cluster_type() -> ClusterType:
|
| 17 |
+
return ClusterType.CW
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_cluster_type(
|
| 21 |
+
cluster_type: Optional[ClusterType] = None,
|
| 22 |
+
) -> Optional[ClusterType]:
|
| 23 |
+
if cluster_type is None:
|
| 24 |
+
return _guess_cluster_type()
|
| 25 |
+
|
| 26 |
+
return cluster_type
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_slurm_account(cluster_type: Optional[ClusterType] = None) -> Optional[str]:
|
| 30 |
+
cluster_type = get_cluster_type(cluster_type)
|
| 31 |
+
if cluster_type is None:
|
| 32 |
+
return None
|
| 33 |
+
return {
|
| 34 |
+
ClusterType.CW: "fair_amaia_cw_explore",
|
| 35 |
+
}[cluster_type]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_checkpoint_path(cluster_type: Optional[ClusterType] = None) -> Optional[Path]:
|
| 39 |
+
cluster_type = get_cluster_type(cluster_type)
|
| 40 |
+
if cluster_type is None:
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
CHECKPOINT_DIRNAMES = {
|
| 44 |
+
ClusterType.CW: "",
|
| 45 |
+
}
|
| 46 |
+
return Path("/") / CHECKPOINT_DIRNAMES[cluster_type]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_user_checkpoint_path(
|
| 50 |
+
cluster_type: Optional[ClusterType] = None,
|
| 51 |
+
) -> Optional[Path]:
|
| 52 |
+
checkpoint_path = get_checkpoint_path(cluster_type)
|
| 53 |
+
if checkpoint_path is None:
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
username = os.environ.get("USER")
|
| 57 |
+
assert username is not None
|
| 58 |
+
return checkpoint_path / username
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_slurm_qos(cluster_type: Optional[ClusterType] = None) -> Optional[str]:
|
| 62 |
+
cluster_type = get_cluster_type(cluster_type)
|
| 63 |
+
if cluster_type is None:
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
return {
|
| 67 |
+
ClusterType.CW: "explore",
|
| 68 |
+
}.get(cluster_type)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_slurm_partition(cluster_type: Optional[ClusterType] = None) -> Optional[str]:
|
| 72 |
+
cluster_type = get_cluster_type(cluster_type)
|
| 73 |
+
if cluster_type is None:
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
SLURM_PARTITIONS = {
|
| 77 |
+
ClusterType.CW: "learn",
|
| 78 |
+
}
|
| 79 |
+
return SLURM_PARTITIONS[cluster_type]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_slurm_executor_parameters(
|
| 83 |
+
nodes: int,
|
| 84 |
+
num_gpus_per_node: int,
|
| 85 |
+
cluster_type: Optional[ClusterType] = None,
|
| 86 |
+
**kwargs,
|
| 87 |
+
) -> Dict[str, Any]:
|
| 88 |
+
# create default parameters
|
| 89 |
+
params = {
|
| 90 |
+
"mem_gb": 0, # Requests all memory on a node, see https://slurm.schedmd.com/sbatch.html
|
| 91 |
+
"gpus_per_node": num_gpus_per_node,
|
| 92 |
+
"tasks_per_node": num_gpus_per_node, # one task per GPU
|
| 93 |
+
"cpus_per_task": 10,
|
| 94 |
+
"nodes": nodes,
|
| 95 |
+
"slurm_partition": get_slurm_partition(cluster_type),
|
| 96 |
+
}
|
| 97 |
+
# apply cluster-specific adjustments
|
| 98 |
+
cluster_type = get_cluster_type(cluster_type)
|
| 99 |
+
if cluster_type == ClusterType.CW:
|
| 100 |
+
params["cpus_per_task"] = 16
|
| 101 |
+
# set additional parameters / apply overrides
|
| 102 |
+
params.update(kwargs)
|
| 103 |
+
return params
|