Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Depth-only reference videos: convert with Depth Anything V2 Small, cached, early steps default 3

Bowen Xuec7a98e6cdb5f
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 614bfcc..66b947e 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -5,6 +5,7 @@ FreeVideo code uses [Apache-2.0](LICENSE). Its dependencies and models retain th
| Component | License |
| --- | --- |
| [Three.js](https://threejs.org/) r160, © 2010–2023 three.js authors (bundled whitebox renderer) | [MIT](web/vendor/three/LICENSE) |
+| [Depth Anything V2 Small](https://github.com/DepthAnything/Depth-Anything-V2/tree/a561b849ebae10a6f5ef49e26c83cbbcd36c71bf), © 2024 Depth Anything authors; DINOv2 © Meta Platforms, Inc. and affiliates. Small-only DPT/DINOv2 inference and preprocessing are adapted and bundled; Small weights are an optional download pinned at `03876f8651c73a60fe4c2c48294e09fcb6838fcf`. | [Apache-2.0 (code and Small weights)](freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt) |
| Qt, PySide6 and Shiboken6 | LGPL-3.0; [component notices](freevideo_engine/launcher/licenses/NOTICE.txt) |
| PyInstaller bootloader | GPL-2.0 with the bootloader exception |
| CPython / psutil | PSF / BSD-3-Clause |
diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py
index 5c3db2d..0d085fa 100644
--- a/freevideo_engine/comfy_assets.py
+++ b/freevideo_engine/comfy_assets.py
@@ -75,8 +75,14 @@ def resolve_assets(serialized, input_directory):
root = Path(input_directory).resolve()
result = {}
for row in rows:
- if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide', 'keep_source_audio'}:
+ if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide', 'keep_source_audio', 'depth'}:
raise ValueError('Invalid media item')
+ if 'depth' in row:
+ if type(row['depth']) is not bool:
+ raise ValueError('Media depth must be a boolean')
+ if (row.get('role') != 'reference' or not isinstance(row.get('file'), str)
+ or media_kind(row['file']) != 'video'):
+ raise ValueError('depth is only allowed on video references')
# The character an @ mention added the row for; a continued part keeps one picture per character.
if 'cast' in row and (set(row['cast'] if isinstance(row['cast'], dict) else ('?',)) != {'id'}
or not isinstance(row['cast']['id'], str) or not 0 < len(row['cast']['id']) <= 128):
@@ -106,6 +112,8 @@ def resolve_assets(serialized, input_directory):
result[role] = str(path)
elif role == 'reference':
reference = {'kind': kind, 'path': str(path)}
+ if row.get('depth') is True:
+ reference.update(depth=True, early_steps=3)
if cast_id(row) is not None:
reference['cast'] = cast_id(row) # only a continued part reads it (comfy_media.continued)
if 'early_steps' in row:
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index 9601098..7647554 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -1392,6 +1392,19 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
elif export_inputs:
send_progress({'label': 'Retaining and checking input media', 'timing_phase': 'encoding'})
extra = export_inputs(run, canvas) or {}
+ if any(row.get('depth') is True for row in (extra.get('media') or {}).get('references', [])):
+ from .depth_reference import prepare_media
+ def release_depth_models():
+ if release_models:
+ release_models()
+ from .encoder_prewarm import IDLE
+ from .resident_process import OWNER, ENV
+ IDLE.stop()
+ OWNER.release('depth_reference')
+ environment.pop(ENV, None)
+ extra = dict(extra, media=prepare_media(extra['media'], root=root, machine=machine,
+ environ=environment, progress=send_progress, interrupted=interrupted,
+ release_models=release_depth_models))
if extra:
if extra.get('conditioning'):
position = command.index('--prompt-file')
diff --git a/freevideo_engine/component_licenses.py b/freevideo_engine/component_licenses.py
index 6bc54f0..6dc6990 100644
--- a/freevideo_engine/component_licenses.py
+++ b/freevideo_engine/component_licenses.py
@@ -35,6 +35,13 @@ ENCODER = row('encoder', ('H3 text encoder', 'H3 文本编码器'),
('MiniMax H3 Community License Agreement, with the Qwen3-VL Apache License 2.0 notice',
'MiniMax H3 社区许可协议,附 Qwen3-VL 的 Apache 2.0 声明'),
'https://huggingface.co/t8star/Vdn-Minimax-H3-Comfy/blob/main/LICENSE')
+DEPTH = row('depth-reference', ('Depth Anything V2 Small code and weights', 'Depth Anything V2 Small 代码和权重'),
+ ('Apache License 2.0', 'Apache 许可证 2.0'),
+ 'https://github.com/DepthAnything/Depth-Anything-V2/blob/a561b849ebae10a6f5ef49e26c83cbbcd36c71bf/LICENSE')
+
+
+def depth_license():
+ return local(DEPTH, HERE / 'licenses/Depth-Anything-V2-Apache-2.0.txt')
# Libraries a runtime may carry, found by file name: versioned Windows names and Linux
# lib*.so.* alike. A CUDA build of Torch counts for CUDA, so a runtime whose CUDA files
# are named otherwise still lists it.
@@ -113,12 +120,17 @@ def bundle(root, value):
# The rest of what the Windows runtime carries (Triton's tools, TinyCC) and where its source is.
rows.append(row('notices', ('Third-party notices', '第三方组件说明'),
('Copyrights and licenses of the other components', '其余组件的版权和许可'), TEXTS / NOTICES))
+ if any('depth_anything_v2/' in entry['path'].replace('\\', '/')
+ or entry['path'].endswith('depth_anything_v2_vits.pth') for entry in value['files']):
+ rows.append(depth_license())
return rows
def named(url):
"""A row for a licence link from an installation plan; one not listed here shows its site."""
from urllib.parse import urlsplit
+ if url.startswith('https://huggingface.co/depth-anything/Depth-Anything-V2-Small/'):
+ return depth_license()
prefixes = ((MODEL, 'https://huggingface.co/OpenVDN/'), (ENCODER, 'https://huggingface.co/t8star/'),
*((value, value['link'].rsplit('/', 1)[0] + '/') for value, _ in RUNTIME))
known = next((value for value, prefix in prefixes if url.startswith(prefix)), None)
diff --git a/freevideo_engine/depth_anything_v2/__init__.py b/freevideo_engine/depth_anything_v2/__init__.py
new file mode 100644
index 0000000..4a68685
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/__init__.py
@@ -0,0 +1,4 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
diff --git a/freevideo_engine/depth_anything_v2/dinov2.py b/freevideo_engine/depth_anything_v2/dinov2.py
new file mode 100644
index 0000000..102e379
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2.py
@@ -0,0 +1,308 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+# 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 partial
+import math
+import logging
+from typing import Sequence, Tuple, Union, Callable
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint
+from torch.nn.init import trunc_normal_
+
+from .dinov2_layers import Mlp, PatchEmbed, Attention, 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" (Small only)
+ 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
+ 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 _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 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=Attention),
+ num_register_tokens=num_register_tokens,
+ **kwargs,
+ )
+ return model
+
+
+def DINOv2(model_name):
+ if model_name != "vits":
+ raise ValueError("Only DINOv2 Small is bundled")
+ return vit_small(img_size=518, patch_size=14, init_values=1.0, ffn_layer="mlp",
+ block_chunks=0, num_register_tokens=0,
+ interpolate_antialias=False, interpolate_offset=0.1)
diff --git a/freevideo_engine/depth_anything_v2/dinov2_layers/__init__.py b/freevideo_engine/depth_anything_v2/dinov2_layers/__init__.py
new file mode 100644
index 0000000..d78af09
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2_layers/__init__.py
@@ -0,0 +1,9 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+from .mlp import Mlp
+from .patch_embed import PatchEmbed
+from .block import Block
+from .attention import Attention
diff --git a/freevideo_engine/depth_anything_v2/dinov2_layers/attention.py b/freevideo_engine/depth_anything_v2/dinov2_layers/attention.py
new file mode 100644
index 0000000..b9c68c3
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2_layers/attention.py
@@ -0,0 +1,58 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+# 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 Tensor
+from torch import nn
+
+
+logger = logging.getLogger("dinov2")
+
+
+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
diff --git a/freevideo_engine/depth_anything_v2/dinov2_layers/block.py b/freevideo_engine/depth_anything_v2/dinov2_layers/block.py
new file mode 100644
index 0000000..7f268c5
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2_layers/block.py
@@ -0,0 +1,126 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+# 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 logging
+from typing import Callable, List, Any, Tuple, Dict
+
+import torch
+from torch import nn, Tensor
+
+from .attention import Attention
+from .drop_path import DropPath
+from .layer_scale import LayerScale
+from .mlp import Mlp
+
+
+logger = logging.getLogger("dinov2")
+
+
+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)
diff --git a/freevideo_engine/depth_anything_v2/dinov2_layers/drop_path.py b/freevideo_engine/depth_anything_v2/dinov2_layers/drop_path.py
new file mode 100644
index 0000000..a26bc04
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2_layers/drop_path.py
@@ -0,0 +1,40 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+# 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)
diff --git a/freevideo_engine/depth_anything_v2/dinov2_layers/layer_scale.py b/freevideo_engine/depth_anything_v2/dinov2_layers/layer_scale.py
new file mode 100644
index 0000000..4b69a9b
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2_layers/layer_scale.py
@@ -0,0 +1,33 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+# 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 torch
+from torch import Tensor
+from 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.gamma
diff --git a/freevideo_engine/depth_anything_v2/dinov2_layers/mlp.py b/freevideo_engine/depth_anything_v2/dinov2_layers/mlp.py
new file mode 100644
index 0000000..66cc9d7
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2_layers/mlp.py
@@ -0,0 +1,46 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+# 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 x
diff --git a/freevideo_engine/depth_anything_v2/dinov2_layers/patch_embed.py b/freevideo_engine/depth_anything_v2/dinov2_layers/patch_embed.py
new file mode 100644
index 0000000..642712c
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dinov2_layers/patch_embed.py
@@ -0,0 +1,94 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+# 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 Tensor
+import 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 flops
diff --git a/freevideo_engine/depth_anything_v2/dpt.py b/freevideo_engine/depth_anything_v2/dpt.py
new file mode 100644
index 0000000..89088e6
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/dpt.py
@@ -0,0 +1,209 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, torch resize, no torchvision.
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from .dinov2 import DINOv2
+from .util.blocks import FeatureFusionBlock, _make_scratch
+from .util.transform import Resize, NormalizeImage, PrepareForNet
+
+
+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 DPTHead(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ features=64,
+ use_bn=False,
+ out_channels=[48, 96, 192, 384],
+ 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
+
+
+class DepthAnythingV2(nn.Module):
+ def __init__(
+ self,
+ encoder='vits',
+ features=64,
+ out_channels=[48, 96, 192, 384],
+ use_bn=False,
+ use_clstoken=False
+ ):
+ super(DepthAnythingV2, self).__init__()
+
+ if encoder != 'vits':
+ raise ValueError('Only Depth Anything V2 Small is bundled')
+ self.intermediate_layer_idx = {'vits': [2, 5, 8, 11]}
+
+ self.encoder = encoder
+ self.pretrained = DINOv2(model_name=encoder)
+
+ self.depth_head = DPTHead(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
+
+ def forward(self, x):
+ patch_h, patch_w = x.shape[-2] // 14, x.shape[-1] // 14
+
+ features = self.pretrained.get_intermediate_layers(x, self.intermediate_layer_idx[self.encoder], return_class_token=True)
+
+ depth = self.depth_head(features, patch_h, patch_w)
+ depth = F.relu(depth)
+
+ return depth.squeeze(1)
+
+ @torch.no_grad()
+ def infer_image(self, raw_image, input_size=518):
+ image, (h, w) = self.image2tensor(raw_image, input_size)
+
+ depth = self.forward(image)
+
+ depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
+
+ return depth.cpu().numpy()
+
+ def image2tensor(self, raw_image, input_size=518):
+ transforms = [
+ 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='bicubic',
+ ),
+ NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
+ PrepareForNet(),
+ ]
+
+ h, w = raw_image.shape[:2]
+
+ image = raw_image[..., ::-1] / 255.0
+
+ sample = {'image': image}
+ for transform in transforms:
+ sample = transform(sample)
+ image = sample['image']
+ image = torch.from_numpy(image).unsqueeze(0)
+
+ image = image.to(next(self.parameters()).device)
+
+ return image, (h, w)
diff --git a/freevideo_engine/depth_anything_v2/util/__init__.py b/freevideo_engine/depth_anything_v2/util/__init__.py
new file mode 100644
index 0000000..4a68685
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/util/__init__.py
@@ -0,0 +1,4 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
diff --git a/freevideo_engine/depth_anything_v2/util/blocks.py b/freevideo_engine/depth_anything_v2/util/blocks.py
new file mode 100644
index 0000000..cff1779
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/util/blocks.py
@@ -0,0 +1,153 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, no torchvision.
+
+import 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 == 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 == True:
+ out = self.bn1(out)
+
+ out = self.activation(out)
+ out = self.conv2(out)
+ if self.bn == 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(FeatureFusionBlock, self).__init__()
+
+ self.deconv = deconv
+ self.align_corners = align_corners
+
+ self.groups=1
+
+ self.expand = expand
+ out_features = features
+ if self.expand == 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, **modifier, mode="bilinear", align_corners=self.align_corners)
+
+ output = self.out_conv(output)
+
+ return output
diff --git a/freevideo_engine/depth_anything_v2/util/transform.py b/freevideo_engine/depth_anything_v2/util/transform.py
new file mode 100644
index 0000000..e90bce2
--- /dev/null
+++ b/freevideo_engine/depth_anything_v2/util/transform.py
@@ -0,0 +1,173 @@
+# Depth Anything V2, Copyright (c) 2024 Depth Anything authors.
+# Adapted from a561b849ebae10a6f5ef49e26c83cbbcd36c71bf for Small inference.
+# SPDX-License-Identifier: Apache-2.0; see freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt.
+# Changes: Small only, ordinary torch attention, explicit device, torch resize, no torchvision.
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+
+
+def _resize(image, width, height, mode):
+ channels = image.ndim == 3
+ value = np.ascontiguousarray(image.transpose(2, 0, 1) if channels else image[None])
+ tensor = torch.from_numpy(value).unsqueeze(0)
+ options = dict(align_corners=False) if mode == 'bicubic' else {}
+ resized = F.interpolate(tensor, (height, width), mode=mode, **options)[0].numpy()
+ return resized.transpose(1, 2, 0) if channels else resized[0]
+
+
+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='bicubic',
+ ):
+ """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"] = _resize(sample["image"], width, height, self.__image_interpolation_method)
+
+ if self.__resize_target:
+ if "depth" in sample:
+ sample["depth"] = _resize(sample["depth"], width, height, 'nearest')
+
+ if "mask" in sample:
+ sample["mask"] = _resize(sample["mask"].astype(np.float32), width, height, '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 sample
diff --git a/freevideo_engine/depth_reference.py b/freevideo_engine/depth_reference.py
new file mode 100644
index 0000000..5704193
--- /dev/null
+++ b/freevideo_engine/depth_reference.py
@@ -0,0 +1,452 @@
+"""Optional, file-backed depth references. Torch lives only in a disposable worker.
+
+Small's vendored Apache-2.0 network and preprocessing follow Quinn's fixed
+DAV2 experiment. Cache identity deliberately excludes prompt, seed and K.
+"""
+from contextlib import contextmanager
+from fractions import Fraction
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+import uuid
+
+from . import processes
+from .paths import data_root
+
+PREPROCESSING_VERSION = 'dav2-small-pyav-torch-bgr-imagenet-lower-bound-14-v2'
+CODE_VERSION = 'freevideo-depth-reference-v1'
+STAGE = 'depth_reference'
+
+
+def catalog():
+ return json.loads(Path(__file__).with_name('depth_reference_model.json').read_text(encoding='utf-8'))
+
+
+def canonical_json(value):
+ return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False)
+
+
+def digest(path, check=lambda: None):
+ value = hashlib.sha256()
+ with Path(path).open('rb') as stream:
+ while block := stream.read(1024 * 1024):
+ check()
+ value.update(block)
+ return value.hexdigest()
+
+
+def cache_directory(root=None):
+ # download_cache is OS page-cache advice, not an application cache folder.
+ return Path(root or data_root()) / 'input-cache' / 'depth-cache'
+
+
+@contextmanager
+def _lock(path, check, *, inherit=False):
+ from .locking import runtime_lock
+ while True:
+ check()
+ try:
+ lease = runtime_lock(path, inherit=inherit)
+ descriptor = lease.__enter__()
+ break
+ except BlockingIOError:
+ time.sleep(.1)
+ try:
+ yield descriptor
+ finally:
+ lease.__exit__(None, None, None)
+
+
+def ensure_weights(root, emit, check):
+ """The same optional-model catalog/transfer mechanism as FreeToken and ASR."""
+ from . import network
+ from .adaln_assets import _download_plan
+ from .prompt_vlm.assets import remote
+ spec = catalog()
+ row = spec['files'][0]
+ folder = Path(root) / 'models' / 'depth-anything-v2-small'
+ path = folder / row['file']
+ with _lock(folder / 'download.lock', check):
+ if path.is_file() and path.stat().st_size == row['bytes'] and digest(path, check) == row['sha256']:
+ return path
+ if path.exists():
+ network.retain_partial(path, 'rejected')
+ plan = _download_plan(Path(root))
+ sources = plan['sources'] = dict(plan.get('sources', {}))
+ if not sources.get('image-models'):
+ sources['image-models'] = [dict(row) for row in sources.get('models', [])
+ if row['id'] in ('official', 'hf-mirror')]
+ sources['image-models'].append({'id': 'modelscope'})
+ plan.update(quiet=True, resource_check=check)
+ # remote() describes HF pins and a hash-locked ModelScope fallback;
+ # network retains its measured routes and the user's connection mode.
+ def moved(current, total, speed, **_):
+ emit(phase='dependencies', stage='depth_reference_download', label='Downloading depth reference model',
+ done=current, total=row['bytes'], unit='bytes', bytes_per_second=speed)
+ check()
+ try:
+ network.download(network.model_urls(plan, remote(spec, row)), path, row['sha256'], moved,
+ network=plan, size=row['bytes'], category='image-models', keep_partial=True,
+ stall_seconds=30, slow_seconds=15, low_speed_limit=64 * 1024)
+ except Exception as error:
+ from .sampling_assets import _cancel_or_disk
+ if _cancel_or_disk(error):
+ raise
+ check()
+ raise RuntimeError('Depth reference weights are unavailable. Retry with a connection, or put the '
+ 'official depth_anything_v2_vits.pth (99,218,434 bytes, SHA-256 '
+ + row['sha256'] + ') in ' + str(folder)) from error
+ if path.stat().st_size != row['bytes'] or digest(path, check) != row['sha256']:
+ raise ValueError('Depth reference weight size/SHA-256 verification failed: ' + str(path))
+ return path
+
+
+def _rotation(frame):
+ # PyAV exposes the display matrix as counterclockwise degrees, as in agent.media.
+ try:
+ return round(frame.rotation or 0) % 360
+ except (AttributeError, ValueError):
+ return 0
+
+
+def _upright_bgr(frame):
+ import numpy as np
+ return np.ascontiguousarray(np.rot90(frame.to_ndarray(format='bgr24'), round(_rotation(frame) / 90) % 4))
+
+
+def inspect_video(path, check=lambda: None, *, depth=False):
+ """Decode every frame, rather than trusting container frame-count headers."""
+ import av
+ import numpy as np
+ pts, dimensions, rotation = [], None, None
+ with av.open(str(path)) as container:
+ if not container.streams.video:
+ raise ValueError('Depth reference needs a decodable video')
+ if depth and container.streams.audio:
+ raise ValueError('Depth reference cache unexpectedly contains audio')
+ stream = container.streams.video[0]
+ rate = stream.average_rate
+ if rate is None or rate <= 0:
+ raise ValueError('Depth reference video has no valid frame rate')
+ time_base = stream.time_base
+ for frame in container.decode(stream):
+ check()
+ current_rotation = _rotation(frame)
+ if rotation is not None and current_rotation != rotation:
+ raise ValueError('Depth reference video changes display rotation')
+ rotation = current_rotation
+ size = (frame.width, frame.height)
+ if dimensions is not None and dimensions != size:
+ raise ValueError('Depth reference video changes dimensions')
+ dimensions = size
+ pts.append(frame.pts)
+ if depth:
+ rgb = frame.to_ndarray(format='rgb24')
+ if not (np.array_equal(rgb[..., 0], rgb[..., 1]) and np.array_equal(rgb[..., 1], rgb[..., 2])):
+ raise ValueError('Depth reference cache is not grayscale')
+ if not pts:
+ raise ValueError('Depth reference video has no decodable frames')
+ if depth and rotation:
+ raise ValueError('Depth reference cache unexpectedly contains display rotation')
+ if round(rotation / 90) % 2:
+ dimensions = dimensions[::-1]
+ return dict(width=dimensions[0], height=dimensions[1], fps_num=rate.numerator, fps_den=rate.denominator,
+ frames=len(pts), pts=pts, time_base=str(time_base), rotation=rotation)
+
+
+def identity(source, video, device, check=lambda: None):
+ spec = catalog()
+ output = {key: video[key] for key in ('width', 'height', 'fps_num', 'fps_den', 'frames')}
+ output.update(fit='source', audio=False)
+ pix_fmt = 'yuv420p' if video['width'] % 2 == video['height'] % 2 == 0 else 'yuv444p'
+ return dict(source_sha256=digest(source, check), source_size=Path(source).stat().st_size,
+ model_id=spec['repo'], weights_sha256=spec['files'][0]['sha256'], source_commit=spec['source_commit'],
+ code_version=CODE_VERSION, preprocessing_version=PREPROCESSING_VERSION,
+ selection_spec=dict(source_start_pts=video['pts'][0], source_end_pts=video['pts'][-1],
+ source_time_base=video['time_base'], crop_rect=None,
+ rotation=video['rotation'], tail_policy='none'),
+ output_spec=output,
+ inference_spec=dict(input_size=518, precision='fp16' if device == 'cuda' else 'fp32',
+ normalization='whole_clip_p1_p99_from_240x136_near_white_v1',
+ encoder='gray-to-'+pix_fmt+'/libx264/crf16/threads2', runtime_backend='torch-'+device))
+
+
+def cache_key(config):
+ return hashlib.sha256(canonical_json(config).encode('utf-8')).hexdigest()
+
+
+def _validate(path, expected, check):
+ observed = inspect_video(path, check, depth=True)
+ if any(observed[key] != expected[key] for key in ('width', 'height', 'fps_num', 'fps_den', 'frames')):
+ raise ValueError('Depth reference output dimensions, frame rate or frame count differ from the input')
+ return observed
+
+
+def _cached(folder, config, check):
+ try:
+ manifest = json.loads((folder / 'manifest.json').read_text(encoding='utf-8'))
+ output = folder / 'depth.mp4'
+ if (manifest['config'] != config or manifest['output_sha256'] != digest(output, check)
+ or manifest['output_bytes'] != output.stat().st_size):
+ return None
+ _validate(output, config['output_spec'], check)
+ return output
+ except (OSError, ValueError, KeyError, TypeError) as error:
+ if isinstance(error, InterruptedError):
+ raise
+ return None
+
+
+def _load_model(weights, device):
+ import torch
+ from .depth_anything_v2.dpt import DepthAnythingV2
+ model = DepthAnythingV2()
+ model.load_state_dict(torch.load(weights, map_location='cpu', weights_only=True), strict=True)
+ return model.to(device).eval()
+
+
+def _infer(source, stage, video, weights, device, emit, check):
+ import av
+ import numpy as np
+ import psutil
+ import torch
+ # Reserve system RAM and account for live free memory before loading.
+ if psutil.virtual_memory().available < 2 * 2**30:
+ raise MemoryError('Depth reference needs 1 GiB working RAM plus 1 GiB system reserve; free memory and retry')
+ if device == 'cuda':
+ if not torch.cuda.is_available():
+ raise RuntimeError('CUDA is unavailable for depth reference; select the CPU backend to use FP32')
+ free, total = torch.cuda.mem_get_info()
+ reserve = max(512 * 2**20, total // 10)
+ if free < reserve + 512 * 2**20:
+ raise MemoryError('Not enough free GPU memory for depth reference and the GPU reserve')
+ torch.set_num_threads(min(8, os.cpu_count() or 1))
+ shape = (video['frames'], video['height'], video['width'])
+ from .disk_space import free_bytes
+ if free_bytes(stage) < (shape[0] * (shape[1] * shape[2] + 240 * 136) * 4 + 256 * 2**20):
+ raise OSError('Not enough disk space to stage depth frames; free space and retry')
+ model = _load_model(weights, device)
+ raw_path, small_path = stage / 'raw.f32', stage / 'small.f32'
+ depths = np.memmap(raw_path, mode='w+', dtype=np.float32, shape=shape)
+ small = np.memmap(small_path, mode='w+', dtype=np.float32, shape=(video['frames'], 136, 240))
+ try:
+ with av.open(str(source)) as container:
+ count = 0
+ for frame in container.decode(video=0):
+ check()
+ bgr = _upright_bgr(frame)
+ if (count >= video['frames'] or bgr.shape[:2] != shape[1:]
+ or _rotation(frame) != video['rotation']):
+ raise ValueError('Source video changed during depth conversion')
+ if psutil.virtual_memory().available < 2**30:
+ raise MemoryError('Depth reference stopped to preserve 1 GiB of free system RAM')
+ with torch.inference_mode(), torch.autocast('cuda', dtype=torch.float16, enabled=device == 'cuda'):
+ depth = np.asarray(model.infer_image(bgr, 518), dtype=np.float32)
+ if depth.shape != shape[1:] or not np.isfinite(depth).all():
+ raise ValueError('Depth model returned invalid/nonfinite pixels')
+ depths[count] = depth
+ small[count] = torch.nn.functional.interpolate(torch.from_numpy(depth)[None, None],
+ (136, 240), mode='area')[0, 0].numpy()
+ count += 1
+ emit(done=count, total=video['frames'], unit='frames', phase='depth_reference',
+ detail='%d/%d frames' % (count, video['frames']))
+ if count != video['frames']:
+ raise ValueError('Source video frame count changed during depth conversion')
+ # Whole-clip p1/p99, in-place selection on disk-backed samples, bounded RAM.
+ small.flush()
+ lo, hi = np.percentile(small.reshape(-1), [1, 99], overwrite_input=True)
+ span = max(float(hi - lo), 1e-6)
+ output = stage / 'depth.mp4'
+ emit(phase='depth_reference', detail='Encoding depth video')
+ with av.open(str(output), 'w') as container:
+ stream = container.add_stream('libx264', rate=Fraction(video['fps_num'], video['fps_den']))
+ stream.width, stream.height = video['width'], video['height']
+ stream.pix_fmt = 'yuv420p' if stream.width % 2 == stream.height % 2 == 0 else 'yuv444p'
+ stream.options = {'crf': '16', 'threads': '2'}
+ for index, depth in enumerate(depths):
+ check()
+ gray = (np.clip((depth - lo) / span, 0, 1) * 255).round().astype(np.uint8)
+ frame = av.VideoFrame.from_ndarray(gray, format='gray')
+ frame.pts, frame.time_base = index, Fraction(video['fps_den'], video['fps_num'])
+ for packet in stream.encode(frame):
+ container.mux(packet)
+ for packet in stream.encode(None):
+ container.mux(packet)
+ return dict(low=float(lo), high=float(hi), near='white', torch=torch.__version__,
+ av=av.__version__, ffmpeg=av.library_versions,
+ attention='ordinary-torch-matmul-softmax', device=device)
+ finally:
+ # Close mappings before deleting or moving files (Windows).
+ depths._mmap.close()
+ small._mmap.close()
+ del depths, small
+ raw_path.unlink(missing_ok=True)
+ small_path.unlink(missing_ok=True)
+
+
+def _convert(request, emit, check):
+ source, root, work = Path(request['source']), Path(request['root']), Path(request['work'])
+ device = request.get('device', 'auto')
+ if device == 'auto':
+ import torch
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
+ if device not in ('cpu', 'cuda'):
+ raise ValueError('Depth reference device must be cpu, cuda or auto')
+ emit(phase='depth_reference', detail='Checking depth reference cache')
+ initial_hash, initial_size = digest(source, check), source.stat().st_size
+ video = inspect_video(source, check)
+ config = identity(source, video, device, check)
+ if config['source_sha256'] != initial_hash or config['source_size'] != initial_size:
+ raise ValueError('Source video changed during depth inspection')
+ cache = Path(request['cache'])
+ key = cache_key(config)
+ target = cache / key
+ with _lock(cache / '.locks' / (key + '.lock'), check):
+ found = _cached(target, config, check)
+ if found is not None:
+ return dict(path=str(found), cache_hit=True, key=key)
+ weights = ensure_weights(root, emit, check)
+ # Parent releases idle Comfy/engine/encoder models only on a cache miss.
+ emit(phase=STAGE, stage=STAGE, label='Extracting depth from the reference video',
+ done=0, total=video['frames'], unit='frames', detail='Loading depth model', waiting_for_device=True)
+ while not (work / 'device-ready').is_file():
+ check()
+ time.sleep(.05)
+ stage = work / 'result'
+ stage.mkdir()
+ with _lock(Path(os.environ.get('FREEVIDEO_LOCK_PATH', root / 'engine.lock')), check, inherit=True):
+ metrics = _infer(source, stage, video, weights, device, emit, check)
+ observed = _validate(stage / 'depth.mp4', video, check)
+ if digest(source, check) != config['source_sha256'] or source.stat().st_size != config['source_size']:
+ raise ValueError('Source video changed during depth conversion')
+ manifest = dict(config=config, source_pts=video['pts'], source_time_base=video['time_base'], output=observed,
+ output_sha256=digest(stage / 'depth.mp4', check), output_bytes=(stage / 'depth.mp4').stat().st_size,
+ normalization=metrics, license='Apache-2.0',
+ license_sources=['https://github.com/DepthAnything/Depth-Anything-V2/tree/'+catalog()['source_commit'],
+ 'https://huggingface.co/'+catalog()['repo']+'/tree/'+catalog()['revision']])
+ (stage / 'manifest.json').write_text(canonical_json(manifest), encoding='utf-8')
+ check()
+ if target.exists():
+ # Retain invalid old artifacts separately; never accept a partial directory.
+ target.rename(cache / (key + '.rejected-' + uuid.uuid4().hex))
+ os.replace(stage, target)
+ return dict(path=str(target / 'depth.mp4'), cache_hit=False, key=key)
+
+
+def convert(source, *, root=None, cache=None, device='auto', python=None, environ=None,
+ progress=None, interrupted=None, release_models=None):
+ """Convert in a supervised child; return a validated cache path after it exits.
+
+ Progress carries stage=depth_reference and done/total in frames. Cancellation
+ stops the whole child tree and removes only this request's temporary files.
+ """
+ root = Path(root or data_root()).resolve()
+ cache = Path(cache or cache_directory(root)).resolve()
+ cache.mkdir(parents=True, exist_ok=True)
+ def check():
+ if interrupted:
+ interrupted()
+ check()
+ with tempfile.TemporaryDirectory(prefix='.depth-', dir=cache) as directory:
+ work = Path(directory)
+ request = dict(source=str(Path(source).resolve()), root=str(root), cache=str(cache), device=device, work=str(work))
+ (work / 'request.json').write_text(canonical_json(request), encoding='utf-8')
+ command = processes.module_command('freevideo_engine.depth_reference', '--request', work / 'request.json')
+ if python is not None:
+ command[0] = str(python)
+ with (work / 'worker.log').open('wb') as log:
+ child = processes.popen(command, env=environ, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
+ start_new_session=True, supervise=True, pass_fds=processes.descriptors())
+ last, released = None, False
+ def poll():
+ nonlocal last, released
+ check()
+ try:
+ value = json.loads((work / 'progress.json').read_text(encoding='utf-8'))
+ except (OSError, ValueError):
+ return
+ if value.get('waiting_for_device') and not released:
+ if release_models:
+ release_models()
+ check()
+ (work / 'device-ready').touch()
+ released = True
+ if progress and value != last:
+ progress({key: val for key, val in value.items() if key != 'waiting_for_device'})
+ last = value
+ try:
+ while child.poll() is None:
+ poll()
+ try:
+ child.wait(timeout=.1)
+ except subprocess.TimeoutExpired:
+ pass
+ poll()
+ if child.returncode:
+ try:
+ error = json.loads((work / 'error.json').read_text(encoding='utf-8'))['error']
+ except (OSError, ValueError, KeyError):
+ error = 'Depth reference worker exited with code %s' % child.returncode
+ raise RuntimeError(error)
+ result = json.loads((work / 'result.json').read_text(encoding='utf-8'))
+ check()
+ return Path(result['path'])
+ except BaseException:
+ (work / 'cancelled').touch()
+ processes.stop(child)
+ raise
+
+
+def prepare_media(media, *, root, machine, environ, progress, interrupted, release_models):
+ """Execution only. With depth off, return the original object unchanged."""
+ if not any(row.get('depth') is True for row in media.get('references', [])):
+ return media
+ result = dict(media, references=[])
+ for row in media.get('references', []):
+ if 'depth' in row and (type(row['depth']) is not bool or row.get('kind') != 'video'):
+ raise ValueError('depth must be a boolean on a video reference')
+ if row.get('depth') is not True:
+ result['references'].append(row)
+ continue
+ converted = convert(row['path'], root=root, python=machine['python'], environ=environ,
+ device='cpu' if machine.get('device_backend') in ('cpu', 'mps') else 'cuda',
+ progress=progress, interrupted=interrupted, release_models=release_models)
+ value = {key: val for key, val in row.items() if key != 'depth'}
+ value['path'] = str(converted)
+ value.setdefault('early_steps', 3)
+ result['references'].append(value)
+ return result
+
+
+def main():
+ import argparse
+ from .monitoring import save
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--request', required=True, type=Path)
+ args = parser.parse_args()
+ request = json.loads(args.request.read_text(encoding='utf-8'))
+ work = Path(request['work'])
+ def check():
+ if (work / 'cancelled').exists():
+ raise InterruptedError('Depth reference conversion cancelled')
+ state = dict(stage=STAGE, phase=STAGE, timing_phase='encoding', label='Extracting depth from the reference video',
+ done=0, total=None, unit='frames', references=True)
+ def emit(**values):
+ state.update(values)
+ save(work / 'progress.json', state)
+ try:
+ with processes.worker_signals():
+ result = _convert(request, emit, check)
+ save(work / 'result.json', result)
+ except Exception as error:
+ save(work / 'error.json', dict(error=type(error).__name__ + ': ' + str(error)))
+ return 1
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/freevideo_engine/depth_reference_model.json b/freevideo_engine/depth_reference_model.json
new file mode 100644
index 0000000..54553f3
--- /dev/null
+++ b/freevideo_engine/depth_reference_model.json
@@ -0,0 +1,12 @@
+{
+ "repo": "depth-anything/Depth-Anything-V2-Small",
+ "revision": "03876f8651c73a60fe4c2c48294e09fcb6838fcf",
+ "source_commit": "a561b849ebae10a6f5ef49e26c83cbbcd36c71bf",
+ "license": "Apache-2.0",
+ "modelscope": {"repo": "depth-anything/Depth-Anything-V2-Small", "revision": "master"},
+ "files": [{
+ "file": "depth_anything_v2_vits.pth",
+ "bytes": 99218434,
+ "sha256": "715fade13be8f229f8a70cc02066f656f2423a59effd0579197bbf57860e1378"
+ }]
+}
diff --git a/freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt b/freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt
new file mode 100644
index 0000000..d3e3fc8
--- /dev/null
+++ b/freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt
@@ -0,0 +1,217 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
+
+FreeVideo attribution and modification notice
+-------------------------------------------
+Depth Anything V2 Small code and weights: Depth Anything authors (2024).
+DINOv2: Copyright (c) Meta Platforms, Inc. and affiliates.
+Source: https://github.com/DepthAnything/Depth-Anything-V2
+Source commit: a561b849ebae10a6f5ef49e26c83cbbcd36c71bf
+Small model: https://huggingface.co/depth-anything/Depth-Anything-V2-Small
+Weight revision: 03876f8651c73a60fe4c2c48294e09fcb6838fcf
+SHA-256: 715fade13be8f229f8a70cc02066f656f2423a59effd0579197bbf57860e1378
+Only Small is included. The Apache-2.0 permission for Small does not apply to
+Base/Large/Giant weights, which are not bundled or downloaded by this feature.
+FreeVideo changes: retain Small DPT and DINOv2 only; remove xformers, nested-tensor
+and SwiGLU paths; use ordinary torch matmul/softmax attention on every machine;
+replace torchvision Compose with the same sequential transforms; follow the
+model's explicit device, and add bounded, cached video conversion in a worker.
diff --git a/pyproject.toml b/pyproject.toml
index fe22466..e9fb437 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -36,4 +36,4 @@ include = ["freevideo_engine*"]
[tool.setuptools.package-data]
"freevideo_engine.prompt_vlm" = ["model.json"]
"freevideo_engine.image_gen" = ["image_models.json", "licenses/NOTICE.txt"]
-freevideo_engine = ["stage_estimate_params.json", "build-version.txt", "build-identity.json", "release_notes.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "macos_reference_catalog.json", "superseded_tables.json", "bootstrap_versions.json", "curl_windows.json", "git_linux.json", "git_macos.json", "gcc_linux.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt", "licenses/runtime/*.txt", "subtitle_pack.json", "frame_preview_weights.json", "agent/skill/freevideo/*.txt", "agent/skill/freevideo/references/*.txt"]
+freevideo_engine = ["stage_estimate_params.json", "build-version.txt", "build-identity.json", "release_notes.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "macos_reference_catalog.json", "superseded_tables.json", "bootstrap_versions.json", "curl_windows.json", "git_linux.json", "git_macos.json", "gcc_linux.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt", "licenses/runtime/*.txt", "subtitle_pack.json", "frame_preview_weights.json", "agent/skill/freevideo/*.txt", "agent/skill/freevideo/references/*.txt", "depth_reference_model.json"]
diff --git a/web/freevideo.js b/web/freevideo.js
index 7512ac5..a6bd54a 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -51,7 +51,7 @@ style.textContent = `
.fv-panel button,.fv-panel select,.fv-panel a{box-sizing:border-box;min-height:var(--fv-h-sm,32px);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-raised);color:var(--fv-ink);padding:5px 10px;font:inherit;font-weight:var(--fv-medium,500);cursor:pointer;text-decoration:none}
.fv-panel button:hover,.fv-panel a:hover{background:var(--fv-hover)}.fv-panel button:disabled{opacity:.45;cursor:wait}
.fv-menu-failure{width:min(460px,calc(100vw - 32px));height:auto}.fv-menu-failure::backdrop{background:#0009}
-.fv-panel select{max-width:170px}.fv-note{color:var(--fv-muted);font-size:var(--fv-micro,12px);margin:8px 0;white-space:pre-wrap}.fv-error{color:var(--fv-danger)}
+.fv-panel select{max-width:170px}.fv-note{color:var(--fv-muted);font-size:var(--fv-micro,12px);margin:8px 0;white-space:pre-wrap}.fv-error{color:var(--fv-danger)}.fv-depth-only{display:flex;align-items:center;gap:8px;margin:8px 0 0;white-space:nowrap;font-size:var(--fv-small,13px);cursor:pointer}.fv-depth-only input{margin:0}
.fv-mode{font-size:var(--fv-micro,12px);color:var(--fv-accent)}
.fv-panel[data-freevideo=media]>.fv-mode{display:inline-block;margin:4px 0 2px;padding:2px 8px;border-radius:var(--fv-r-xs,3px);background:var(--fv-selected);font-weight:var(--fv-medium,500)}.fv-card{border:1px solid var(--fv-border);border-radius:var(--fv-r-md,12px);padding:10px;margin-top:10px;background:var(--fv-raised)}
.fv-card[data-enabled=false]{opacity:.5}.fv-file{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:60px}
@@ -354,6 +354,15 @@ function mediaPanel(node, mount = null) {
};
preview.onloadedmetadata = () => showLength();
}
+ if (kind === "video" && row.role === "reference") {
+ // Off by default: the video itself is the reference. On: its depth picture is, and the picture and colours are not asked for.
+ const depth = el("label", undefined, "fv-depth-only"), box = el("input");
+ box.type = "checkbox"; box.checked = row.depth === true;
+ box.onchange = () => { if (box.checked) rows[index].depth = true; else delete rows[index].depth; update(rows); };
+ depth.append(box, el("span", text("Depth only", "仅参考深度")));
+ depth.title = text("Uses a depth version of this video as the reference.", "转成深度视频后再作参考。");
+ card.append(depth);
+ }
const controls = el("div", undefined, "fv-row");
const move = delta => { const target = index + delta; if (target < 0 || target >= rows.length) return; [rows[index], rows[target]] = [rows[target], rows[index]]; update(rows); };
if (kind === "image") {
@@ -375,7 +384,7 @@ function mediaPanel(node, mount = null) {
return JSON.stringify(requestRows(swapState(node)));
}
// The run takes only what it uses (and which character a picture belongs to); the editing data of a picture stays in the workflow.
- try { return JSON.stringify(read().map(({file, role, enabled, cast, sound}) => ({file, role, enabled, ...(sound === false && mediaKindOrNull(file) === 'video' ? {sound: false} : {}), ...(typeof cast?.id === 'string' && cast.id ? {cast: {id: cast.id}} : {})}))); } catch { return serialized.value; }
+ try { return JSON.stringify(read().map(({file, role, enabled, cast, sound, depth}) => ({file, role, enabled, ...(sound === false && mediaKindOrNull(file) === 'video' ? {sound: false} : {}), ...(depth === true && role === 'reference' && mediaKindOrNull(file) === 'video' ? {depth: true} : {}), ...(typeof cast?.id === 'string' && cast.id ? {cast: {id: cast.id}} : {})}))); } catch { return serialized.value; }
};
async function upload(files) {
if (node.isUploading || !files.length) return;
diff --git a/web/generation_progress.js b/web/generation_progress.js
index ae7429d..896d5a8 100644
--- a/web/generation_progress.js
+++ b/web/generation_progress.js
@@ -20,6 +20,7 @@ const SUBACTIVITY = {
gpu: ['Loading the prompt model', '正在加载提示词模型'],
prompt: ['Processing the prompt', '正在处理提示词'],
reference: ['Processing reference images and videos', '正在处理参考图片和视频'],
+ depth: ['Extracting depth from the reference video', '正在提取参考视频的深度'],
load: ['Loading the video model', '正在载入视频模型'],
first: ['Running the first step (it takes longer the first time a size is used or after an update)',
'正在进行第一步(首次使用这个尺寸或更新后,第一步要多花一些时间)'],
@@ -38,6 +39,7 @@ const SAMPLING_NAME = {
};
const SAMPLING_PASS = {first: ['first pass', '一采'], pass2: ['second pass', '二采'], preview: ['preview', '预览']};
const SUBACTIVITY_LABELS = {
+ 'Extracting depth from the reference video': 'depth',
'Starting generation process': 'start', 'Starting text encoder': 'libraries',
'Loading text encoder': 'libraries', 'Preparing text encoder GPU': 'gpu',
'Reading text encoder weights': 'weights', 'Preparing text encoder model': 'weights',
@@ -122,7 +124,7 @@ const LABEL_ACTIVITY = {
'Preparing prompt data', 'Saving prompt cache', 'Reusing prompt cache', 'Prompt ready',
'Releasing idle models and checking available memory again'],
combined: ['Encoding text and images', 'Preparing the prompt and images', 'Preparing text and image tokens'],
- reference: ['Preparing reference media', 'Retaining and checking input media', 'Encoding input media',
+ reference: ['Extracting depth from the reference video', 'Preparing reference media', 'Retaining and checking input media', 'Encoding input media',
'Encoding reference media', 'Encoding image/video references', 'Encoding reference audio',
'Encoding long references', 'Encoding long references in smaller blocks'],
load: ['Loading the video model', 'Loading video model', 'Loading native MPS model', 'Loading cached video model',