add gradio demo
Browse filesFiles changed (24)
- .gitattributes+2
- app.pyAdded+168
- assets/example_videos/Tokyo-Walk_rgb.mp4Added+3
- assets/example_videos/davis_rollercoaster.mp4Added+3
- assets/teaser_video_v2.pngAdded
- requirements.txtAdded+19
- utils/dc_utils.pyAdded+82
- utils/util.pyAdded+74
- video_depth_anything/dinov2.pyAdded+415
- video_depth_anything/dinov2_layers/__init__.pyAdded+11
- video_depth_anything/dinov2_layers/attention.pyAdded+83
- video_depth_anything/dinov2_layers/block.pyAdded+252
- video_depth_anything/dinov2_layers/drop_path.pyAdded+35
- video_depth_anything/dinov2_layers/layer_scale.pyAdded+28
- video_depth_anything/dinov2_layers/mlp.pyAdded+41
- video_depth_anything/dinov2_layers/patch_embed.pyAdded+89
- video_depth_anything/dinov2_layers/swiglu_ffn.pyAdded+63
- video_depth_anything/dpt.pyAdded+160
- video_depth_anything/dpt_temporal.pyAdded+96
- video_depth_anything/motion_module/attention.pyAdded+423
- video_depth_anything/motion_module/motion_module.pyAdded+288
- video_depth_anything/util/blocks.pyAdded+162
- video_depth_anything/util/transform.pyAdded+158
- video_depth_anything/video_depth.pyAdded+149
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.mp4 filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Copyright (2025) Bytedance Ltd. and/or its affiliates
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gradio as gr
import numpy as npimport osimport torch
from video_depth_anything.video_depth import VideoDepthAnythingfrom utils.dc_utils import read_video_frames, vis_sequence_depth, save_video
from huggingface_hub import hf_hub_download
examples = [ ['assets/example_videos/davis_rollercoaster.mp4'],]
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
model_configs = { 'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]}, 'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},}
encoder2name = { 'vits': 'Small', 'vitl': 'Large',}
encoder='vitl'model_name = encoder2name[encoder]
video_depth_anything = VideoDepthAnything(**model_configs[encoder])filepath = hf_hub_download(repo_id=f"depth-anything/Video-Depth-Anything-{model_name}", filename=f"video_depth_anything_{encoder}.pth", repo_type="model")video_depth_anything.load_state_dict(torch.load(filepath, map_location='cpu'))video_depth_anything = video_depth_anything.to(DEVICE).eval()
title = "# Video Depth Anything"description = """Official demo for **Video Depth Anything**.Please refer to our [project page](https://videodepthanything.github.io/), and [github](https://github.com/DepthAnything/Video-Depth-Anything) for more details."""
def infer_video_depth( input_video: str, max_len: int = -1, target_fps: int = -1, max_res: int = 1280, output_dir: str = './outputs', input_size: int = 518,): frames, target_fps = read_video_frames(input_video, max_len, target_fps, max_res) depth_list, fps = video_depth_anything.infer_video_depth(frames, target_fps, input_size=input_size, device=DEVICE) depth_list = np.stack(depth_list, axis=0) vis = vis_sequence_depth(depth_list) video_name = os.path.basename(input_video) if not os.path.exists(output_dir): os.makedirs(output_dir)
processed_video_path = os.path.join(output_dir, os.path.splitext(video_name)[0]+'_src.mp4') depth_vis_path = os.path.join(output_dir, os.path.splitext(video_name)[0]+'_vis.mp4') save_video(frames, processed_video_path, fps=fps) save_video(vis, depth_vis_path, fps=fps)
return [processed_video_path, depth_vis_path]
def construct_demo(): with gr.Blocks(analytics_enabled=False) as demo: gr.Markdown(title) gr.Markdown(description) gr.Markdown("### Video Depth Prediction demo")
with gr.Row(equal_height=True): with gr.Column(scale=1): input_video = gr.Video(label="Input Video")
# with gr.Tab(label="Output"): with gr.Column(scale=2): with gr.Row(equal_height=True): processed_video = gr.Video( label="Preprocessed video", interactive=False, autoplay=True, loop=True, show_share_button=True, scale=5, ) depth_vis_video = gr.Video( label="Generated Depth Video", interactive=False, autoplay=True, loop=True, show_share_button=True, scale=5, )
with gr.Row(equal_height=True): with gr.Column(scale=1): with gr.Row(equal_height=False): with gr.Accordion("Advanced Settings", open=False): max_len = gr.Slider( label="max process length", minimum=-1, maximum=1000, value=-1, step=1, ) target_fps = gr.Slider( label="target FPS", minimum=-1, maximum=30, value=15, step=1, ) max_res = gr.Slider( label="max side resolution", minimum=480, maximum=1920, value=1280, step=1, ) generate_btn = gr.Button("Generate") with gr.Column(scale=2): pass
gr.Examples( examples=examples, inputs=[ input_video, max_len, target_fps, max_res ], outputs=[processed_video, depth_vis_video], fn=infer_video_depth, cache_examples="lazy", )
generate_btn.click( fn=infer_video_depth, inputs=[ input_video, max_len, target_fps, max_res ], outputs=[processed_video, depth_vis_video], )
return demo
if __name__ == "__main__": demo = construct_demo() demo.queue() demo.launch(share=True)123version https://git-lfs.github.com/spec/v1oid sha256:097f16c33dd8c8d1d2a24d9ea31a90b76bd0ee324b958a47385183e3547a63a8size 2251450123version https://git-lfs.github.com/spec/v1oid sha256:7268cbecd9806a1e90a416de50dc02e50b4ae01428d5971837cf679dd0c87cb8size 180956012345678910111213141516171819gradio_imageslidergradio==4.36.0torchtorchvisionopencv-pythonmatplotlibhuggingface_hubtypingtempfilepillowmediapydecordxformerseinopsmathfunctoolsloggingeasydicttqdm12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# This file is originally from DepthCrafter/depthcrafter/utils.py at main · Tencent/DepthCrafter# SPDX-License-Identifier: MIT License license## This file may have been modified by ByteDance Ltd. and/or its affiliates on [date of modification]# Original file is released under [ MIT License license], with the full license text available at [https://github.com/Tencent/DepthCrafter?tab=License-1-ov-file].from typing import Union, Listimport tempfileimport numpy as npimport PIL.Imageimport matplotlib.cm as cmimport mediapyimport torchfrom decord import VideoReader, cpu
def read_video_frames(video_path, process_length, target_fps=-1, max_res=-1, dataset="open"):
vid = VideoReader(video_path, ctx=cpu(0)) original_height, original_width = vid.get_batch([0]).shape[1:3] height = original_height width = original_width if max_res > 0 and max(height, width) > max_res: scale = max_res / max(original_height, original_width) height = round(original_height * scale) width = round(original_width * scale)
vid = VideoReader(video_path, ctx=cpu(0), width=width, height=height)
fps = vid.get_avg_fps() if target_fps == -1 else target_fps stride = round(vid.get_avg_fps() / fps) stride = max(stride, 1) frames_idx = list(range(0, len(vid), stride)) if process_length != -1 and process_length < len(frames_idx): frames_idx = frames_idx[:process_length] frames = vid.get_batch(frames_idx).asnumpy()
return frames, fps
def save_video( video_frames: Union[List[np.ndarray], List[PIL.Image.Image]], output_video_path: str = None, fps: int = 10, crf: int = 18,) -> str: if output_video_path is None: output_video_path = tempfile.NamedTemporaryFile(suffix=".mp4").name
if isinstance(video_frames[0], np.ndarray): video_frames = [frame.astype(np.uint8) for frame in video_frames]
elif isinstance(video_frames[0], PIL.Image.Image): video_frames = [np.array(frame) for frame in video_frames] mediapy.write_video(output_video_path, video_frames, fps=fps, crf=crf) return output_video_path
class ColorMapper: # a color mapper to map depth values to a certain colormap def __init__(self, colormap: str = "inferno"): self.colormap = torch.tensor(cm.get_cmap(colormap).colors)
def apply(self, image: torch.Tensor, v_min=None, v_max=None): # assert len(image.shape) == 2 if v_min is None: v_min = image.min() if v_max is None: v_max = image.max() image = (image - v_min) / (v_max - v_min) image = (image * 255).long() image = self.colormap[image] * 255 return image
def vis_sequence_depth(depths: np.ndarray, v_min=None, v_max=None): visualizer = ColorMapper() if v_min is None: v_min = depths.min() if v_max is None: v_max = depths.max() res = visualizer.apply(torch.tensor(depths), v_min=v_min, v_max=v_max).numpy() return res1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# Copyright (2025) Bytedance Ltd. and/or its affiliates
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np
def compute_scale_and_shift(prediction, target, mask, scale_only=False): if scale_only: return compute_scale(prediction, target, mask), 0 else: return compute_scale_and_shift_full(prediction, target, mask)
def compute_scale(prediction, target, mask): # system matrix: A = [[a_00, a_01], [a_10, a_11]] prediction = prediction.astype(np.float32) target = target.astype(np.float32) mask = mask.astype(np.float32)
a_00 = np.sum(mask * prediction * prediction) a_01 = np.sum(mask * prediction) a_11 = np.sum(mask)
# right hand side: b = [b_0, b_1] b_0 = np.sum(mask * prediction * target)
x_0 = b_0 / (a_00 + 1e-6)
return x_0
def compute_scale_and_shift_full(prediction, target, mask): # system matrix: A = [[a_00, a_01], [a_10, a_11]] prediction = prediction.astype(np.float32) target = target.astype(np.float32) mask = mask.astype(np.float32)
a_00 = np.sum(mask * prediction * prediction) a_01 = np.sum(mask * prediction) a_11 = np.sum(mask)
b_0 = np.sum(mask * prediction * target) b_1 = np.sum(mask * target)
x_0 = 1 x_1 = 0
det = a_00 * a_11 - a_01 * a_01
if det != 0: x_0 = (a_11 * b_0 - a_01 * b_1) / det x_1 = (-a_01 * b_0 + a_00 * b_1) / det
return x_0, x_1
def get_interpolate_frames(frame_list_pre, frame_list_post): assert len(frame_list_pre) == len(frame_list_post) min_w = 0.0 max_w = 1.0 step = (max_w - min_w) / (len(frame_list_pre)-1) post_w_list = [min_w] + [i * step for i in range(1,len(frame_list_pre)-1)] + [max_w] interpolated_frames = [] for i in range(len(frame_list_pre)): interpolated_frames.append(frame_list_pre[i] * (1-post_w_list[i]) + frame_list_post[i] * post_w_list[i]) return interpolated_frames123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415# Copyright (c) Meta Platforms, Inc. and affiliates.## This source code is licensed under the Apache License, Version 2.0# found in the LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
from functools import partialimport mathimport loggingfrom typing import Sequence, Tuple, Union, Callable
import torchimport torch.nn as nnimport torch.utils.checkpointfrom torch.nn.init import trunc_normal_
from .dinov2_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
logger = logging.getLogger("dinov2")
def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module: if not depth_first and include_root: fn(module=module, name=name) for child_name, child_module in module.named_children(): child_name = ".".join((name, child_name)) if name else child_name named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True) if depth_first and include_root: fn(module=module, name=name) return module
class BlockChunk(nn.ModuleList): def forward(self, x): for b in self: x = b(x) return x
class DinoVisionTransformer(nn.Module): def __init__( self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, ffn_bias=True, proj_bias=True, drop_path_rate=0.0, drop_path_uniform=False, init_values=None, # for layerscale: None or 0 => no layerscale embed_layer=PatchEmbed, act_layer=nn.GELU, block_fn=Block, ffn_layer="mlp", block_chunks=1, num_register_tokens=0, interpolate_antialias=False, interpolate_offset=0.1, ): """ Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads mlp_ratio (int): ratio of mlp hidden dim to embedding dim qkv_bias (bool): enable bias for qkv if True proj_bias (bool): enable bias for proj in attn if True ffn_bias (bool): enable bias for ffn if True drop_path_rate (float): stochastic depth rate drop_path_uniform (bool): apply uniform drop rate across blocks weight_init (str): weight init scheme init_values (float): layer-scale init values embed_layer (nn.Module): patch embedding layer act_layer (nn.Module): MLP activation layer block_fn (nn.Module): transformer block class ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity" block_chunks: (int) split block sequence into block_chunks units for FSDP wrap num_register_tokens: (int) number of extra cls tokens (so-called "registers") interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings """ super().__init__() norm_layer = partial(nn.LayerNorm, eps=1e-6)
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models self.num_tokens = 1 self.n_blocks = depth self.num_heads = num_heads self.patch_size = patch_size self.num_register_tokens = num_register_tokens self.interpolate_antialias = interpolate_antialias self.interpolate_offset = interpolate_offset
self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) num_patches = self.patch_embed.num_patches
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim)) assert num_register_tokens >= 0 self.register_tokens = ( nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None )
if drop_path_uniform is True: dpr = [drop_path_rate] * depth else: dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
if ffn_layer == "mlp": logger.info("using MLP layer as FFN") ffn_layer = Mlp elif ffn_layer == "swiglufused" or ffn_layer == "swiglu": logger.info("using SwiGLU layer as FFN") ffn_layer = SwiGLUFFNFused elif ffn_layer == "identity": logger.info("using Identity layer as FFN")
def f(*args, **kwargs): return nn.Identity()
ffn_layer = f else: raise NotImplementedError
blocks_list = [ block_fn( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, proj_bias=proj_bias, ffn_bias=ffn_bias, drop_path=dpr[i], norm_layer=norm_layer, act_layer=act_layer, ffn_layer=ffn_layer, init_values=init_values, ) for i in range(depth) ] if block_chunks > 0: self.chunked_blocks = True chunked_blocks = [] chunksize = depth // block_chunks for i in range(0, depth, chunksize): # this is to keep the block index consistent if we chunk the block list chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize]) self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks]) else: self.chunked_blocks = False self.blocks = nn.ModuleList(blocks_list)
self.norm = norm_layer(embed_dim) self.head = nn.Identity()
self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
self.init_weights()
def init_weights(self): trunc_normal_(self.pos_embed, std=0.02) nn.init.normal_(self.cls_token, std=1e-6) if self.register_tokens is not None: nn.init.normal_(self.register_tokens, std=1e-6) named_apply(init_weights_vit_timm, self)
def interpolate_pos_encoding(self, x, w, h): previous_dtype = x.dtype npatch = x.shape[1] - 1 N = self.pos_embed.shape[1] - 1 if npatch == N and w == h: return self.pos_embed pos_embed = self.pos_embed.float() class_pos_embed = pos_embed[:, 0] patch_pos_embed = pos_embed[:, 1:] dim = x.shape[-1] w0 = w // self.patch_size h0 = h // self.patch_size # we add a small number to avoid floating point error in the interpolation # see discussion at https://github.com/facebookresearch/dino/issues/8 # DINOv2 with register modify the interpolate_offset from 0.1 to 0.0 w0, h0 = w0 + self.interpolate_offset, h0 + self.interpolate_offset # w0, h0 = w0 + 0.1, h0 + 0.1 sqrt_N = math.sqrt(N) sx, sy = float(w0) / sqrt_N, float(h0) / sqrt_N patch_pos_embed = nn.functional.interpolate( patch_pos_embed.reshape(1, int(sqrt_N), int(sqrt_N), dim).permute(0, 3, 1, 2), scale_factor=(sx, sy), # (int(w0), int(h0)), # to solve the upsampling shape issue mode="bicubic", antialias=self.interpolate_antialias ) assert int(w0) == patch_pos_embed.shape[-2] assert int(h0) == patch_pos_embed.shape[-1] patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
def prepare_tokens_with_masks(self, x, masks=None): B, nc, w, h = x.shape x = self.patch_embed(x) if masks is not None: x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) x = x + self.interpolate_pos_encoding(x, w, h)
if self.register_tokens is not None: x = torch.cat( ( x[:, :1], self.register_tokens.expand(x.shape[0], -1, -1), x[:, 1:], ), dim=1, )
return x
def forward_features_list(self, x_list, masks_list): x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)] for blk in self.blocks: x = blk(x)
all_x = x output = [] for x, masks in zip(all_x, masks_list): x_norm = self.norm(x) output.append( { "x_norm_clstoken": x_norm[:, 0], "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], "x_prenorm": x, "masks": masks, } ) return output
def forward_features(self, x, masks=None): if isinstance(x, list): return self.forward_features_list(x, masks)
x = self.prepare_tokens_with_masks(x, masks)
for blk in self.blocks: x = blk(x)
x_norm = self.norm(x) return { "x_norm_clstoken": x_norm[:, 0], "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1], "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :], "x_prenorm": x, "masks": masks, }
def _get_intermediate_layers_not_chunked(self, x, n=1): x = self.prepare_tokens_with_masks(x) # If n is an int, take the n last blocks. If it's a list, take them output, total_block_len = [], len(self.blocks) blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n for i, blk in enumerate(self.blocks): x = blk(x) if i in blocks_to_take: output.append(x) assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" return output
def _get_intermediate_layers_chunked(self, x, n=1): x = self.prepare_tokens_with_masks(x) output, i, total_block_len = [], 0, len(self.blocks[-1]) # If n is an int, take the n last blocks. If it's a list, take them blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n for block_chunk in self.blocks: for blk in block_chunk[i:]: # Passing the nn.Identity() x = blk(x) if i in blocks_to_take: output.append(x) i += 1 assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found" return output
def get_intermediate_layers( self, x: torch.Tensor, n: Union[int, Sequence] = 1, # Layers or n last layers to take reshape: bool = False, return_class_token: bool = False, norm=True ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]: if self.chunked_blocks: outputs = self._get_intermediate_layers_chunked(x, n) else: outputs = self._get_intermediate_layers_not_chunked(x, n) if norm: outputs = [self.norm(out) for out in outputs] class_tokens = [out[:, 0] for out in outputs] outputs = [out[:, 1 + self.num_register_tokens:] for out in outputs] if reshape: B, _, w, h = x.shape outputs = [ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous() for out in outputs ] if return_class_token: return tuple(zip(outputs, class_tokens)) return tuple(outputs)
def forward(self, *args, is_training=False, **kwargs): ret = self.forward_features(*args, **kwargs) if is_training: return ret else: return self.head(ret["x_norm_clstoken"])
def init_weights_vit_timm(module: nn.Module, name: str = ""): """ViT weight initialization, original timm impl (for reproducibility)""" if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias)
def vit_small(patch_size=16, num_register_tokens=0, **kwargs): model = DinoVisionTransformer( patch_size=patch_size, embed_dim=384, depth=12, num_heads=6, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model
def vit_base(patch_size=16, num_register_tokens=0, **kwargs): model = DinoVisionTransformer( patch_size=patch_size, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model
def vit_large(patch_size=16, num_register_tokens=0, **kwargs): model = DinoVisionTransformer( patch_size=patch_size, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model
def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs): """ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 """ model = DinoVisionTransformer( patch_size=patch_size, embed_dim=1536, depth=40, num_heads=24, mlp_ratio=4, block_fn=partial(Block, attn_class=MemEffAttention), num_register_tokens=num_register_tokens, **kwargs, ) return model
def DINOv2(model_name): model_zoo = { "vits": vit_small, "vitb": vit_base, "vitl": vit_large, "vitg": vit_giant2 } return model_zoo[model_name]( img_size=518, patch_size=14, init_values=1.0, ffn_layer="mlp" if model_name != "vitg" else "swiglufused", block_chunks=0, num_register_tokens=0, interpolate_antialias=False, interpolate_offset=0.1 )1234567891011# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
from .mlp import Mlpfrom .patch_embed import PatchEmbedfrom .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFusedfrom .block import NestedTensorBlockfrom .attention import MemEffAttention1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
import logging
from torch import Tensorfrom torch import nn
logger = logging.getLogger("dinov2")
try: from xformers.ops import memory_efficient_attention, unbind, fmha
XFORMERS_AVAILABLE = Trueexcept ImportError: logger.warning("xFormers not available") XFORMERS_AVAILABLE = False
class Attention(nn.Module): def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = False, proj_bias: bool = True, attn_drop: float = 0.0, proj_drop: float = 0.0, ) -> None: super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim**-0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim, bias=proj_bias) self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x: Tensor) -> Tensor: B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] attn = q @ k.transpose(-2, -1)
attn = attn.softmax(dim=-1) attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x
class MemEffAttention(Attention): def forward(self, x: Tensor, attn_bias=None) -> Tensor: if not XFORMERS_AVAILABLE: assert attn_bias is None, "xFormers is required for nested tensors usage" return super().forward(x)
B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
q, k, v = unbind(qkv, 2)
x = memory_efficient_attention(q, k, v, attn_bias=attn_bias) x = x.reshape([B, N, C])
x = self.proj(x) x = self.proj_drop(x) return x
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
import loggingfrom typing import Callable, List, Any, Tuple, Dict
import torchfrom torch import nn, Tensor
from .attention import Attention, MemEffAttentionfrom .drop_path import DropPathfrom .layer_scale import LayerScalefrom .mlp import Mlp
logger = logging.getLogger("dinov2")
try: from xformers.ops import fmha from xformers.ops import scaled_index_add, index_select_cat
XFORMERS_AVAILABLE = Trueexcept ImportError: logger.warning("xFormers not available") XFORMERS_AVAILABLE = False
class Block(nn.Module): def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = False, proj_bias: bool = True, ffn_bias: bool = True, drop: float = 0.0, attn_drop: float = 0.0, init_values=None, drop_path: float = 0.0, act_layer: Callable[..., nn.Module] = nn.GELU, norm_layer: Callable[..., nn.Module] = nn.LayerNorm, attn_class: Callable[..., nn.Module] = Attention, ffn_layer: Callable[..., nn.Module] = Mlp, ) -> None: super().__init__() # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}") self.norm1 = norm_layer(dim) self.attn = attn_class( dim, num_heads=num_heads, qkv_bias=qkv_bias, proj_bias=proj_bias, attn_drop=attn_drop, proj_drop=drop, ) self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = ffn_layer( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop, bias=ffn_bias, ) self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity() self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.sample_drop_ratio = drop_path
def forward(self, x: Tensor) -> Tensor: def attn_residual_func(x: Tensor) -> Tensor: return self.ls1(self.attn(self.norm1(x)))
def ffn_residual_func(x: Tensor) -> Tensor: return self.ls2(self.mlp(self.norm2(x)))
if self.training and self.sample_drop_ratio > 0.1: # the overhead is compensated only for a drop path rate larger than 0.1 x = drop_add_residual_stochastic_depth( x, residual_func=attn_residual_func, sample_drop_ratio=self.sample_drop_ratio, ) x = drop_add_residual_stochastic_depth( x, residual_func=ffn_residual_func, sample_drop_ratio=self.sample_drop_ratio, ) elif self.training and self.sample_drop_ratio > 0.0: x = x + self.drop_path1(attn_residual_func(x)) x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2 else: x = x + attn_residual_func(x) x = x + ffn_residual_func(x) return x
def drop_add_residual_stochastic_depth( x: Tensor, residual_func: Callable[[Tensor], Tensor], sample_drop_ratio: float = 0.0,) -> Tensor: # 1) extract subset using permutation b, n, d = x.shape sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) brange = (torch.randperm(b, device=x.device))[:sample_subset_size] x_subset = x[brange]
# 2) apply residual_func to get residual residual = residual_func(x_subset)
x_flat = x.flatten(1) residual = residual.flatten(1)
residual_scale_factor = b / sample_subset_size
# 3) add the residual x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) return x_plus_residual.view_as(x)
def get_branges_scales(x, sample_drop_ratio=0.0): b, n, d = x.shape sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1) brange = (torch.randperm(b, device=x.device))[:sample_subset_size] residual_scale_factor = b / sample_subset_size return brange, residual_scale_factor
def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None): if scaling_vector is None: x_flat = x.flatten(1) residual = residual.flatten(1) x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor) else: x_plus_residual = scaled_index_add( x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor ) return x_plus_residual
attn_bias_cache: Dict[Tuple, Any] = {}
def get_attn_bias_and_cat(x_list, branges=None): """ this will perform the index select, cat the tensors, and provide the attn_bias from cache """ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list)) if all_shapes not in attn_bias_cache.keys(): seqlens = [] for b, x in zip(batch_sizes, x_list): for _ in range(b): seqlens.append(x.shape[1]) attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens) attn_bias._batch_sizes = batch_sizes attn_bias_cache[all_shapes] = attn_bias
if branges is not None: cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1]) else: tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list) cat_tensors = torch.cat(tensors_bs1, dim=1)
return attn_bias_cache[all_shapes], cat_tensors
def drop_add_residual_stochastic_depth_list( x_list: List[Tensor], residual_func: Callable[[Tensor, Any], Tensor], sample_drop_ratio: float = 0.0, scaling_vector=None,) -> Tensor: # 1) generate random set of indices for dropping samples in the batch branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list] branges = [s[0] for s in branges_scales] residual_scale_factors = [s[1] for s in branges_scales]
# 2) get attention bias and index+concat the tensors attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
# 3) apply residual_func to get residual, and split the result residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
outputs = [] for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors): outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x)) return outputs
class NestedTensorBlock(Block): def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: """ x_list contains a list of tensors to nest together and run """ assert isinstance(self.attn, MemEffAttention)
if self.training and self.sample_drop_ratio > 0.0:
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.attn(self.norm1(x), attn_bias=attn_bias)
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.mlp(self.norm2(x))
x_list = drop_add_residual_stochastic_depth_list( x_list, residual_func=attn_residual_func, sample_drop_ratio=self.sample_drop_ratio, scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None, ) x_list = drop_add_residual_stochastic_depth_list( x_list, residual_func=ffn_residual_func, sample_drop_ratio=self.sample_drop_ratio, scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None, ) return x_list else:
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor: return self.ls2(self.mlp(self.norm2(x)))
attn_bias, x = get_attn_bias_and_cat(x_list) x = x + attn_residual_func(x, attn_bias=attn_bias) x = x + ffn_residual_func(x) return attn_bias.split(x)
def forward(self, x_or_x_list): if isinstance(x_or_x_list, Tensor): return super().forward(x_or_x_list) elif isinstance(x_or_x_list, list): assert XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage" return self.forward_nested(x_or_x_list) else: raise AssertionError1234567891011121314151617181920212223242526272829303132333435# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
from torch import nn
def drop_path(x, drop_prob: float = 0.0, training: bool = False): if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = x.new_empty(shape).bernoulli_(keep_prob) if keep_prob > 0.0: random_tensor.div_(keep_prob) output = x * random_tensor return output
class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob
def forward(self, x): return drop_path(x, self.drop_prob, self.training)12345678910111213141516171819202122232425262728# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
from typing import Union
import torchfrom torch import Tensorfrom torch import nn
class LayerScale(nn.Module): def __init__( self, dim: int, init_values: Union[float, Tensor] = 1e-5, inplace: bool = False, ) -> None: super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self, x: Tensor) -> Tensor: return x.mul_(self.gamma) if self.inplace else x * self.gamma1234567891011121314151617181920212223242526272829303132333435363738394041# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
from typing import Callable, Optional
from torch import Tensor, nn
class Mlp(nn.Module): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = nn.GELU, drop: float = 0.0, bias: bool = True, ) -> None: super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features, bias=bias) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features, bias=bias) self.drop = nn.Dropout(drop)
def forward(self, x: Tensor) -> Tensor: x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
# References:# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
from typing import Callable, Optional, Tuple, Union
from torch import Tensorimport torch.nn as nn
def make_2tuple(x): if isinstance(x, tuple): assert len(x) == 2 return x
assert isinstance(x, int) return (x, x)
class PatchEmbed(nn.Module): """ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
Args: img_size: Image size. patch_size: Patch token size. in_chans: Number of input image channels. embed_dim: Number of linear projection output channels. norm_layer: Normalization layer. """
def __init__( self, img_size: Union[int, Tuple[int, int]] = 224, patch_size: Union[int, Tuple[int, int]] = 16, in_chans: int = 3, embed_dim: int = 768, norm_layer: Optional[Callable] = None, flatten_embedding: bool = True, ) -> None: super().__init__()
image_HW = make_2tuple(img_size) patch_HW = make_2tuple(patch_size) patch_grid_size = ( image_HW[0] // patch_HW[0], image_HW[1] // patch_HW[1], )
self.img_size = image_HW self.patch_size = patch_HW self.patches_resolution = patch_grid_size self.num_patches = patch_grid_size[0] * patch_grid_size[1]
self.in_chans = in_chans self.embed_dim = embed_dim
self.flatten_embedding = flatten_embedding
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW) self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x: Tensor) -> Tensor: _, _, H, W = x.shape patch_H, patch_W = self.patch_size
assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}" assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
x = self.proj(x) # B C H W H, W = x.size(2), x.size(3) x = x.flatten(2).transpose(1, 2) # B HW C x = self.norm(x) if not self.flatten_embedding: x = x.reshape(-1, H, W, self.embed_dim) # B H W C return x
def flops(self) -> float: Ho, Wo = self.patches_resolution flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1]) if self.norm is not None: flops += Ho * Wo * self.embed_dim return flops123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
from typing import Callable, Optional
from torch import Tensor, nnimport torch.nn.functional as F
class SwiGLUFFN(nn.Module): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = None, drop: float = 0.0, bias: bool = True, ) -> None: super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
def forward(self, x: Tensor) -> Tensor: x12 = self.w12(x) x1, x2 = x12.chunk(2, dim=-1) hidden = F.silu(x1) * x2 return self.w3(hidden)
try: from xformers.ops import SwiGLU
XFORMERS_AVAILABLE = Trueexcept ImportError: SwiGLU = SwiGLUFFN XFORMERS_AVAILABLE = False
class SwiGLUFFNFused(SwiGLU): def __init__( self, in_features: int, hidden_features: Optional[int] = None, out_features: Optional[int] = None, act_layer: Callable[..., nn.Module] = None, drop: float = 0.0, bias: bool = True, ) -> None: out_features = out_features or in_features hidden_features = hidden_features or in_features hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8 super().__init__( in_features=in_features, hidden_features=hidden_features, out_features=out_features, bias=bias, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160# Copyright (2025) Bytedance Ltd. and/or its affiliates
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torchimport torch.nn as nnimport torch.nn.functional as F
from .util.blocks import FeatureFusionBlock, _make_scratch
def _make_fusion_block(features, use_bn, size=None): return FeatureFusionBlock( features, nn.ReLU(False), deconv=False, bn=use_bn, expand=False, align_corners=True, size=size, )
class ConvBlock(nn.Module): def __init__(self, in_feature, out_feature): super().__init__() self.conv_block = nn.Sequential( nn.Conv2d(in_feature, out_feature, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(out_feature), nn.ReLU(True) ) def forward(self, x): return self.conv_block(x)
class DPTHead(nn.Module): def __init__( self, in_channels, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False ): super(DPTHead, self).__init__() self.use_clstoken = use_clstoken self.projects = nn.ModuleList([ nn.Conv2d( in_channels=in_channels, out_channels=out_channel, kernel_size=1, stride=1, padding=0, ) for out_channel in out_channels ]) self.resize_layers = nn.ModuleList([ nn.ConvTranspose2d( in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0), nn.ConvTranspose2d( in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0), nn.Identity(), nn.Conv2d( in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1) ]) if use_clstoken: self.readout_projects = nn.ModuleList() for _ in range(len(self.projects)): self.readout_projects.append( nn.Sequential( nn.Linear(2 * in_channels, in_channels), nn.GELU())) self.scratch = _make_scratch( out_channels, features, groups=1, expand=False, ) self.scratch.stem_transpose = None self.scratch.refinenet1 = _make_fusion_block(features, use_bn) self.scratch.refinenet2 = _make_fusion_block(features, use_bn) self.scratch.refinenet3 = _make_fusion_block(features, use_bn) self.scratch.refinenet4 = _make_fusion_block(features, use_bn) head_features_1 = features head_features_2 = 32 self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1) self.scratch.output_conv2 = nn.Sequential( nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1), nn.ReLU(True), nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0), nn.ReLU(True), nn.Identity(), ) def forward(self, out_features, patch_h, patch_w): out = [] for i, x in enumerate(out_features): if self.use_clstoken: x, cls_token = x[0], x[1] readout = cls_token.unsqueeze(1).expand_as(x) x = self.readout_projects[i](torch.cat((x, readout), -1)) else: x = x[0] x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)) x = self.projects[i](x) x = self.resize_layers[i](x) out.append(x) layer_1, layer_2, layer_3, layer_4 = out layer_1_rn = self.scratch.layer1_rn(layer_1) layer_2_rn = self.scratch.layer2_rn(layer_2) layer_3_rn = self.scratch.layer3_rn(layer_3) layer_4_rn = self.scratch.layer4_rn(layer_4) path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:]) path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:]) path_1 = self.scratch.refinenet1(path_2, layer_1_rn) out = self.scratch.output_conv1(path_1) out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True) out = self.scratch.output_conv2(out) return out 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596# Copyright (2025) Bytedance Ltd. and/or its affiliates
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torchimport torch.nn.functional as Fimport torch.nn as nnfrom .dpt import DPTHeadfrom .motion_module.motion_module import TemporalModulefrom easydict import EasyDict
class DPTHeadTemporal(DPTHead): def __init__(self, in_channels, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False, num_frames=32, pe='ape' ): super().__init__(in_channels, features, use_bn, out_channels, use_clstoken)
assert num_frames > 0 motion_module_kwargs = EasyDict(num_attention_heads = 8, num_transformer_block = 1, num_attention_blocks = 2, temporal_max_len = num_frames, zero_initialize = True, pos_embedding_type = pe)
self.motion_modules = nn.ModuleList([ TemporalModule(in_channels=out_channels[2], **motion_module_kwargs), TemporalModule(in_channels=out_channels[3], **motion_module_kwargs), TemporalModule(in_channels=features, **motion_module_kwargs), TemporalModule(in_channels=features, **motion_module_kwargs) ])
def forward(self, out_features, patch_h, patch_w, frame_length): out = [] for i, x in enumerate(out_features): if self.use_clstoken: x, cls_token = x[0], x[1] readout = cls_token.unsqueeze(1).expand_as(x) x = self.readout_projects[i](torch.cat((x, readout), -1)) else: x = x[0]
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)).contiguous()
B, T = x.shape[0] // frame_length, frame_length x = self.projects[i](x) x = self.resize_layers[i](x)
out.append(x)
layer_1, layer_2, layer_3, layer_4 = out
B, T = layer_1.shape[0] // frame_length, frame_length
layer_3 = self.motion_modules[0](layer_3.unflatten(0, (B, T)).permute(0, 2, 1, 3, 4), None, None).permute(0, 2, 1, 3, 4).flatten(0, 1) layer_4 = self.motion_modules[1](layer_4.unflatten(0, (B, T)).permute(0, 2, 1, 3, 4), None, None).permute(0, 2, 1, 3, 4).flatten(0, 1)
layer_1_rn = self.scratch.layer1_rn(layer_1) layer_2_rn = self.scratch.layer2_rn(layer_2) layer_3_rn = self.scratch.layer3_rn(layer_3) layer_4_rn = self.scratch.layer4_rn(layer_4)
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) path_4 = self.motion_modules[2](path_4.unflatten(0, (B, T)).permute(0, 2, 1, 3, 4), None, None).permute(0, 2, 1, 3, 4).flatten(0, 1) path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:]) path_3 = self.motion_modules[3](path_3.unflatten(0, (B, T)).permute(0, 2, 1, 3, 4), None, None).permute(0, 2, 1, 3, 4).flatten(0, 1) path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:]) path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
out = self.scratch.output_conv1(path_1) out = F.interpolate( out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True ) out = self.scratch.output_conv2(out)
return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423# Copyright 2022 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.from typing import Optional, Tuple
import torchimport torch.nn.functional as Ffrom torch import nn
import xformersimport xformers.ops
class CrossAttention(nn.Module): r""" A cross attention layer.
Parameters: query_dim (`int`): The number of channels in the query. cross_attention_dim (`int`, *optional*): The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`. heads (`int`, *optional*, defaults to 8): The number of heads to use for multi-head attention. dim_head (`int`, *optional*, defaults to 64): The number of channels in each head. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. bias (`bool`, *optional*, defaults to False): Set to `True` for the query, key, and value linear layers to contain a bias parameter. """
def __init__( self, query_dim: int, cross_attention_dim: Optional[int] = None, heads: int = 8, dim_head: int = 64, dropout: float = 0.0, bias=False, upcast_attention: bool = False, upcast_softmax: bool = False, added_kv_proj_dim: Optional[int] = None, norm_num_groups: Optional[int] = None, ): super().__init__() inner_dim = dim_head * heads cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim self.upcast_attention = upcast_attention self.upcast_softmax = upcast_softmax self.upcast_efficient_attention = False
self.scale = dim_head**-0.5
self.heads = heads # for slice_size > 0 the attention score computation # is split across the batch axis to save memory # You can set slice_size with `set_attention_slice` self.sliceable_head_dim = heads self._slice_size = None self._use_memory_efficient_attention_xformers = False self.added_kv_proj_dim = added_kv_proj_dim
if norm_num_groups is not None: self.group_norm = nn.GroupNorm(num_channels=inner_dim, num_groups=norm_num_groups, eps=1e-5, affine=True) else: self.group_norm = None
self.to_q = nn.Linear(query_dim, inner_dim, bias=bias) self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=bias) self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=bias)
if self.added_kv_proj_dim is not None: self.add_k_proj = nn.Linear(added_kv_proj_dim, cross_attention_dim) self.add_v_proj = nn.Linear(added_kv_proj_dim, cross_attention_dim)
self.to_out = nn.ModuleList([]) self.to_out.append(nn.Linear(inner_dim, query_dim)) self.to_out.append(nn.Dropout(dropout))
def reshape_heads_to_batch_dim(self, tensor): batch_size, seq_len, dim = tensor.shape head_size = self.heads tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size).contiguous() tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size * head_size, seq_len, dim // head_size).contiguous() return tensor
def reshape_heads_to_4d(self, tensor): batch_size, seq_len, dim = tensor.shape head_size = self.heads tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size).contiguous() return tensor
def reshape_batch_dim_to_heads(self, tensor): batch_size, seq_len, dim = tensor.shape head_size = self.heads tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim).contiguous() tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size).contiguous() return tensor
def reshape_4d_to_heads(self, tensor): batch_size, seq_len, head_size, dim = tensor.shape head_size = self.heads tensor = tensor.reshape(batch_size, seq_len, dim * head_size).contiguous() return tensor
def set_attention_slice(self, slice_size): if slice_size is not None and slice_size > self.sliceable_head_dim: raise ValueError(f"slice_size {slice_size} has to be smaller or equal to {self.sliceable_head_dim}.")
self._slice_size = slice_size
def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None): batch_size, sequence_length, _ = hidden_states.shape
encoder_hidden_states = encoder_hidden_states
if self.group_norm is not None: hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = self.to_q(hidden_states) dim = query.shape[-1] query = self.reshape_heads_to_batch_dim(query)
if self.added_kv_proj_dim is not None: key = self.to_k(hidden_states) value = self.to_v(hidden_states) encoder_hidden_states_key_proj = self.add_k_proj(encoder_hidden_states) encoder_hidden_states_value_proj = self.add_v_proj(encoder_hidden_states)
key = self.reshape_heads_to_batch_dim(key) value = self.reshape_heads_to_batch_dim(value) encoder_hidden_states_key_proj = self.reshape_heads_to_batch_dim(encoder_hidden_states_key_proj) encoder_hidden_states_value_proj = self.reshape_heads_to_batch_dim(encoder_hidden_states_value_proj)
key = torch.concat([encoder_hidden_states_key_proj, key], dim=1) value = torch.concat([encoder_hidden_states_value_proj, value], dim=1) else: encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states key = self.to_k(encoder_hidden_states) value = self.to_v(encoder_hidden_states)
key = self.reshape_heads_to_batch_dim(key) value = self.reshape_heads_to_batch_dim(value)
if attention_mask is not None: if attention_mask.shape[-1] != query.shape[1]: target_length = query.shape[1] attention_mask = F.pad(attention_mask, (0, target_length), value=0.0) attention_mask = attention_mask.repeat_interleave(self.heads, dim=0)
# attention, what we cannot get enough of if self._use_memory_efficient_attention_xformers: hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask) # Some versions of xformers return output in fp32, cast it back to the dtype of the input hidden_states = hidden_states.to(query.dtype) else: if self._slice_size is None or query.shape[0] // self._slice_size == 1: hidden_states = self._attention(query, key, value, attention_mask) else: hidden_states = self._sliced_attention(query, key, value, sequence_length, dim, attention_mask)
# linear proj hidden_states = self.to_out[0](hidden_states)
# dropout hidden_states = self.to_out[1](hidden_states) return hidden_states
def _attention(self, query, key, value, attention_mask=None): if self.upcast_attention: query = query.float() key = key.float()
attention_scores = torch.baddbmm( torch.empty(query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device), query, key.transpose(-1, -2), beta=0, alpha=self.scale, )
if attention_mask is not None: attention_scores = attention_scores + attention_mask
if self.upcast_softmax: attention_scores = attention_scores.float()
attention_probs = attention_scores.softmax(dim=-1)
# cast back to the original dtype attention_probs = attention_probs.to(value.dtype)
# compute attention output hidden_states = torch.bmm(attention_probs, value)
# reshape hidden_states hidden_states = self.reshape_batch_dim_to_heads(hidden_states) return hidden_states
def _sliced_attention(self, query, key, value, sequence_length, dim, attention_mask): batch_size_attention = query.shape[0] hidden_states = torch.zeros( (batch_size_attention, sequence_length, dim // self.heads), device=query.device, dtype=query.dtype ) slice_size = self._slice_size if self._slice_size is not None else hidden_states.shape[0] for i in range(hidden_states.shape[0] // slice_size): start_idx = i * slice_size end_idx = (i + 1) * slice_size
query_slice = query[start_idx:end_idx] key_slice = key[start_idx:end_idx]
if self.upcast_attention: query_slice = query_slice.float() key_slice = key_slice.float()
attn_slice = torch.baddbmm( torch.empty(slice_size, query.shape[1], key.shape[1], dtype=query_slice.dtype, device=query.device), query_slice, key_slice.transpose(-1, -2), beta=0, alpha=self.scale, )
if attention_mask is not None: attn_slice = attn_slice + attention_mask[start_idx:end_idx]
if self.upcast_softmax: attn_slice = attn_slice.float()
attn_slice = attn_slice.softmax(dim=-1)
# cast back to the original dtype attn_slice = attn_slice.to(value.dtype) attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx])
hidden_states[start_idx:end_idx] = attn_slice
# reshape hidden_states hidden_states = self.reshape_batch_dim_to_heads(hidden_states) return hidden_states
def _memory_efficient_attention_xformers(self, query, key, value, attention_mask): if self.upcast_efficient_attention: org_dtype = query.dtype query = query.float() key = key.float() value = value.float() if attention_mask is not None: attention_mask = attention_mask.float() hidden_states = self._memory_efficient_attention_split(query, key, value, attention_mask) if self.upcast_efficient_attention: hidden_states = hidden_states.to(org_dtype) hidden_states = self.reshape_4d_to_heads(hidden_states) return hidden_states
# print("Errror: no xformers") # raise NotImplementedError
def _memory_efficient_attention_split(self, query, key, value, attention_mask): batch_size = query.shape[0] max_batch_size = 65535 num_batches = (batch_size + max_batch_size - 1) // max_batch_size results = [] for i in range(num_batches): start_idx = i * max_batch_size end_idx = min((i + 1) * max_batch_size, batch_size) query_batch = query[start_idx:end_idx] key_batch = key[start_idx:end_idx] value_batch = value[start_idx:end_idx] if attention_mask is not None: attention_mask_batch = attention_mask[start_idx:end_idx] else: attention_mask_batch = None result = xformers.ops.memory_efficient_attention(query_batch, key_batch, value_batch, attn_bias=attention_mask_batch) results.append(result) full_result = torch.cat(results, dim=0) return full_result
class FeedForward(nn.Module): r""" A feed-forward layer.
Parameters: dim (`int`): The number of channels in the input. dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`. mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. """
def __init__( self, dim: int, dim_out: Optional[int] = None, mult: int = 4, dropout: float = 0.0, activation_fn: str = "geglu", ): super().__init__() inner_dim = int(dim * mult) dim_out = dim_out if dim_out is not None else dim
if activation_fn == "gelu": act_fn = GELU(dim, inner_dim) elif activation_fn == "geglu": act_fn = GEGLU(dim, inner_dim) elif activation_fn == "geglu-approximate": act_fn = ApproximateGELU(dim, inner_dim)
self.net = nn.ModuleList([]) # project in self.net.append(act_fn) # project dropout self.net.append(nn.Dropout(dropout)) # project out self.net.append(nn.Linear(inner_dim, dim_out))
def forward(self, hidden_states): for module in self.net: hidden_states = module(hidden_states) return hidden_states
class GELU(nn.Module): r""" GELU activation function """
def __init__(self, dim_in: int, dim_out: int): super().__init__() self.proj = nn.Linear(dim_in, dim_out)
def gelu(self, gate): if gate.device.type != "mps": return F.gelu(gate) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
def forward(self, hidden_states): hidden_states = self.proj(hidden_states) hidden_states = self.gelu(hidden_states) return hidden_states
# feedforwardclass GEGLU(nn.Module): r""" A variant of the gated linear unit activation function from https://arxiv.org/abs/2002.05202.
Parameters: dim_in (`int`): The number of channels in the input. dim_out (`int`): The number of channels in the output. """
def __init__(self, dim_in: int, dim_out: int): super().__init__() self.proj = nn.Linear(dim_in, dim_out * 2)
def gelu(self, gate): if gate.device.type != "mps": return F.gelu(gate) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
def forward(self, hidden_states): hidden_states, gate = self.proj(hidden_states).chunk(2, dim=-1) return hidden_states * self.gelu(gate)
class ApproximateGELU(nn.Module): """ The approximate form of Gaussian Error Linear Unit (GELU)
For more details, see section 2: https://arxiv.org/abs/1606.08415 """
def __init__(self, dim_in: int, dim_out: int): super().__init__() self.proj = nn.Linear(dim_in, dim_out)
def forward(self, x): x = self.proj(x) return x * torch.sigmoid(1.702 * x)
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0): freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) t = torch.arange(end, device=freqs.device, dtype=torch.float32) freqs = torch.outer(t, freqs) freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 return freqs_cis
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor): ndim = x.ndim assert 0 <= 1 < ndim assert freqs_cis.shape == (x.shape[1], x.shape[-1]) shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)] return freqs_cis.view(*shape)
def apply_rotary_emb( xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor,) -> Tuple[torch.Tensor, torch.Tensor]: xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2).contiguous()) xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2).contiguous()) freqs_cis = reshape_for_broadcast(freqs_cis, xq_) xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(2) xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(2) return xq_out.type_as(xq), xk_out.type_as(xk)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288# This file is originally from AnimateDiff/animatediff/models/motion_module.py at main · guoyww/AnimateDiff# SPDX-License-Identifier: Apache-2.0 license## This file may have been modified by ByteDance Ltd. and/or its affiliates on [date of modification]# Original file was released under [ Apache-2.0 license], with the full license text available at [https://github.com/guoyww/AnimateDiff?tab=Apache-2.0-1-ov-file#readme].import torchimport torch.nn.functional as Ffrom torch import nn
from .attention import CrossAttention, FeedForward, apply_rotary_emb, precompute_freqs_cis
from einops import rearrange, repeatimport math
def zero_module(module): # Zero out the parameters of a module and return it. for p in module.parameters(): p.detach().zero_() return module
class TemporalModule(nn.Module): def __init__( self, in_channels, num_attention_heads = 8, num_transformer_block = 2, num_attention_blocks = 2, norm_num_groups = 32, temporal_max_len = 32, zero_initialize = True, pos_embedding_type = "ape", ): super().__init__() self.temporal_transformer = TemporalTransformer3DModel( in_channels=in_channels, num_attention_heads=num_attention_heads, attention_head_dim=in_channels // num_attention_heads, num_layers=num_transformer_block, num_attention_blocks=num_attention_blocks, norm_num_groups=norm_num_groups, temporal_max_len=temporal_max_len, pos_embedding_type=pos_embedding_type, ) if zero_initialize: self.temporal_transformer.proj_out = zero_module(self.temporal_transformer.proj_out)
def forward(self, input_tensor, encoder_hidden_states, attention_mask=None): hidden_states = input_tensor hidden_states = self.temporal_transformer(hidden_states, encoder_hidden_states, attention_mask)
output = hidden_states return output
class TemporalTransformer3DModel(nn.Module): def __init__( self, in_channels, num_attention_heads, attention_head_dim, num_layers, num_attention_blocks = 2, norm_num_groups = 32, temporal_max_len = 32, pos_embedding_type = "ape", ): super().__init__()
inner_dim = num_attention_heads * attention_head_dim
self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True) self.proj_in = nn.Linear(in_channels, inner_dim)
self.transformer_blocks = nn.ModuleList( [ TemporalTransformerBlock( dim=inner_dim, num_attention_heads=num_attention_heads, attention_head_dim=attention_head_dim, num_attention_blocks=num_attention_blocks, temporal_max_len=temporal_max_len, pos_embedding_type=pos_embedding_type, ) for d in range(num_layers) ] ) self.proj_out = nn.Linear(inner_dim, in_channels) def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None): assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}." video_length = hidden_states.shape[2] hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
batch, channel, height, width = hidden_states.shape residual = hidden_states
hidden_states = self.norm(hidden_states) inner_dim = hidden_states.shape[1] hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim).contiguous() hidden_states = self.proj_in(hidden_states)
# Transformer Blocks for block in self.transformer_blocks: hidden_states = block(hidden_states, encoder_hidden_states=encoder_hidden_states, video_length=video_length, attention_mask=attention_mask) # output hidden_states = self.proj_out(hidden_states) hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
output = hidden_states + residual output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length) return output
class TemporalTransformerBlock(nn.Module): def __init__( self, dim, num_attention_heads, attention_head_dim, num_attention_blocks = 2, temporal_max_len = 32, pos_embedding_type = "ape", ): super().__init__()
self.attention_blocks = nn.ModuleList( [ TemporalAttention( query_dim=dim, heads=num_attention_heads, dim_head=attention_head_dim, temporal_max_len=temporal_max_len, pos_embedding_type=pos_embedding_type, ) for i in range(num_attention_blocks) ] ) self.norms = nn.ModuleList( [ nn.LayerNorm(dim) for i in range(num_attention_blocks) ] )
self.ff = FeedForward(dim, dropout=0.0, activation_fn="geglu") self.ff_norm = nn.LayerNorm(dim)
def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None): for attention_block, norm in zip(self.attention_blocks, self.norms): norm_hidden_states = norm(hidden_states) hidden_states = attention_block( norm_hidden_states, encoder_hidden_states=encoder_hidden_states, video_length=video_length, attention_mask=attention_mask, ) + hidden_states hidden_states = self.ff(self.ff_norm(hidden_states)) + hidden_states output = hidden_states return output
class PositionalEncoding(nn.Module): def __init__( self, d_model, dropout = 0., max_len = 32 ): super().__init__() self.dropout = nn.Dropout(p=dropout) position = torch.arange(max_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)) pe = torch.zeros(1, max_len, d_model) pe[0, :, 0::2] = torch.sin(position * div_term) pe[0, :, 1::2] = torch.cos(position * div_term) self.register_buffer('pe', pe)
def forward(self, x): x = x + self.pe[:, :x.size(1)].to(x.dtype) return self.dropout(x)
class TemporalAttention(CrossAttention): def __init__( self, temporal_max_len = 32, pos_embedding_type = "ape", *args, **kwargs ): super().__init__(*args, **kwargs)
self.pos_embedding_type = pos_embedding_type self._use_memory_efficient_attention_xformers = True
self.pos_encoder = None self.freqs_cis = None if self.pos_embedding_type == "ape": self.pos_encoder = PositionalEncoding( kwargs["query_dim"], dropout=0., max_len=temporal_max_len )
elif self.pos_embedding_type == "rope": self.freqs_cis = precompute_freqs_cis( kwargs["query_dim"], temporal_max_len ) else: raise NotImplementedError
def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None): d = hidden_states.shape[1] hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=video_length) if self.pos_encoder is not None: hidden_states = self.pos_encoder(hidden_states) encoder_hidden_states = repeat(encoder_hidden_states, "b n c -> (b d) n c", d=d) if encoder_hidden_states is not None else encoder_hidden_states
if self.group_norm is not None: hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = self.to_q(hidden_states) dim = query.shape[-1]
if self.added_kv_proj_dim is not None: raise NotImplementedError
encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states key = self.to_k(encoder_hidden_states) value = self.to_v(encoder_hidden_states)
if self.freqs_cis is not None: seq_len = query.shape[1] freqs_cis = self.freqs_cis[:seq_len].to(query.device) query, key = apply_rotary_emb(query, key, freqs_cis)
if attention_mask is not None: if attention_mask.shape[-1] != query.shape[1]: target_length = query.shape[1] attention_mask = F.pad(attention_mask, (0, target_length), value=0.0) attention_mask = attention_mask.repeat_interleave(self.heads, dim=0)
use_memory_efficient = self._use_memory_efficient_attention_xformers if use_memory_efficient and (dim // self.heads) % 8 != 0: # print('Warning: the dim {} cannot be divided by 8. Fall into normal attention'.format(dim // self.heads)) use_memory_efficient = False
# attention, what we cannot get enough of if use_memory_efficient: query = self.reshape_heads_to_4d(query) key = self.reshape_heads_to_4d(key) value = self.reshape_heads_to_4d(value)
hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask) # Some versions of xformers return output in fp32, cast it back to the dtype of the input hidden_states = hidden_states.to(query.dtype) else: query = self.reshape_heads_to_batch_dim(query) key = self.reshape_heads_to_batch_dim(key) value = self.reshape_heads_to_batch_dim(value)
if self._slice_size is None or query.shape[0] // self._slice_size == 1: hidden_states = self._attention(query, key, value, attention_mask) else: raise NotImplementedError # hidden_states = self._sliced_attention(query, key, value, sequence_length, dim, attention_mask)
# linear proj hidden_states = self.to_out[0](hidden_states)
# dropout hidden_states = self.to_out[1](hidden_states)
hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
return hidden_states123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False): scratch = nn.Module()
out_shape1 = out_shape out_shape2 = out_shape out_shape3 = out_shape if len(in_shape) >= 4: out_shape4 = out_shape
if expand: out_shape1 = out_shape out_shape2 = out_shape * 2 out_shape3 = out_shape * 4 if len(in_shape) >= 4: out_shape4 = out_shape * 8
scratch.layer1_rn = nn.Conv2d( in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer2_rn = nn.Conv2d( in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer3_rn = nn.Conv2d( in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) if len(in_shape) >= 4: scratch.layer4_rn = nn.Conv2d( in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups )
return scratch
class ResidualConvUnit(nn.Module): """Residual convolution module."""
def __init__(self, features, activation, bn): """Init.
Args: features (int): number of features """ super().__init__()
self.bn = bn
self.groups = 1
self.conv1 = nn.Conv2d( features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups )
self.conv2 = nn.Conv2d( features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups )
if self.bn is True: self.bn1 = nn.BatchNorm2d(features) self.bn2 = nn.BatchNorm2d(features)
self.activation = activation
self.skip_add = nn.quantized.FloatFunctional()
def forward(self, x): """Forward pass.
Args: x (tensor): input
Returns: tensor: output """
out = self.activation(x) out = self.conv1(out) if self.bn is True: out = self.bn1(out)
out = self.activation(out) out = self.conv2(out) if self.bn is True: out = self.bn2(out)
if self.groups > 1: out = self.conv_merge(out)
return self.skip_add.add(out, x)
class FeatureFusionBlock(nn.Module): """Feature fusion block."""
def __init__( self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None, ): """Init.
Args: features (int): number of features """ super().__init__()
self.deconv = deconv self.align_corners = align_corners
self.groups = 1
self.expand = expand out_features = features if self.expand is True: out_features = features // 2
self.out_conv = nn.Conv2d( features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1 )
self.resConfUnit1 = ResidualConvUnit(features, activation, bn) self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
self.skip_add = nn.quantized.FloatFunctional()
self.size = size
def forward(self, *xs, size=None): """Forward pass.
Returns: tensor: output """ output = xs[0]
if len(xs) == 2: res = self.resConfUnit1(xs[1]) output = self.skip_add.add(output, res)
output = self.resConfUnit2(output)
if (size is None) and (self.size is None): modifier = {"scale_factor": 2} elif size is None: modifier = {"size": self.size} else: modifier = {"size": size}
output = nn.functional.interpolate( output.contiguous(), **modifier, mode="bilinear", align_corners=self.align_corners )
output = self.out_conv(output)
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158import numpy as npimport cv2
class Resize(object): """Resize sample to given size (width, height). """
def __init__( self, width, height, resize_target=True, keep_aspect_ratio=False, ensure_multiple_of=1, resize_method="lower_bound", image_interpolation_method=cv2.INTER_AREA, ): """Init.
Args: width (int): desired output width height (int): desired output height resize_target (bool, optional): True: Resize the full sample (image, mask, target). False: Resize image only. Defaults to True. keep_aspect_ratio (bool, optional): True: Keep the aspect ratio of the input sample. Output sample might not have the given width and height, and resize behaviour depends on the parameter 'resize_method'. Defaults to False. ensure_multiple_of (int, optional): Output width and height is constrained to be multiple of this parameter. Defaults to 1. resize_method (str, optional): "lower_bound": Output will be at least as large as the given size. "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.) "minimal": Scale as least as possible. (Output size might be smaller than given size.) Defaults to "lower_bound". """ self.__width = width self.__height = height
self.__resize_target = resize_target self.__keep_aspect_ratio = keep_aspect_ratio self.__multiple_of = ensure_multiple_of self.__resize_method = resize_method self.__image_interpolation_method = image_interpolation_method
def constrain_to_multiple_of(self, x, min_val=0, max_val=None): y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
if max_val is not None and y > max_val: y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
if y < min_val: y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
return y
def get_size(self, width, height): # determine new height and width scale_height = self.__height / height scale_width = self.__width / width
if self.__keep_aspect_ratio: if self.__resize_method == "lower_bound": # scale such that output size is lower bound if scale_width > scale_height: # fit width scale_height = scale_width else: # fit height scale_width = scale_height elif self.__resize_method == "upper_bound": # scale such that output size is upper bound if scale_width < scale_height: # fit width scale_height = scale_width else: # fit height scale_width = scale_height elif self.__resize_method == "minimal": # scale as least as possbile if abs(1 - scale_width) < abs(1 - scale_height): # fit width scale_height = scale_width else: # fit height scale_width = scale_height else: raise ValueError(f"resize_method {self.__resize_method} not implemented")
if self.__resize_method == "lower_bound": new_height = self.constrain_to_multiple_of(scale_height * height, min_val=self.__height) new_width = self.constrain_to_multiple_of(scale_width * width, min_val=self.__width) elif self.__resize_method == "upper_bound": new_height = self.constrain_to_multiple_of(scale_height * height, max_val=self.__height) new_width = self.constrain_to_multiple_of(scale_width * width, max_val=self.__width) elif self.__resize_method == "minimal": new_height = self.constrain_to_multiple_of(scale_height * height) new_width = self.constrain_to_multiple_of(scale_width * width) else: raise ValueError(f"resize_method {self.__resize_method} not implemented")
return (new_width, new_height)
def __call__(self, sample): width, height = self.get_size(sample["image"].shape[1], sample["image"].shape[0]) # resize sample sample["image"] = cv2.resize(sample["image"], (width, height), interpolation=self.__image_interpolation_method)
if self.__resize_target: if "depth" in sample: sample["depth"] = cv2.resize(sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST) if "mask" in sample: sample["mask"] = cv2.resize(sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST) return sample
class NormalizeImage(object): """Normlize image by given mean and std. """
def __init__(self, mean, std): self.__mean = mean self.__std = std
def __call__(self, sample): sample["image"] = (sample["image"] - self.__mean) / self.__std
return sample
class PrepareForNet(object): """Prepare sample for usage as network input. """
def __init__(self): pass
def __call__(self, sample): image = np.transpose(sample["image"], (2, 0, 1)) sample["image"] = np.ascontiguousarray(image).astype(np.float32)
if "depth" in sample: depth = sample["depth"].astype(np.float32) sample["depth"] = np.ascontiguousarray(depth) if "mask" in sample: sample["mask"] = sample["mask"].astype(np.float32) sample["mask"] = np.ascontiguousarray(sample["mask"]) return sample123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149# Copyright (2025) Bytedance Ltd. and/or its affiliates
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torchimport torch.nn.functional as Fimport torch.nn as nnfrom torchvision.transforms import Composeimport cv2from tqdm import tqdmimport numpy as npimport gc
from .dinov2 import DINOv2from .dpt_temporal import DPTHeadTemporalfrom .util.transform import Resize, NormalizeImage, PrepareForNet
from utils.util import compute_scale_and_shift, get_interpolate_frames
# infer settings, do not changeINFER_LEN = 32OVERLAP = 10KEYFRAMES = [0,12,24,25,26,27,28,29,30,31]INTERP_LEN = 8
class VideoDepthAnything(nn.Module): def __init__( self, encoder='vitl', features=256, out_channels=[256, 512, 1024, 1024], use_bn=False, use_clstoken=False, num_frames=32, pe='ape' ): super(VideoDepthAnything, self).__init__()
self.intermediate_layer_idx = { 'vits': [2, 5, 8, 11], 'vitl': [4, 11, 17, 23] } self.encoder = encoder self.pretrained = DINOv2(model_name=encoder)
self.head = DPTHeadTemporal(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken, num_frames=num_frames, pe=pe)
def forward(self, x): B, T, C, H, W = x.shape patch_h, patch_w = H // 14, W // 14 features = self.pretrained.get_intermediate_layers(x.flatten(0,1), self.intermediate_layer_idx[self.encoder], return_class_token=True) depth = self.head(features, patch_h, patch_w, T) depth = F.interpolate(depth, size=(H, W), mode="bilinear", align_corners=True) depth = F.relu(depth) return depth.squeeze(1).unflatten(0, (B, T)) # return shape [B, T, H, W] def infer_video_depth(self, frames, target_fps, input_size=518, device='cuda'): transform = Compose([ Resize( width=input_size, height=input_size, resize_target=False, keep_aspect_ratio=True, ensure_multiple_of=14, resize_method='lower_bound', image_interpolation_method=cv2.INTER_CUBIC, ), NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), PrepareForNet(), ])
frame_size = frames[0].shape[:2] frame_list = [frames[i] for i in range(frames.shape[0])] frame_step = INFER_LEN - OVERLAP org_video_len = len(frame_list) append_frame_len = (frame_step - (org_video_len % frame_step)) % frame_step + (INFER_LEN - frame_step) frame_list = frame_list + [frame_list[-1].copy()] * append_frame_len depth_list = [] pre_input = None for frame_id in tqdm(range(0, org_video_len, frame_step)): cur_list = [] for i in range(INFER_LEN): cur_list.append(torch.from_numpy(transform({'image': frame_list[frame_id+i].astype(np.float32) / 255.0})['image']).unsqueeze(0).unsqueeze(0)) cur_input = torch.cat(cur_list, dim=1).to(device) if pre_input is not None: cur_input[:, :OVERLAP, ...] = pre_input[:, KEYFRAMES, ...]
with torch.no_grad(): depth = self.forward(cur_input) # depth shape: [1, T, H, W]
depth = F.interpolate(depth.flatten(0,1).unsqueeze(1), size=frame_size, mode='bilinear', align_corners=True) depth_list += [depth[i][0].cpu().numpy() for i in range(depth.shape[0])]
pre_input = cur_input
del frame_list gc.collect()
depth_list_aligned = [] ref_align = [] align_len = OVERLAP - INTERP_LEN kf_align_list = KEYFRAMES[:align_len]
for frame_id in range(0, len(depth_list), INFER_LEN): if len(depth_list_aligned) == 0: depth_list_aligned += depth_list[:INFER_LEN] for kf_id in kf_align_list: ref_align.append(depth_list[frame_id+kf_id]) else: curr_align = [] for i in range(len(kf_align_list)): curr_align.append(depth_list[frame_id+i]) scale, shift = compute_scale_and_shift(np.concatenate(curr_align), np.concatenate(ref_align), np.concatenate(np.ones_like(ref_align)==1))
pre_depth_list = depth_list_aligned[-INTERP_LEN:] post_depth_list = depth_list[frame_id+align_len:frame_id+OVERLAP] for i in range(len(post_depth_list)): post_depth_list[i] = post_depth_list[i] * scale + shift post_depth_list[i][post_depth_list[i]<0] = 0 depth_list_aligned[-INTERP_LEN:] = get_interpolate_frames(pre_depth_list, post_depth_list)
for i in range(OVERLAP, INFER_LEN): new_depth = depth_list[frame_id+i] * scale + shift new_depth[new_depth<0] = 0 depth_list_aligned.append(new_depth)
ref_align = ref_align[:1] for kf_id in kf_align_list[1:]: new_depth = depth_list[frame_id+kf_id] * scale + shift new_depth[new_depth<0] = 0 ref_align.append(new_depth) depth_list = depth_list_aligned return depth_list[:org_video_len], target_fps .gitattributes+2
app.pyAdded+168
assets/example_videos/Tokyo-Walk_rgb.mp4Added+3
assets/example_videos/davis_rollercoaster.mp4Added+3
assets/teaser_video_v2.pngAdded

Large File Pointer Details
- SHA256: 7ab2bf5f739de9d00adafe15ac4225143b59e208b8f79af7dc22c417c3a4584f
- Pointer size: 132 Bytes
- Size of remote file: 3.8 MB
requirements.txtAdded+19
utils/dc_utils.pyAdded+82
utils/util.pyAdded+74
video_depth_anything/dinov2.pyAdded+415
video_depth_anything/dinov2_layers/__init__.pyAdded+11
video_depth_anything/dinov2_layers/attention.pyAdded+83
video_depth_anything/dinov2_layers/block.pyAdded+252
video_depth_anything/dinov2_layers/drop_path.pyAdded+35
video_depth_anything/dinov2_layers/layer_scale.pyAdded+28
video_depth_anything/dinov2_layers/mlp.pyAdded+41
video_depth_anything/dinov2_layers/patch_embed.pyAdded+89
video_depth_anything/dinov2_layers/swiglu_ffn.pyAdded+63
video_depth_anything/dpt.pyAdded+160
video_depth_anything/dpt_temporal.pyAdded+96
video_depth_anything/motion_module/attention.pyAdded+423
video_depth_anything/motion_module/motion_module.pyAdded+288
video_depth_anything/util/blocks.pyAdded+162
video_depth_anything/util/transform.pyAdded+158
video_depth_anything/video_depth.pyAdded+149