Spaces:
Running
on
Zero
Running
on
Zero
Commit
·
e0f1d2e
1
Parent(s):
789c9b1
initial commit of depth-anything compare
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- Depth-Anything-V2/app_depth_v2_local.py +516 -0
- Depth-Anything-V2/assets/examples/demo01.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo02.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo03.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo04.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo05.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo06.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo07.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo08.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo09.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo10.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo11.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo12.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo13.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo14.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo15.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo16.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo17.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo18.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo19.jpg +3 -0
- Depth-Anything-V2/assets/examples/demo20.jpg +3 -0
- Depth-Anything-V2/depth_anything_v2/__init__.py +1 -0
- Depth-Anything-V2/depth_anything_v2/__pycache__/__init__.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/__pycache__/dinov2.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/__pycache__/dpt.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2.py +415 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__init__.py +11 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/__init__.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/attention.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/block.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/drop_path.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/layer_scale.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/mlp.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/patch_embed.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/swiglu_ffn.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/attention.py +83 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/block.py +252 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/drop_path.py +35 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/layer_scale.py +28 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/mlp.py +41 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/patch_embed.py +89 -0
- Depth-Anything-V2/depth_anything_v2/dinov2_layers/swiglu_ffn.py +63 -0
- Depth-Anything-V2/depth_anything_v2/dpt.py +221 -0
- Depth-Anything-V2/depth_anything_v2/util/__init__.py +1 -0
- Depth-Anything-V2/depth_anything_v2/util/__pycache__/__init__.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/util/__pycache__/blocks.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/util/__pycache__/transform.cpython-311.pyc +0 -0
- Depth-Anything-V2/depth_anything_v2/util/blocks.py +148 -0
- Depth-Anything-V2/depth_anything_v2/util/transform.py +158 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
Depth-Anything-V2/app_depth_v2_local.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import matplotlib
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import torch
|
| 7 |
+
import tempfile
|
| 8 |
+
import os
|
| 9 |
+
import logging
|
| 10 |
+
import gc
|
| 11 |
+
from typing import Optional, Tuple
|
| 12 |
+
from gradio_imageslider import ImageSlider
|
| 13 |
+
from huggingface_hub import hf_hub_download
|
| 14 |
+
|
| 15 |
+
from depth_anything_v2.dpt import DepthAnythingV2
|
| 16 |
+
|
| 17 |
+
# Configure logging
|
| 18 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 19 |
+
|
| 20 |
+
css = """
|
| 21 |
+
#img-display-container {
|
| 22 |
+
max-height: 100vh;
|
| 23 |
+
}
|
| 24 |
+
#img-display-input {
|
| 25 |
+
max-height: 80vh;
|
| 26 |
+
}
|
| 27 |
+
#img-display-output {
|
| 28 |
+
max-height: 80vh;
|
| 29 |
+
}
|
| 30 |
+
#download {
|
| 31 |
+
height: 62px;
|
| 32 |
+
}
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
# Device detection with fallback
|
| 36 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
|
| 37 |
+
logging.info(f"Using device: {DEVICE}")
|
| 38 |
+
|
| 39 |
+
# Model configurations for Depth Anything V2
|
| 40 |
+
MODEL_CONFIGS = {
|
| 41 |
+
'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},
|
| 42 |
+
'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},
|
| 43 |
+
'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
|
| 44 |
+
'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
# Available model variants with display names
|
| 48 |
+
MODEL_VARIANTS = {
|
| 49 |
+
'vits': {
|
| 50 |
+
'display_name': 'ViT-Small (Fastest, Lower Quality)',
|
| 51 |
+
'checkpoint': 'checkpoints/depth_anything_v2_vits.pth'
|
| 52 |
+
},
|
| 53 |
+
'vitb': {
|
| 54 |
+
'display_name': 'ViT-Base (Balanced Speed/Quality)',
|
| 55 |
+
'checkpoint': 'checkpoints/depth_anything_v2_vitb.pth'
|
| 56 |
+
},
|
| 57 |
+
'vitl': {
|
| 58 |
+
'display_name': 'ViT-Large (High Quality, Recommended)',
|
| 59 |
+
'checkpoint': 'checkpoints/depth_anything_v2_vitl.pth'
|
| 60 |
+
},
|
| 61 |
+
'vitg': {
|
| 62 |
+
'display_name': 'ViT-Giant (Highest Quality, Slowest)',
|
| 63 |
+
'checkpoint': 'checkpoints/depth_anything_v2_vitg.pth'
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# Global variables for model caching
|
| 68 |
+
_cached_model = None
|
| 69 |
+
_cached_device = None
|
| 70 |
+
_cached_model_selection = None
|
| 71 |
+
|
| 72 |
+
def check_gpu_memory():
|
| 73 |
+
"""Check and log current GPU memory usage"""
|
| 74 |
+
try:
|
| 75 |
+
if torch.cuda.is_available():
|
| 76 |
+
allocated = torch.cuda.memory_allocated(0) / 1024**3
|
| 77 |
+
reserved = torch.cuda.memory_reserved(0) / 1024**3
|
| 78 |
+
max_allocated = torch.cuda.max_memory_allocated(0) / 1024**3
|
| 79 |
+
total = torch.cuda.get_device_properties(0).total_memory / 1024**3
|
| 80 |
+
|
| 81 |
+
logging.info(f"GPU Memory - Allocated: {allocated:.2f}GB, Reserved: {reserved:.2f}GB, Max: {max_allocated:.2f}GB, Total: {total:.2f}GB")
|
| 82 |
+
return allocated, reserved, max_allocated, total
|
| 83 |
+
except RuntimeError as e:
|
| 84 |
+
logging.warning(f"Failed to get GPU memory info: {e}")
|
| 85 |
+
return None, None, None, None
|
| 86 |
+
|
| 87 |
+
def get_paginated_examples(examples: list, page: int = 0, per_page: int = 8) -> tuple:
|
| 88 |
+
"""Get paginated examples with navigation info"""
|
| 89 |
+
total_pages = (len(examples) - 1) // per_page + 1 if examples else 0
|
| 90 |
+
start_idx = page * per_page
|
| 91 |
+
end_idx = min(start_idx + per_page, len(examples))
|
| 92 |
+
|
| 93 |
+
current_examples = examples[start_idx:end_idx]
|
| 94 |
+
has_prev = page > 0
|
| 95 |
+
has_next = page < total_pages - 1
|
| 96 |
+
|
| 97 |
+
return current_examples, total_pages, has_prev, has_next
|
| 98 |
+
|
| 99 |
+
def aggressive_cleanup():
|
| 100 |
+
"""Perform aggressive memory cleanup"""
|
| 101 |
+
gc.collect()
|
| 102 |
+
if torch.cuda.is_available():
|
| 103 |
+
torch.cuda.empty_cache()
|
| 104 |
+
logging.info("Performed memory cleanup")
|
| 105 |
+
|
| 106 |
+
def get_available_models() -> dict:
|
| 107 |
+
"""Get all available models with their display names"""
|
| 108 |
+
available_models = {}
|
| 109 |
+
|
| 110 |
+
# All models are available since we can download them from HF Hub
|
| 111 |
+
for variant, info in MODEL_VARIANTS.items():
|
| 112 |
+
available_models[info['display_name']] = {
|
| 113 |
+
'variant': variant,
|
| 114 |
+
'checkpoint': info['checkpoint'], # Keep for backwards compatibility
|
| 115 |
+
'config': MODEL_CONFIGS[variant]
|
| 116 |
+
}
|
| 117 |
+
logging.info(f"Available model: {info['display_name']} (variant: {variant})")
|
| 118 |
+
|
| 119 |
+
return available_models
|
| 120 |
+
|
| 121 |
+
def get_model_from_selection(model_selection: str) -> Tuple[str, dict]:
|
| 122 |
+
"""Get model variant and config from selection"""
|
| 123 |
+
available_models = get_available_models()
|
| 124 |
+
|
| 125 |
+
if model_selection in available_models:
|
| 126 |
+
model_info = available_models[model_selection]
|
| 127 |
+
return model_info['variant'], model_info['config'], model_info['checkpoint']
|
| 128 |
+
|
| 129 |
+
# Fallback to default if selection not found
|
| 130 |
+
logging.warning(f"Model selection '{model_selection}' not found, using default")
|
| 131 |
+
return 'vitl', MODEL_CONFIGS['vitl'], 'checkpoints/depth_anything_v2_vitl.pth'
|
| 132 |
+
|
| 133 |
+
def load_model(model_selection: str) -> Tuple[DepthAnythingV2, str]:
|
| 134 |
+
"""Load and cache the selected model"""
|
| 135 |
+
global _cached_model, _cached_device, _cached_model_selection
|
| 136 |
+
|
| 137 |
+
# Check if we already have the right model cached
|
| 138 |
+
if (_cached_model is not None and
|
| 139 |
+
_cached_model_selection == model_selection and
|
| 140 |
+
_cached_device == DEVICE):
|
| 141 |
+
logging.info(f"Using cached model: {model_selection}")
|
| 142 |
+
return _cached_model, _cached_device
|
| 143 |
+
|
| 144 |
+
# Clear previous model if any
|
| 145 |
+
if _cached_model is not None:
|
| 146 |
+
logging.info("Clearing previous model from cache...")
|
| 147 |
+
del _cached_model
|
| 148 |
+
_cached_model = None
|
| 149 |
+
aggressive_cleanup()
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
# Get model info
|
| 153 |
+
variant, config, checkpoint_path = get_model_from_selection(model_selection)
|
| 154 |
+
|
| 155 |
+
logging.info(f"Loading model: {model_selection} (variant: {variant})")
|
| 156 |
+
|
| 157 |
+
# Download model from Hugging Face Hub if not already cached locally
|
| 158 |
+
try:
|
| 159 |
+
# Map variant to model names used in HF Hub
|
| 160 |
+
model_name_mapping = {
|
| 161 |
+
'vits': 'Small',
|
| 162 |
+
'vitb': 'Base',
|
| 163 |
+
'vitl': 'Large',
|
| 164 |
+
'vitg': 'Giant'
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
model_name = model_name_mapping.get(variant, 'Large') # Default to Large
|
| 168 |
+
filename = f"depth_anything_v2_{variant}.pth"
|
| 169 |
+
|
| 170 |
+
# Try to download from HF Hub first
|
| 171 |
+
try:
|
| 172 |
+
filepath = hf_hub_download(
|
| 173 |
+
repo_id=f"depth-anything/Depth-Anything-V2-{model_name}",
|
| 174 |
+
filename=filename,
|
| 175 |
+
repo_type="model"
|
| 176 |
+
)
|
| 177 |
+
logging.info(f"Downloaded model from HF Hub: {filepath}")
|
| 178 |
+
checkpoint_path = filepath
|
| 179 |
+
except Exception as e:
|
| 180 |
+
logging.warning(f"Failed to download from HF Hub: {e}")
|
| 181 |
+
# Fallback to local checkpoint if it exists
|
| 182 |
+
if not os.path.exists(checkpoint_path):
|
| 183 |
+
raise FileNotFoundError(f"Neither HF Hub download nor local checkpoint available: {checkpoint_path}")
|
| 184 |
+
logging.info(f"Using local checkpoint: {checkpoint_path}")
|
| 185 |
+
|
| 186 |
+
except Exception as e:
|
| 187 |
+
logging.error(f"Error in model download/loading: {e}")
|
| 188 |
+
raise
|
| 189 |
+
|
| 190 |
+
# Create model
|
| 191 |
+
model = DepthAnythingV2(**config)
|
| 192 |
+
|
| 193 |
+
# Load state dict
|
| 194 |
+
state_dict = torch.load(checkpoint_path, map_location="cpu")
|
| 195 |
+
model.load_state_dict(state_dict)
|
| 196 |
+
|
| 197 |
+
# Move to device and set to eval mode
|
| 198 |
+
model = model.to(DEVICE).eval()
|
| 199 |
+
|
| 200 |
+
# Cache the model
|
| 201 |
+
_cached_model = model
|
| 202 |
+
_cached_device = DEVICE
|
| 203 |
+
_cached_model_selection = model_selection
|
| 204 |
+
|
| 205 |
+
logging.info(f"✅ Model loaded successfully: {model_selection}")
|
| 206 |
+
check_gpu_memory()
|
| 207 |
+
|
| 208 |
+
return model, DEVICE
|
| 209 |
+
|
| 210 |
+
except Exception as e:
|
| 211 |
+
logging.error(f"Failed to load model {model_selection}: {e}")
|
| 212 |
+
raise RuntimeError(f"Failed to load model: {str(e)}")
|
| 213 |
+
|
| 214 |
+
def predict_depth(image: np.ndarray, model_selection: str) -> np.ndarray:
|
| 215 |
+
"""Predict depth using the selected model"""
|
| 216 |
+
try:
|
| 217 |
+
# Load model (uses cache if available)
|
| 218 |
+
model, device = load_model(model_selection)
|
| 219 |
+
|
| 220 |
+
# Predict depth
|
| 221 |
+
depth = model.infer_image(image[:, :, ::-1]) # BGR to RGB conversion
|
| 222 |
+
|
| 223 |
+
return depth
|
| 224 |
+
|
| 225 |
+
except Exception as e:
|
| 226 |
+
logging.error(f"Depth prediction failed: {e}")
|
| 227 |
+
raise
|
| 228 |
+
|
| 229 |
+
def process_image(model_selection: str, image: np.ndarray,
|
| 230 |
+
progress: gr.Progress = gr.Progress()) -> Tuple[Optional[tuple], Optional[str], Optional[str], str]:
|
| 231 |
+
"""
|
| 232 |
+
Main processing function for depth estimation
|
| 233 |
+
"""
|
| 234 |
+
if image is None:
|
| 235 |
+
return None, None, None, "❌ Please upload an image."
|
| 236 |
+
|
| 237 |
+
try:
|
| 238 |
+
progress(0.1, desc=f"Loading model ({model_selection})...")
|
| 239 |
+
|
| 240 |
+
# Get model info for status
|
| 241 |
+
variant, _, _ = get_model_from_selection(model_selection)
|
| 242 |
+
|
| 243 |
+
progress(0.3, desc="Running depth inference...")
|
| 244 |
+
|
| 245 |
+
# Make a copy of the original image
|
| 246 |
+
original_image = image.copy()
|
| 247 |
+
h, w = image.shape[:2]
|
| 248 |
+
|
| 249 |
+
# Predict depth
|
| 250 |
+
depth = predict_depth(image, model_selection)
|
| 251 |
+
|
| 252 |
+
progress(0.7, desc="Creating visualizations...")
|
| 253 |
+
|
| 254 |
+
# Create raw depth file
|
| 255 |
+
raw_depth = Image.fromarray(depth.astype('uint16'))
|
| 256 |
+
tmp_raw_depth = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
|
| 257 |
+
raw_depth.save(tmp_raw_depth.name)
|
| 258 |
+
|
| 259 |
+
# Normalize depth for visualization
|
| 260 |
+
depth_normalized = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0
|
| 261 |
+
depth_normalized = depth_normalized.astype(np.uint8)
|
| 262 |
+
|
| 263 |
+
# Apply colormap
|
| 264 |
+
cmap = matplotlib.colormaps.get_cmap('Spectral_r')
|
| 265 |
+
colored_depth = (cmap(depth_normalized)[:, :, :3] * 255).astype(np.uint8)
|
| 266 |
+
|
| 267 |
+
# Create grayscale depth file
|
| 268 |
+
gray_depth = Image.fromarray(depth_normalized)
|
| 269 |
+
tmp_gray_depth = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
|
| 270 |
+
gray_depth.save(tmp_gray_depth.name)
|
| 271 |
+
|
| 272 |
+
progress(1.0, desc="Complete!")
|
| 273 |
+
|
| 274 |
+
# Create slider output
|
| 275 |
+
slider_output = (original_image, colored_depth)
|
| 276 |
+
|
| 277 |
+
# Create status message
|
| 278 |
+
min_depth = depth.min()
|
| 279 |
+
max_depth = depth.max()
|
| 280 |
+
mean_depth = depth.mean()
|
| 281 |
+
|
| 282 |
+
# Get memory info
|
| 283 |
+
if torch.cuda.is_available():
|
| 284 |
+
current_memory = torch.cuda.memory_allocated(0) / 1024**3
|
| 285 |
+
max_memory = torch.cuda.max_memory_allocated(0) / 1024**3
|
| 286 |
+
memory_info = f" | GPU: {current_memory:.2f}GB/{max_memory:.2f}GB peak"
|
| 287 |
+
else:
|
| 288 |
+
memory_info = " | CPU processing"
|
| 289 |
+
|
| 290 |
+
status = f"""✅ Processing successful!
|
| 291 |
+
🔧 Model: {variant.upper()}{memory_info}
|
| 292 |
+
📊 Depth Statistics:
|
| 293 |
+
• Range: {min_depth:.2f} - {max_depth:.2f}
|
| 294 |
+
• Mean: {mean_depth:.2f}
|
| 295 |
+
• Input size: {w}×{h}
|
| 296 |
+
• Device: {DEVICE}"""
|
| 297 |
+
|
| 298 |
+
return slider_output, tmp_gray_depth.name, tmp_raw_depth.name, status
|
| 299 |
+
|
| 300 |
+
except Exception as e:
|
| 301 |
+
logging.error(f"Image processing failed: {e}")
|
| 302 |
+
# Clean up on error
|
| 303 |
+
aggressive_cleanup()
|
| 304 |
+
return None, None, None, f"❌ Error: {str(e)}"
|
| 305 |
+
|
| 306 |
+
def create_app() -> gr.Blocks:
|
| 307 |
+
"""Create the Gradio application"""
|
| 308 |
+
|
| 309 |
+
# Get available models
|
| 310 |
+
available_models = get_available_models()
|
| 311 |
+
|
| 312 |
+
if not available_models:
|
| 313 |
+
logging.warning("No model checkpoints found!")
|
| 314 |
+
# Add dummy entries for interface
|
| 315 |
+
available_models = {
|
| 316 |
+
"No models found - please check checkpoints folder": {
|
| 317 |
+
'variant': 'vitl',
|
| 318 |
+
'checkpoint': 'checkpoints/depth_anything_v2_vitl.pth',
|
| 319 |
+
'config': MODEL_CONFIGS['vitl']
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
model_choices = list(available_models.keys())
|
| 324 |
+
default_model = model_choices[0]
|
| 325 |
+
|
| 326 |
+
# Try to find ViT-Large as default if available
|
| 327 |
+
for choice in model_choices:
|
| 328 |
+
if "ViT-Large" in choice:
|
| 329 |
+
default_model = choice
|
| 330 |
+
break
|
| 331 |
+
|
| 332 |
+
title = "# Depth Anything V2 - Enhanced"
|
| 333 |
+
description = """Enhanced demo for **Depth Anything V2** with model selection.
|
| 334 |
+
Please refer to the [paper](https://arxiv.org/abs/2406.09414), [project page](https://depth-anything-v2.github.io), or [github](https://github.com/DepthAnything/Depth-Anything-V2) for more details."""
|
| 335 |
+
|
| 336 |
+
with gr.Blocks(
|
| 337 |
+
css=css,
|
| 338 |
+
title="Depth Anything V2 - Enhanced",
|
| 339 |
+
theme=gr.themes.Soft()
|
| 340 |
+
) as app:
|
| 341 |
+
|
| 342 |
+
gr.Markdown(title)
|
| 343 |
+
gr.Markdown(description)
|
| 344 |
+
|
| 345 |
+
# Instructions section
|
| 346 |
+
with gr.Accordion("📋 Instructions", open=False):
|
| 347 |
+
gr.Markdown("""
|
| 348 |
+
## 🚀 How to Use This Demo
|
| 349 |
+
|
| 350 |
+
1. **Select Model**: Choose the model variant that best fits your needs:
|
| 351 |
+
- **ViT-Small**: Fastest processing, lower quality
|
| 352 |
+
- **ViT-Base**: Balanced speed and quality
|
| 353 |
+
- **ViT-Large**: High quality, recommended for most uses
|
| 354 |
+
- **ViT-Giant**: Highest quality, slowest processing
|
| 355 |
+
|
| 356 |
+
2. **Upload Image**: Upload any image in common formats (JPEG, PNG, etc.)
|
| 357 |
+
|
| 358 |
+
3. **Process**: Click "Compute Depth" to generate the depth map
|
| 359 |
+
|
| 360 |
+
4. **View Results**:
|
| 361 |
+
- Interactive slider to compare original and depth map
|
| 362 |
+
- Download grayscale and raw depth maps
|
| 363 |
+
|
| 364 |
+
### 📊 Model Comparison
|
| 365 |
+
- **Speed**: ViT-S > ViT-B > ViT-L > ViT-G
|
| 366 |
+
- **Quality**: ViT-G > ViT-L > ViT-B > ViT-S
|
| 367 |
+
- **Memory Usage**: ViT-G > ViT-L > ViT-B > ViT-S
|
| 368 |
+
|
| 369 |
+
### 🔧 Technical Notes
|
| 370 |
+
- Models are cached for faster switching
|
| 371 |
+
- GPU acceleration when available
|
| 372 |
+
- Supports various image formats and sizes
|
| 373 |
+
""")
|
| 374 |
+
|
| 375 |
+
# Model selection
|
| 376 |
+
with gr.Row():
|
| 377 |
+
model_selector = gr.Dropdown(
|
| 378 |
+
choices=model_choices,
|
| 379 |
+
value=default_model,
|
| 380 |
+
label="🎯 Select Model Variant",
|
| 381 |
+
info="Choose the Depth Anything V2 model variant",
|
| 382 |
+
interactive=True
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
gr.Markdown("### Depth Prediction Demo")
|
| 386 |
+
|
| 387 |
+
with gr.Row():
|
| 388 |
+
input_image = gr.Image(
|
| 389 |
+
label="Input Image",
|
| 390 |
+
type='numpy',
|
| 391 |
+
elem_id='img-display-input'
|
| 392 |
+
)
|
| 393 |
+
depth_image_slider = ImageSlider(
|
| 394 |
+
label="Depth Map with Slider View",
|
| 395 |
+
elem_id='img-display-output',
|
| 396 |
+
position=0.5
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
submit = gr.Button(
|
| 400 |
+
value="🚀 Compute Depth",
|
| 401 |
+
variant="primary",
|
| 402 |
+
size="lg"
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
with gr.Row():
|
| 406 |
+
gray_depth_file = gr.File(
|
| 407 |
+
label="📥 Grayscale depth map",
|
| 408 |
+
elem_id="download"
|
| 409 |
+
)
|
| 410 |
+
raw_file = gr.File(
|
| 411 |
+
label="📥 16-bit raw output (disparity)",
|
| 412 |
+
elem_id="download"
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
status_text = gr.Textbox(
|
| 416 |
+
label="📊 Processing Status",
|
| 417 |
+
interactive=False,
|
| 418 |
+
lines=6
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# Example images - Paginated
|
| 422 |
+
example_files = glob.glob('assets/examples/*')
|
| 423 |
+
if example_files:
|
| 424 |
+
# Sort files for consistent ordering
|
| 425 |
+
example_files = sorted(example_files)
|
| 426 |
+
|
| 427 |
+
# Show first 8 examples
|
| 428 |
+
page1_examples = example_files[:8] if len(example_files) > 8 else example_files
|
| 429 |
+
gr.Examples(
|
| 430 |
+
examples=[[f] for f in page1_examples],
|
| 431 |
+
inputs=[input_image],
|
| 432 |
+
label=f"📋 Example Images (1-{len(page1_examples)} of {len(example_files)})"
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# Show remaining examples if there are more than 8
|
| 436 |
+
if len(example_files) > 8:
|
| 437 |
+
page2_examples = example_files[8:16] if len(example_files) > 16 else example_files[8:]
|
| 438 |
+
gr.Examples(
|
| 439 |
+
examples=[[f] for f in page2_examples],
|
| 440 |
+
inputs=[input_image],
|
| 441 |
+
label=f"📋 More Examples ({9}-{len(page2_examples)+8} of {len(example_files)})"
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
# Show final batch if there are more than 16
|
| 445 |
+
if len(example_files) > 16:
|
| 446 |
+
page3_examples = example_files[16:]
|
| 447 |
+
gr.Examples(
|
| 448 |
+
examples=[[f] for f in page3_examples],
|
| 449 |
+
inputs=[input_image],
|
| 450 |
+
label=f"📋 Additional Examples ({17}-{len(example_files)} of {len(example_files)})"
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Event handlers
|
| 454 |
+
submit.click(
|
| 455 |
+
fn=process_image,
|
| 456 |
+
inputs=[model_selector, input_image],
|
| 457 |
+
outputs=[depth_image_slider, gray_depth_file, raw_file, status_text],
|
| 458 |
+
show_progress=True
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
# Footer
|
| 462 |
+
with gr.Accordion("📖 Citation & Info", open=False):
|
| 463 |
+
gr.Markdown("""
|
| 464 |
+
### 📄 Citation
|
| 465 |
+
|
| 466 |
+
If you use Depth Anything V2 in your research, please cite:
|
| 467 |
+
|
| 468 |
+
```bibtex
|
| 469 |
+
@article{depth_anything_v2,
|
| 470 |
+
title={Depth Anything V2},
|
| 471 |
+
author={Lihe Yang and Bingyi Kang and Zilong Huang and Zhen Zhao and Xiaogang Xu and Jiashi Feng and Hengshuang Zhao},
|
| 472 |
+
journal={arXiv:2406.09414},
|
| 473 |
+
year={2024}
|
| 474 |
+
}
|
| 475 |
+
```
|
| 476 |
+
|
| 477 |
+
### 🔗 Links
|
| 478 |
+
- [Paper](https://arxiv.org/abs/2406.09414)
|
| 479 |
+
- [Project Page](https://depth-anything-v2.github.io)
|
| 480 |
+
- [GitHub Repository](https://github.com/DepthAnything/Depth-Anything-V2)
|
| 481 |
+
|
| 482 |
+
### ⚡ Performance Notes
|
| 483 |
+
- Enhanced with model caching for faster switching
|
| 484 |
+
- GPU memory optimization
|
| 485 |
+
- Support for multiple model variants
|
| 486 |
+
""")
|
| 487 |
+
|
| 488 |
+
return app
|
| 489 |
+
|
| 490 |
+
def main():
|
| 491 |
+
"""Main function to launch the app"""
|
| 492 |
+
|
| 493 |
+
logging.info("🚀 Starting Enhanced Depth Anything V2 App...")
|
| 494 |
+
|
| 495 |
+
# Check available models
|
| 496 |
+
available_models = get_available_models()
|
| 497 |
+
logging.info(f"Found {len(available_models)} available models")
|
| 498 |
+
|
| 499 |
+
try:
|
| 500 |
+
# Create and launch app
|
| 501 |
+
logging.info("Creating Gradio app...")
|
| 502 |
+
app = create_app()
|
| 503 |
+
logging.info("✅ Gradio app created successfully")
|
| 504 |
+
|
| 505 |
+
# Launch app
|
| 506 |
+
app.queue().launch(
|
| 507 |
+
share=False,
|
| 508 |
+
show_error=True
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
except Exception as e:
|
| 512 |
+
logging.error(f"Failed to launch app: {e}")
|
| 513 |
+
raise
|
| 514 |
+
|
| 515 |
+
if __name__ == "__main__":
|
| 516 |
+
main()
|
Depth-Anything-V2/assets/examples/demo01.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo02.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo03.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo04.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo05.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo06.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo07.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo08.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo09.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo10.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo11.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo12.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo13.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo14.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo15.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo16.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo17.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo18.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo19.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/assets/examples/demo20.jpg
ADDED
|
Git LFS Details
|
Depth-Anything-V2/depth_anything_v2/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Depth Anything v2 module
|
Depth-Anything-V2/depth_anything_v2/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (211 Bytes). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/__pycache__/dinov2.cpython-311.pyc
ADDED
|
Binary file (21.8 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/__pycache__/dpt.cpython-311.pyc
ADDED
|
Binary file (11.8 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
#
|
| 3 |
+
# This source code is licensed under the Apache License, Version 2.0
|
| 4 |
+
# found in the LICENSE file in the root directory of this source tree.
|
| 5 |
+
|
| 6 |
+
# References:
|
| 7 |
+
# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
|
| 8 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
|
| 9 |
+
|
| 10 |
+
from functools import partial
|
| 11 |
+
import math
|
| 12 |
+
import logging
|
| 13 |
+
from typing import Sequence, Tuple, Union, Callable
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.utils.checkpoint
|
| 18 |
+
from torch.nn.init import trunc_normal_
|
| 19 |
+
|
| 20 |
+
from .dinov2_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger("dinov2")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
|
| 27 |
+
if not depth_first and include_root:
|
| 28 |
+
fn(module=module, name=name)
|
| 29 |
+
for child_name, child_module in module.named_children():
|
| 30 |
+
child_name = ".".join((name, child_name)) if name else child_name
|
| 31 |
+
named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
|
| 32 |
+
if depth_first and include_root:
|
| 33 |
+
fn(module=module, name=name)
|
| 34 |
+
return module
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class BlockChunk(nn.ModuleList):
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
for b in self:
|
| 40 |
+
x = b(x)
|
| 41 |
+
return x
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DinoVisionTransformer(nn.Module):
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
img_size=224,
|
| 48 |
+
patch_size=16,
|
| 49 |
+
in_chans=3,
|
| 50 |
+
embed_dim=768,
|
| 51 |
+
depth=12,
|
| 52 |
+
num_heads=12,
|
| 53 |
+
mlp_ratio=4.0,
|
| 54 |
+
qkv_bias=True,
|
| 55 |
+
ffn_bias=True,
|
| 56 |
+
proj_bias=True,
|
| 57 |
+
drop_path_rate=0.0,
|
| 58 |
+
drop_path_uniform=False,
|
| 59 |
+
init_values=None, # for layerscale: None or 0 => no layerscale
|
| 60 |
+
embed_layer=PatchEmbed,
|
| 61 |
+
act_layer=nn.GELU,
|
| 62 |
+
block_fn=Block,
|
| 63 |
+
ffn_layer="mlp",
|
| 64 |
+
block_chunks=1,
|
| 65 |
+
num_register_tokens=0,
|
| 66 |
+
interpolate_antialias=False,
|
| 67 |
+
interpolate_offset=0.1,
|
| 68 |
+
):
|
| 69 |
+
"""
|
| 70 |
+
Args:
|
| 71 |
+
img_size (int, tuple): input image size
|
| 72 |
+
patch_size (int, tuple): patch size
|
| 73 |
+
in_chans (int): number of input channels
|
| 74 |
+
embed_dim (int): embedding dimension
|
| 75 |
+
depth (int): depth of transformer
|
| 76 |
+
num_heads (int): number of attention heads
|
| 77 |
+
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
|
| 78 |
+
qkv_bias (bool): enable bias for qkv if True
|
| 79 |
+
proj_bias (bool): enable bias for proj in attn if True
|
| 80 |
+
ffn_bias (bool): enable bias for ffn if True
|
| 81 |
+
drop_path_rate (float): stochastic depth rate
|
| 82 |
+
drop_path_uniform (bool): apply uniform drop rate across blocks
|
| 83 |
+
weight_init (str): weight init scheme
|
| 84 |
+
init_values (float): layer-scale init values
|
| 85 |
+
embed_layer (nn.Module): patch embedding layer
|
| 86 |
+
act_layer (nn.Module): MLP activation layer
|
| 87 |
+
block_fn (nn.Module): transformer block class
|
| 88 |
+
ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
|
| 89 |
+
block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
|
| 90 |
+
num_register_tokens: (int) number of extra cls tokens (so-called "registers")
|
| 91 |
+
interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
|
| 92 |
+
interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
|
| 93 |
+
"""
|
| 94 |
+
super().__init__()
|
| 95 |
+
norm_layer = partial(nn.LayerNorm, eps=1e-6)
|
| 96 |
+
|
| 97 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
| 98 |
+
self.num_tokens = 1
|
| 99 |
+
self.n_blocks = depth
|
| 100 |
+
self.num_heads = num_heads
|
| 101 |
+
self.patch_size = patch_size
|
| 102 |
+
self.num_register_tokens = num_register_tokens
|
| 103 |
+
self.interpolate_antialias = interpolate_antialias
|
| 104 |
+
self.interpolate_offset = interpolate_offset
|
| 105 |
+
|
| 106 |
+
self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
|
| 107 |
+
num_patches = self.patch_embed.num_patches
|
| 108 |
+
|
| 109 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
| 110 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
|
| 111 |
+
assert num_register_tokens >= 0
|
| 112 |
+
self.register_tokens = (
|
| 113 |
+
nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if drop_path_uniform is True:
|
| 117 |
+
dpr = [drop_path_rate] * depth
|
| 118 |
+
else:
|
| 119 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
| 120 |
+
|
| 121 |
+
if ffn_layer == "mlp":
|
| 122 |
+
logger.info("using MLP layer as FFN")
|
| 123 |
+
ffn_layer = Mlp
|
| 124 |
+
elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
|
| 125 |
+
logger.info("using SwiGLU layer as FFN")
|
| 126 |
+
ffn_layer = SwiGLUFFNFused
|
| 127 |
+
elif ffn_layer == "identity":
|
| 128 |
+
logger.info("using Identity layer as FFN")
|
| 129 |
+
|
| 130 |
+
def f(*args, **kwargs):
|
| 131 |
+
return nn.Identity()
|
| 132 |
+
|
| 133 |
+
ffn_layer = f
|
| 134 |
+
else:
|
| 135 |
+
raise NotImplementedError
|
| 136 |
+
|
| 137 |
+
blocks_list = [
|
| 138 |
+
block_fn(
|
| 139 |
+
dim=embed_dim,
|
| 140 |
+
num_heads=num_heads,
|
| 141 |
+
mlp_ratio=mlp_ratio,
|
| 142 |
+
qkv_bias=qkv_bias,
|
| 143 |
+
proj_bias=proj_bias,
|
| 144 |
+
ffn_bias=ffn_bias,
|
| 145 |
+
drop_path=dpr[i],
|
| 146 |
+
norm_layer=norm_layer,
|
| 147 |
+
act_layer=act_layer,
|
| 148 |
+
ffn_layer=ffn_layer,
|
| 149 |
+
init_values=init_values,
|
| 150 |
+
)
|
| 151 |
+
for i in range(depth)
|
| 152 |
+
]
|
| 153 |
+
if block_chunks > 0:
|
| 154 |
+
self.chunked_blocks = True
|
| 155 |
+
chunked_blocks = []
|
| 156 |
+
chunksize = depth // block_chunks
|
| 157 |
+
for i in range(0, depth, chunksize):
|
| 158 |
+
# this is to keep the block index consistent if we chunk the block list
|
| 159 |
+
chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
|
| 160 |
+
self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
|
| 161 |
+
else:
|
| 162 |
+
self.chunked_blocks = False
|
| 163 |
+
self.blocks = nn.ModuleList(blocks_list)
|
| 164 |
+
|
| 165 |
+
self.norm = norm_layer(embed_dim)
|
| 166 |
+
self.head = nn.Identity()
|
| 167 |
+
|
| 168 |
+
self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
|
| 169 |
+
|
| 170 |
+
self.init_weights()
|
| 171 |
+
|
| 172 |
+
def init_weights(self):
|
| 173 |
+
trunc_normal_(self.pos_embed, std=0.02)
|
| 174 |
+
nn.init.normal_(self.cls_token, std=1e-6)
|
| 175 |
+
if self.register_tokens is not None:
|
| 176 |
+
nn.init.normal_(self.register_tokens, std=1e-6)
|
| 177 |
+
named_apply(init_weights_vit_timm, self)
|
| 178 |
+
|
| 179 |
+
def interpolate_pos_encoding(self, x, w, h):
|
| 180 |
+
previous_dtype = x.dtype
|
| 181 |
+
npatch = x.shape[1] - 1
|
| 182 |
+
N = self.pos_embed.shape[1] - 1
|
| 183 |
+
if npatch == N and w == h:
|
| 184 |
+
return self.pos_embed
|
| 185 |
+
pos_embed = self.pos_embed.float()
|
| 186 |
+
class_pos_embed = pos_embed[:, 0]
|
| 187 |
+
patch_pos_embed = pos_embed[:, 1:]
|
| 188 |
+
dim = x.shape[-1]
|
| 189 |
+
w0 = w // self.patch_size
|
| 190 |
+
h0 = h // self.patch_size
|
| 191 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 192 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 193 |
+
# DINOv2 with register modify the interpolate_offset from 0.1 to 0.0
|
| 194 |
+
w0, h0 = w0 + self.interpolate_offset, h0 + self.interpolate_offset
|
| 195 |
+
# w0, h0 = w0 + 0.1, h0 + 0.1
|
| 196 |
+
|
| 197 |
+
sqrt_N = math.sqrt(N)
|
| 198 |
+
sx, sy = float(w0) / sqrt_N, float(h0) / sqrt_N
|
| 199 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 200 |
+
patch_pos_embed.reshape(1, int(sqrt_N), int(sqrt_N), dim).permute(0, 3, 1, 2),
|
| 201 |
+
scale_factor=(sx, sy),
|
| 202 |
+
# (int(w0), int(h0)), # to solve the upsampling shape issue
|
| 203 |
+
mode="bicubic",
|
| 204 |
+
antialias=self.interpolate_antialias
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
assert int(w0) == patch_pos_embed.shape[-2]
|
| 208 |
+
assert int(h0) == patch_pos_embed.shape[-1]
|
| 209 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 210 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
|
| 211 |
+
|
| 212 |
+
def prepare_tokens_with_masks(self, x, masks=None):
|
| 213 |
+
B, nc, w, h = x.shape
|
| 214 |
+
x = self.patch_embed(x)
|
| 215 |
+
if masks is not None:
|
| 216 |
+
x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
|
| 217 |
+
|
| 218 |
+
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
|
| 219 |
+
x = x + self.interpolate_pos_encoding(x, w, h)
|
| 220 |
+
|
| 221 |
+
if self.register_tokens is not None:
|
| 222 |
+
x = torch.cat(
|
| 223 |
+
(
|
| 224 |
+
x[:, :1],
|
| 225 |
+
self.register_tokens.expand(x.shape[0], -1, -1),
|
| 226 |
+
x[:, 1:],
|
| 227 |
+
),
|
| 228 |
+
dim=1,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
return x
|
| 232 |
+
|
| 233 |
+
def forward_features_list(self, x_list, masks_list):
|
| 234 |
+
x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
|
| 235 |
+
for blk in self.blocks:
|
| 236 |
+
x = blk(x)
|
| 237 |
+
|
| 238 |
+
all_x = x
|
| 239 |
+
output = []
|
| 240 |
+
for x, masks in zip(all_x, masks_list):
|
| 241 |
+
x_norm = self.norm(x)
|
| 242 |
+
output.append(
|
| 243 |
+
{
|
| 244 |
+
"x_norm_clstoken": x_norm[:, 0],
|
| 245 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
| 246 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
| 247 |
+
"x_prenorm": x,
|
| 248 |
+
"masks": masks,
|
| 249 |
+
}
|
| 250 |
+
)
|
| 251 |
+
return output
|
| 252 |
+
|
| 253 |
+
def forward_features(self, x, masks=None):
|
| 254 |
+
if isinstance(x, list):
|
| 255 |
+
return self.forward_features_list(x, masks)
|
| 256 |
+
|
| 257 |
+
x = self.prepare_tokens_with_masks(x, masks)
|
| 258 |
+
|
| 259 |
+
for blk in self.blocks:
|
| 260 |
+
x = blk(x)
|
| 261 |
+
|
| 262 |
+
x_norm = self.norm(x)
|
| 263 |
+
return {
|
| 264 |
+
"x_norm_clstoken": x_norm[:, 0],
|
| 265 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
| 266 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
| 267 |
+
"x_prenorm": x,
|
| 268 |
+
"masks": masks,
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
def _get_intermediate_layers_not_chunked(self, x, n=1):
|
| 272 |
+
x = self.prepare_tokens_with_masks(x)
|
| 273 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
| 274 |
+
output, total_block_len = [], len(self.blocks)
|
| 275 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 276 |
+
for i, blk in enumerate(self.blocks):
|
| 277 |
+
x = blk(x)
|
| 278 |
+
if i in blocks_to_take:
|
| 279 |
+
output.append(x)
|
| 280 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 281 |
+
return output
|
| 282 |
+
|
| 283 |
+
def _get_intermediate_layers_chunked(self, x, n=1):
|
| 284 |
+
x = self.prepare_tokens_with_masks(x)
|
| 285 |
+
output, i, total_block_len = [], 0, len(self.blocks[-1])
|
| 286 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
| 287 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
| 288 |
+
for block_chunk in self.blocks:
|
| 289 |
+
for blk in block_chunk[i:]: # Passing the nn.Identity()
|
| 290 |
+
x = blk(x)
|
| 291 |
+
if i in blocks_to_take:
|
| 292 |
+
output.append(x)
|
| 293 |
+
i += 1
|
| 294 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
| 295 |
+
return output
|
| 296 |
+
|
| 297 |
+
def get_intermediate_layers(
|
| 298 |
+
self,
|
| 299 |
+
x: torch.Tensor,
|
| 300 |
+
n: Union[int, Sequence] = 1, # Layers or n last layers to take
|
| 301 |
+
reshape: bool = False,
|
| 302 |
+
return_class_token: bool = False,
|
| 303 |
+
norm=True
|
| 304 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
|
| 305 |
+
if self.chunked_blocks:
|
| 306 |
+
outputs = self._get_intermediate_layers_chunked(x, n)
|
| 307 |
+
else:
|
| 308 |
+
outputs = self._get_intermediate_layers_not_chunked(x, n)
|
| 309 |
+
if norm:
|
| 310 |
+
outputs = [self.norm(out) for out in outputs]
|
| 311 |
+
class_tokens = [out[:, 0] for out in outputs]
|
| 312 |
+
outputs = [out[:, 1 + self.num_register_tokens:] for out in outputs]
|
| 313 |
+
if reshape:
|
| 314 |
+
B, _, w, h = x.shape
|
| 315 |
+
outputs = [
|
| 316 |
+
out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
|
| 317 |
+
for out in outputs
|
| 318 |
+
]
|
| 319 |
+
if return_class_token:
|
| 320 |
+
return tuple(zip(outputs, class_tokens))
|
| 321 |
+
return tuple(outputs)
|
| 322 |
+
|
| 323 |
+
def forward(self, *args, is_training=False, **kwargs):
|
| 324 |
+
ret = self.forward_features(*args, **kwargs)
|
| 325 |
+
if is_training:
|
| 326 |
+
return ret
|
| 327 |
+
else:
|
| 328 |
+
return self.head(ret["x_norm_clstoken"])
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def init_weights_vit_timm(module: nn.Module, name: str = ""):
|
| 332 |
+
"""ViT weight initialization, original timm impl (for reproducibility)"""
|
| 333 |
+
if isinstance(module, nn.Linear):
|
| 334 |
+
trunc_normal_(module.weight, std=0.02)
|
| 335 |
+
if module.bias is not None:
|
| 336 |
+
nn.init.zeros_(module.bias)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
|
| 340 |
+
model = DinoVisionTransformer(
|
| 341 |
+
patch_size=patch_size,
|
| 342 |
+
embed_dim=384,
|
| 343 |
+
depth=12,
|
| 344 |
+
num_heads=6,
|
| 345 |
+
mlp_ratio=4,
|
| 346 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 347 |
+
num_register_tokens=num_register_tokens,
|
| 348 |
+
**kwargs,
|
| 349 |
+
)
|
| 350 |
+
return model
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
|
| 354 |
+
model = DinoVisionTransformer(
|
| 355 |
+
patch_size=patch_size,
|
| 356 |
+
embed_dim=768,
|
| 357 |
+
depth=12,
|
| 358 |
+
num_heads=12,
|
| 359 |
+
mlp_ratio=4,
|
| 360 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 361 |
+
num_register_tokens=num_register_tokens,
|
| 362 |
+
**kwargs,
|
| 363 |
+
)
|
| 364 |
+
return model
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
|
| 368 |
+
model = DinoVisionTransformer(
|
| 369 |
+
patch_size=patch_size,
|
| 370 |
+
embed_dim=1024,
|
| 371 |
+
depth=24,
|
| 372 |
+
num_heads=16,
|
| 373 |
+
mlp_ratio=4,
|
| 374 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 375 |
+
num_register_tokens=num_register_tokens,
|
| 376 |
+
**kwargs,
|
| 377 |
+
)
|
| 378 |
+
return model
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
|
| 382 |
+
"""
|
| 383 |
+
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
|
| 384 |
+
"""
|
| 385 |
+
model = DinoVisionTransformer(
|
| 386 |
+
patch_size=patch_size,
|
| 387 |
+
embed_dim=1536,
|
| 388 |
+
depth=40,
|
| 389 |
+
num_heads=24,
|
| 390 |
+
mlp_ratio=4,
|
| 391 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
| 392 |
+
num_register_tokens=num_register_tokens,
|
| 393 |
+
**kwargs,
|
| 394 |
+
)
|
| 395 |
+
return model
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def DINOv2(model_name):
|
| 399 |
+
model_zoo = {
|
| 400 |
+
"vits": vit_small,
|
| 401 |
+
"vitb": vit_base,
|
| 402 |
+
"vitl": vit_large,
|
| 403 |
+
"vitg": vit_giant2
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
return model_zoo[model_name](
|
| 407 |
+
img_size=518,
|
| 408 |
+
patch_size=14,
|
| 409 |
+
init_values=1.0,
|
| 410 |
+
ffn_layer="mlp" if model_name != "vitg" else "swiglufused",
|
| 411 |
+
block_chunks=0,
|
| 412 |
+
num_register_tokens=0,
|
| 413 |
+
interpolate_antialias=False,
|
| 414 |
+
interpolate_offset=0.1
|
| 415 |
+
)
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from .mlp import Mlp
|
| 8 |
+
from .patch_embed import PatchEmbed
|
| 9 |
+
from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused
|
| 10 |
+
from .block import NestedTensorBlock
|
| 11 |
+
from .attention import MemEffAttention
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (525 Bytes). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/attention.cpython-311.pyc
ADDED
|
Binary file (4.48 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/block.cpython-311.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/drop_path.cpython-311.pyc
ADDED
|
Binary file (1.87 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/layer_scale.cpython-311.pyc
ADDED
|
Binary file (1.63 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/mlp.cpython-311.pyc
ADDED
|
Binary file (2.09 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/patch_embed.cpython-311.pyc
ADDED
|
Binary file (4.46 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/__pycache__/swiglu_ffn.cpython-311.pyc
ADDED
|
Binary file (3.31 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/attention.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
from torch import Tensor
|
| 14 |
+
from torch import nn
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("dinov2")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
from xformers.ops import memory_efficient_attention, unbind, fmha
|
| 22 |
+
|
| 23 |
+
XFORMERS_AVAILABLE = True
|
| 24 |
+
except ImportError:
|
| 25 |
+
logger.warning("xFormers not available")
|
| 26 |
+
XFORMERS_AVAILABLE = False
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Attention(nn.Module):
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
dim: int,
|
| 33 |
+
num_heads: int = 8,
|
| 34 |
+
qkv_bias: bool = False,
|
| 35 |
+
proj_bias: bool = True,
|
| 36 |
+
attn_drop: float = 0.0,
|
| 37 |
+
proj_drop: float = 0.0,
|
| 38 |
+
) -> None:
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.num_heads = num_heads
|
| 41 |
+
head_dim = dim // num_heads
|
| 42 |
+
self.scale = head_dim**-0.5
|
| 43 |
+
|
| 44 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
| 45 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
| 46 |
+
self.proj = nn.Linear(dim, dim, bias=proj_bias)
|
| 47 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
| 48 |
+
|
| 49 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 50 |
+
B, N, C = x.shape
|
| 51 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 52 |
+
|
| 53 |
+
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
|
| 54 |
+
attn = q @ k.transpose(-2, -1)
|
| 55 |
+
|
| 56 |
+
attn = attn.softmax(dim=-1)
|
| 57 |
+
attn = self.attn_drop(attn)
|
| 58 |
+
|
| 59 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
|
| 60 |
+
x = self.proj(x)
|
| 61 |
+
x = self.proj_drop(x)
|
| 62 |
+
return x
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class MemEffAttention(Attention):
|
| 66 |
+
def forward(self, x: Tensor, attn_bias=None) -> Tensor:
|
| 67 |
+
if not XFORMERS_AVAILABLE:
|
| 68 |
+
assert attn_bias is None, "xFormers is required for nested tensors usage"
|
| 69 |
+
return super().forward(x)
|
| 70 |
+
|
| 71 |
+
B, N, C = x.shape
|
| 72 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
| 73 |
+
|
| 74 |
+
q, k, v = unbind(qkv, 2)
|
| 75 |
+
|
| 76 |
+
x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
|
| 77 |
+
x = x.reshape([B, N, C])
|
| 78 |
+
|
| 79 |
+
x = self.proj(x)
|
| 80 |
+
x = self.proj_drop(x)
|
| 81 |
+
return x
|
| 82 |
+
|
| 83 |
+
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/block.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
from typing import Callable, List, Any, Tuple, Dict
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from torch import nn, Tensor
|
| 16 |
+
|
| 17 |
+
from .attention import Attention, MemEffAttention
|
| 18 |
+
from .drop_path import DropPath
|
| 19 |
+
from .layer_scale import LayerScale
|
| 20 |
+
from .mlp import Mlp
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger("dinov2")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from xformers.ops import fmha
|
| 28 |
+
from xformers.ops import scaled_index_add, index_select_cat
|
| 29 |
+
|
| 30 |
+
XFORMERS_AVAILABLE = True
|
| 31 |
+
except ImportError:
|
| 32 |
+
logger.warning("xFormers not available")
|
| 33 |
+
XFORMERS_AVAILABLE = False
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Block(nn.Module):
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
dim: int,
|
| 40 |
+
num_heads: int,
|
| 41 |
+
mlp_ratio: float = 4.0,
|
| 42 |
+
qkv_bias: bool = False,
|
| 43 |
+
proj_bias: bool = True,
|
| 44 |
+
ffn_bias: bool = True,
|
| 45 |
+
drop: float = 0.0,
|
| 46 |
+
attn_drop: float = 0.0,
|
| 47 |
+
init_values=None,
|
| 48 |
+
drop_path: float = 0.0,
|
| 49 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 50 |
+
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
|
| 51 |
+
attn_class: Callable[..., nn.Module] = Attention,
|
| 52 |
+
ffn_layer: Callable[..., nn.Module] = Mlp,
|
| 53 |
+
) -> None:
|
| 54 |
+
super().__init__()
|
| 55 |
+
# print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
|
| 56 |
+
self.norm1 = norm_layer(dim)
|
| 57 |
+
self.attn = attn_class(
|
| 58 |
+
dim,
|
| 59 |
+
num_heads=num_heads,
|
| 60 |
+
qkv_bias=qkv_bias,
|
| 61 |
+
proj_bias=proj_bias,
|
| 62 |
+
attn_drop=attn_drop,
|
| 63 |
+
proj_drop=drop,
|
| 64 |
+
)
|
| 65 |
+
self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
| 66 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 67 |
+
|
| 68 |
+
self.norm2 = norm_layer(dim)
|
| 69 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
| 70 |
+
self.mlp = ffn_layer(
|
| 71 |
+
in_features=dim,
|
| 72 |
+
hidden_features=mlp_hidden_dim,
|
| 73 |
+
act_layer=act_layer,
|
| 74 |
+
drop=drop,
|
| 75 |
+
bias=ffn_bias,
|
| 76 |
+
)
|
| 77 |
+
self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
| 78 |
+
self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 79 |
+
|
| 80 |
+
self.sample_drop_ratio = drop_path
|
| 81 |
+
|
| 82 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 83 |
+
def attn_residual_func(x: Tensor) -> Tensor:
|
| 84 |
+
return self.ls1(self.attn(self.norm1(x)))
|
| 85 |
+
|
| 86 |
+
def ffn_residual_func(x: Tensor) -> Tensor:
|
| 87 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
| 88 |
+
|
| 89 |
+
if self.training and self.sample_drop_ratio > 0.1:
|
| 90 |
+
# the overhead is compensated only for a drop path rate larger than 0.1
|
| 91 |
+
x = drop_add_residual_stochastic_depth(
|
| 92 |
+
x,
|
| 93 |
+
residual_func=attn_residual_func,
|
| 94 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 95 |
+
)
|
| 96 |
+
x = drop_add_residual_stochastic_depth(
|
| 97 |
+
x,
|
| 98 |
+
residual_func=ffn_residual_func,
|
| 99 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 100 |
+
)
|
| 101 |
+
elif self.training and self.sample_drop_ratio > 0.0:
|
| 102 |
+
x = x + self.drop_path1(attn_residual_func(x))
|
| 103 |
+
x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
|
| 104 |
+
else:
|
| 105 |
+
x = x + attn_residual_func(x)
|
| 106 |
+
x = x + ffn_residual_func(x)
|
| 107 |
+
return x
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def drop_add_residual_stochastic_depth(
|
| 111 |
+
x: Tensor,
|
| 112 |
+
residual_func: Callable[[Tensor], Tensor],
|
| 113 |
+
sample_drop_ratio: float = 0.0,
|
| 114 |
+
) -> Tensor:
|
| 115 |
+
# 1) extract subset using permutation
|
| 116 |
+
b, n, d = x.shape
|
| 117 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
| 118 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 119 |
+
x_subset = x[brange]
|
| 120 |
+
|
| 121 |
+
# 2) apply residual_func to get residual
|
| 122 |
+
residual = residual_func(x_subset)
|
| 123 |
+
|
| 124 |
+
x_flat = x.flatten(1)
|
| 125 |
+
residual = residual.flatten(1)
|
| 126 |
+
|
| 127 |
+
residual_scale_factor = b / sample_subset_size
|
| 128 |
+
|
| 129 |
+
# 3) add the residual
|
| 130 |
+
x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
|
| 131 |
+
return x_plus_residual.view_as(x)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def get_branges_scales(x, sample_drop_ratio=0.0):
|
| 135 |
+
b, n, d = x.shape
|
| 136 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
| 137 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
| 138 |
+
residual_scale_factor = b / sample_subset_size
|
| 139 |
+
return brange, residual_scale_factor
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
|
| 143 |
+
if scaling_vector is None:
|
| 144 |
+
x_flat = x.flatten(1)
|
| 145 |
+
residual = residual.flatten(1)
|
| 146 |
+
x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
|
| 147 |
+
else:
|
| 148 |
+
x_plus_residual = scaled_index_add(
|
| 149 |
+
x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
|
| 150 |
+
)
|
| 151 |
+
return x_plus_residual
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
attn_bias_cache: Dict[Tuple, Any] = {}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def get_attn_bias_and_cat(x_list, branges=None):
|
| 158 |
+
"""
|
| 159 |
+
this will perform the index select, cat the tensors, and provide the attn_bias from cache
|
| 160 |
+
"""
|
| 161 |
+
batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
|
| 162 |
+
all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
|
| 163 |
+
if all_shapes not in attn_bias_cache.keys():
|
| 164 |
+
seqlens = []
|
| 165 |
+
for b, x in zip(batch_sizes, x_list):
|
| 166 |
+
for _ in range(b):
|
| 167 |
+
seqlens.append(x.shape[1])
|
| 168 |
+
attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
|
| 169 |
+
attn_bias._batch_sizes = batch_sizes
|
| 170 |
+
attn_bias_cache[all_shapes] = attn_bias
|
| 171 |
+
|
| 172 |
+
if branges is not None:
|
| 173 |
+
cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
|
| 174 |
+
else:
|
| 175 |
+
tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
|
| 176 |
+
cat_tensors = torch.cat(tensors_bs1, dim=1)
|
| 177 |
+
|
| 178 |
+
return attn_bias_cache[all_shapes], cat_tensors
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def drop_add_residual_stochastic_depth_list(
|
| 182 |
+
x_list: List[Tensor],
|
| 183 |
+
residual_func: Callable[[Tensor, Any], Tensor],
|
| 184 |
+
sample_drop_ratio: float = 0.0,
|
| 185 |
+
scaling_vector=None,
|
| 186 |
+
) -> Tensor:
|
| 187 |
+
# 1) generate random set of indices for dropping samples in the batch
|
| 188 |
+
branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
|
| 189 |
+
branges = [s[0] for s in branges_scales]
|
| 190 |
+
residual_scale_factors = [s[1] for s in branges_scales]
|
| 191 |
+
|
| 192 |
+
# 2) get attention bias and index+concat the tensors
|
| 193 |
+
attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
|
| 194 |
+
|
| 195 |
+
# 3) apply residual_func to get residual, and split the result
|
| 196 |
+
residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
|
| 197 |
+
|
| 198 |
+
outputs = []
|
| 199 |
+
for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
|
| 200 |
+
outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
|
| 201 |
+
return outputs
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class NestedTensorBlock(Block):
|
| 205 |
+
def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
|
| 206 |
+
"""
|
| 207 |
+
x_list contains a list of tensors to nest together and run
|
| 208 |
+
"""
|
| 209 |
+
assert isinstance(self.attn, MemEffAttention)
|
| 210 |
+
|
| 211 |
+
if self.training and self.sample_drop_ratio > 0.0:
|
| 212 |
+
|
| 213 |
+
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 214 |
+
return self.attn(self.norm1(x), attn_bias=attn_bias)
|
| 215 |
+
|
| 216 |
+
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 217 |
+
return self.mlp(self.norm2(x))
|
| 218 |
+
|
| 219 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
| 220 |
+
x_list,
|
| 221 |
+
residual_func=attn_residual_func,
|
| 222 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 223 |
+
scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None,
|
| 224 |
+
)
|
| 225 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
| 226 |
+
x_list,
|
| 227 |
+
residual_func=ffn_residual_func,
|
| 228 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
| 229 |
+
scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None,
|
| 230 |
+
)
|
| 231 |
+
return x_list
|
| 232 |
+
else:
|
| 233 |
+
|
| 234 |
+
def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 235 |
+
return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
|
| 236 |
+
|
| 237 |
+
def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
|
| 238 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
| 239 |
+
|
| 240 |
+
attn_bias, x = get_attn_bias_and_cat(x_list)
|
| 241 |
+
x = x + attn_residual_func(x, attn_bias=attn_bias)
|
| 242 |
+
x = x + ffn_residual_func(x)
|
| 243 |
+
return attn_bias.split(x)
|
| 244 |
+
|
| 245 |
+
def forward(self, x_or_x_list):
|
| 246 |
+
if isinstance(x_or_x_list, Tensor):
|
| 247 |
+
return super().forward(x_or_x_list)
|
| 248 |
+
elif isinstance(x_or_x_list, list):
|
| 249 |
+
assert XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage"
|
| 250 |
+
return self.forward_nested(x_or_x_list)
|
| 251 |
+
else:
|
| 252 |
+
raise AssertionError
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/drop_path.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from torch import nn
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def drop_path(x, drop_prob: float = 0.0, training: bool = False):
|
| 16 |
+
if drop_prob == 0.0 or not training:
|
| 17 |
+
return x
|
| 18 |
+
keep_prob = 1 - drop_prob
|
| 19 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 20 |
+
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
|
| 21 |
+
if keep_prob > 0.0:
|
| 22 |
+
random_tensor.div_(keep_prob)
|
| 23 |
+
output = x * random_tensor
|
| 24 |
+
return output
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DropPath(nn.Module):
|
| 28 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 29 |
+
|
| 30 |
+
def __init__(self, drop_prob=None):
|
| 31 |
+
super(DropPath, self).__init__()
|
| 32 |
+
self.drop_prob = drop_prob
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
return drop_path(x, self.drop_prob, self.training)
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/layer_scale.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
|
| 8 |
+
|
| 9 |
+
from typing import Union
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import Tensor
|
| 13 |
+
from torch import nn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class LayerScale(nn.Module):
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
dim: int,
|
| 20 |
+
init_values: Union[float, Tensor] = 1e-5,
|
| 21 |
+
inplace: bool = False,
|
| 22 |
+
) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.inplace = inplace
|
| 25 |
+
self.gamma = nn.Parameter(init_values * torch.ones(dim))
|
| 26 |
+
|
| 27 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 28 |
+
return x.mul_(self.gamma) if self.inplace else x * self.gamma
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/mlp.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from typing import Callable, Optional
|
| 13 |
+
|
| 14 |
+
from torch import Tensor, nn
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Mlp(nn.Module):
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
in_features: int,
|
| 21 |
+
hidden_features: Optional[int] = None,
|
| 22 |
+
out_features: Optional[int] = None,
|
| 23 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
| 24 |
+
drop: float = 0.0,
|
| 25 |
+
bias: bool = True,
|
| 26 |
+
) -> None:
|
| 27 |
+
super().__init__()
|
| 28 |
+
out_features = out_features or in_features
|
| 29 |
+
hidden_features = hidden_features or in_features
|
| 30 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
|
| 31 |
+
self.act = act_layer()
|
| 32 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 33 |
+
self.drop = nn.Dropout(drop)
|
| 34 |
+
|
| 35 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 36 |
+
x = self.fc1(x)
|
| 37 |
+
x = self.act(x)
|
| 38 |
+
x = self.drop(x)
|
| 39 |
+
x = self.fc2(x)
|
| 40 |
+
x = self.drop(x)
|
| 41 |
+
return x
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/patch_embed.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# References:
|
| 8 |
+
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
|
| 9 |
+
# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
|
| 10 |
+
|
| 11 |
+
from typing import Callable, Optional, Tuple, Union
|
| 12 |
+
|
| 13 |
+
from torch import Tensor
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def make_2tuple(x):
|
| 18 |
+
if isinstance(x, tuple):
|
| 19 |
+
assert len(x) == 2
|
| 20 |
+
return x
|
| 21 |
+
|
| 22 |
+
assert isinstance(x, int)
|
| 23 |
+
return (x, x)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PatchEmbed(nn.Module):
|
| 27 |
+
"""
|
| 28 |
+
2D image to patch embedding: (B,C,H,W) -> (B,N,D)
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
img_size: Image size.
|
| 32 |
+
patch_size: Patch token size.
|
| 33 |
+
in_chans: Number of input image channels.
|
| 34 |
+
embed_dim: Number of linear projection output channels.
|
| 35 |
+
norm_layer: Normalization layer.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
img_size: Union[int, Tuple[int, int]] = 224,
|
| 41 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
| 42 |
+
in_chans: int = 3,
|
| 43 |
+
embed_dim: int = 768,
|
| 44 |
+
norm_layer: Optional[Callable] = None,
|
| 45 |
+
flatten_embedding: bool = True,
|
| 46 |
+
) -> None:
|
| 47 |
+
super().__init__()
|
| 48 |
+
|
| 49 |
+
image_HW = make_2tuple(img_size)
|
| 50 |
+
patch_HW = make_2tuple(patch_size)
|
| 51 |
+
patch_grid_size = (
|
| 52 |
+
image_HW[0] // patch_HW[0],
|
| 53 |
+
image_HW[1] // patch_HW[1],
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
self.img_size = image_HW
|
| 57 |
+
self.patch_size = patch_HW
|
| 58 |
+
self.patches_resolution = patch_grid_size
|
| 59 |
+
self.num_patches = patch_grid_size[0] * patch_grid_size[1]
|
| 60 |
+
|
| 61 |
+
self.in_chans = in_chans
|
| 62 |
+
self.embed_dim = embed_dim
|
| 63 |
+
|
| 64 |
+
self.flatten_embedding = flatten_embedding
|
| 65 |
+
|
| 66 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
|
| 67 |
+
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
|
| 68 |
+
|
| 69 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 70 |
+
_, _, H, W = x.shape
|
| 71 |
+
patch_H, patch_W = self.patch_size
|
| 72 |
+
|
| 73 |
+
assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
|
| 74 |
+
assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
|
| 75 |
+
|
| 76 |
+
x = self.proj(x) # B C H W
|
| 77 |
+
H, W = x.size(2), x.size(3)
|
| 78 |
+
x = x.flatten(2).transpose(1, 2) # B HW C
|
| 79 |
+
x = self.norm(x)
|
| 80 |
+
if not self.flatten_embedding:
|
| 81 |
+
x = x.reshape(-1, H, W, self.embed_dim) # B H W C
|
| 82 |
+
return x
|
| 83 |
+
|
| 84 |
+
def flops(self) -> float:
|
| 85 |
+
Ho, Wo = self.patches_resolution
|
| 86 |
+
flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
|
| 87 |
+
if self.norm is not None:
|
| 88 |
+
flops += Ho * Wo * self.embed_dim
|
| 89 |
+
return flops
|
Depth-Anything-V2/depth_anything_v2/dinov2_layers/swiglu_ffn.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from typing import Callable, Optional
|
| 8 |
+
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SwiGLUFFN(nn.Module):
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
in_features: int,
|
| 17 |
+
hidden_features: Optional[int] = None,
|
| 18 |
+
out_features: Optional[int] = None,
|
| 19 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 20 |
+
drop: float = 0.0,
|
| 21 |
+
bias: bool = True,
|
| 22 |
+
) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
out_features = out_features or in_features
|
| 25 |
+
hidden_features = hidden_features or in_features
|
| 26 |
+
self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
|
| 27 |
+
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
|
| 28 |
+
|
| 29 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 30 |
+
x12 = self.w12(x)
|
| 31 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
| 32 |
+
hidden = F.silu(x1) * x2
|
| 33 |
+
return self.w3(hidden)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
from xformers.ops import SwiGLU
|
| 38 |
+
|
| 39 |
+
XFORMERS_AVAILABLE = True
|
| 40 |
+
except ImportError:
|
| 41 |
+
SwiGLU = SwiGLUFFN
|
| 42 |
+
XFORMERS_AVAILABLE = False
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class SwiGLUFFNFused(SwiGLU):
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
in_features: int,
|
| 49 |
+
hidden_features: Optional[int] = None,
|
| 50 |
+
out_features: Optional[int] = None,
|
| 51 |
+
act_layer: Callable[..., nn.Module] = None,
|
| 52 |
+
drop: float = 0.0,
|
| 53 |
+
bias: bool = True,
|
| 54 |
+
) -> None:
|
| 55 |
+
out_features = out_features or in_features
|
| 56 |
+
hidden_features = hidden_features or in_features
|
| 57 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 58 |
+
super().__init__(
|
| 59 |
+
in_features=in_features,
|
| 60 |
+
hidden_features=hidden_features,
|
| 61 |
+
out_features=out_features,
|
| 62 |
+
bias=bias,
|
| 63 |
+
)
|
Depth-Anything-V2/depth_anything_v2/dpt.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torchvision.transforms import Compose
|
| 6 |
+
|
| 7 |
+
from .dinov2 import DINOv2
|
| 8 |
+
from .util.blocks import FeatureFusionBlock, _make_scratch
|
| 9 |
+
from .util.transform import Resize, NormalizeImage, PrepareForNet
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _make_fusion_block(features, use_bn, size=None):
|
| 13 |
+
return FeatureFusionBlock(
|
| 14 |
+
features,
|
| 15 |
+
nn.ReLU(False),
|
| 16 |
+
deconv=False,
|
| 17 |
+
bn=use_bn,
|
| 18 |
+
expand=False,
|
| 19 |
+
align_corners=True,
|
| 20 |
+
size=size,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ConvBlock(nn.Module):
|
| 25 |
+
def __init__(self, in_feature, out_feature):
|
| 26 |
+
super().__init__()
|
| 27 |
+
|
| 28 |
+
self.conv_block = nn.Sequential(
|
| 29 |
+
nn.Conv2d(in_feature, out_feature, kernel_size=3, stride=1, padding=1),
|
| 30 |
+
nn.BatchNorm2d(out_feature),
|
| 31 |
+
nn.ReLU(True)
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
return self.conv_block(x)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DPTHead(nn.Module):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
in_channels,
|
| 42 |
+
features=256,
|
| 43 |
+
use_bn=False,
|
| 44 |
+
out_channels=[256, 512, 1024, 1024],
|
| 45 |
+
use_clstoken=False
|
| 46 |
+
):
|
| 47 |
+
super(DPTHead, self).__init__()
|
| 48 |
+
|
| 49 |
+
self.use_clstoken = use_clstoken
|
| 50 |
+
|
| 51 |
+
self.projects = nn.ModuleList([
|
| 52 |
+
nn.Conv2d(
|
| 53 |
+
in_channels=in_channels,
|
| 54 |
+
out_channels=out_channel,
|
| 55 |
+
kernel_size=1,
|
| 56 |
+
stride=1,
|
| 57 |
+
padding=0,
|
| 58 |
+
) for out_channel in out_channels
|
| 59 |
+
])
|
| 60 |
+
|
| 61 |
+
self.resize_layers = nn.ModuleList([
|
| 62 |
+
nn.ConvTranspose2d(
|
| 63 |
+
in_channels=out_channels[0],
|
| 64 |
+
out_channels=out_channels[0],
|
| 65 |
+
kernel_size=4,
|
| 66 |
+
stride=4,
|
| 67 |
+
padding=0),
|
| 68 |
+
nn.ConvTranspose2d(
|
| 69 |
+
in_channels=out_channels[1],
|
| 70 |
+
out_channels=out_channels[1],
|
| 71 |
+
kernel_size=2,
|
| 72 |
+
stride=2,
|
| 73 |
+
padding=0),
|
| 74 |
+
nn.Identity(),
|
| 75 |
+
nn.Conv2d(
|
| 76 |
+
in_channels=out_channels[3],
|
| 77 |
+
out_channels=out_channels[3],
|
| 78 |
+
kernel_size=3,
|
| 79 |
+
stride=2,
|
| 80 |
+
padding=1)
|
| 81 |
+
])
|
| 82 |
+
|
| 83 |
+
if use_clstoken:
|
| 84 |
+
self.readout_projects = nn.ModuleList()
|
| 85 |
+
for _ in range(len(self.projects)):
|
| 86 |
+
self.readout_projects.append(
|
| 87 |
+
nn.Sequential(
|
| 88 |
+
nn.Linear(2 * in_channels, in_channels),
|
| 89 |
+
nn.GELU()))
|
| 90 |
+
|
| 91 |
+
self.scratch = _make_scratch(
|
| 92 |
+
out_channels,
|
| 93 |
+
features,
|
| 94 |
+
groups=1,
|
| 95 |
+
expand=False,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
self.scratch.stem_transpose = None
|
| 99 |
+
|
| 100 |
+
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
|
| 101 |
+
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
|
| 102 |
+
self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
|
| 103 |
+
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
|
| 104 |
+
|
| 105 |
+
head_features_1 = features
|
| 106 |
+
head_features_2 = 32
|
| 107 |
+
|
| 108 |
+
self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1)
|
| 109 |
+
self.scratch.output_conv2 = nn.Sequential(
|
| 110 |
+
nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
|
| 111 |
+
nn.ReLU(True),
|
| 112 |
+
nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
|
| 113 |
+
nn.ReLU(True),
|
| 114 |
+
nn.Identity(),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def forward(self, out_features, patch_h, patch_w):
|
| 118 |
+
out = []
|
| 119 |
+
for i, x in enumerate(out_features):
|
| 120 |
+
if self.use_clstoken:
|
| 121 |
+
x, cls_token = x[0], x[1]
|
| 122 |
+
readout = cls_token.unsqueeze(1).expand_as(x)
|
| 123 |
+
x = self.readout_projects[i](torch.cat((x, readout), -1))
|
| 124 |
+
else:
|
| 125 |
+
x = x[0]
|
| 126 |
+
|
| 127 |
+
x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
|
| 128 |
+
|
| 129 |
+
x = self.projects[i](x)
|
| 130 |
+
x = self.resize_layers[i](x)
|
| 131 |
+
|
| 132 |
+
out.append(x)
|
| 133 |
+
|
| 134 |
+
layer_1, layer_2, layer_3, layer_4 = out
|
| 135 |
+
|
| 136 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
| 137 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
| 138 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
| 139 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
| 140 |
+
|
| 141 |
+
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
|
| 142 |
+
path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
|
| 143 |
+
path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
|
| 144 |
+
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
|
| 145 |
+
|
| 146 |
+
out = self.scratch.output_conv1(path_1)
|
| 147 |
+
out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True)
|
| 148 |
+
out = self.scratch.output_conv2(out)
|
| 149 |
+
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class DepthAnythingV2(nn.Module):
|
| 154 |
+
def __init__(
|
| 155 |
+
self,
|
| 156 |
+
encoder='vitl',
|
| 157 |
+
features=256,
|
| 158 |
+
out_channels=[256, 512, 1024, 1024],
|
| 159 |
+
use_bn=False,
|
| 160 |
+
use_clstoken=False
|
| 161 |
+
):
|
| 162 |
+
super(DepthAnythingV2, self).__init__()
|
| 163 |
+
|
| 164 |
+
self.intermediate_layer_idx = {
|
| 165 |
+
'vits': [2, 5, 8, 11],
|
| 166 |
+
'vitb': [2, 5, 8, 11],
|
| 167 |
+
'vitl': [4, 11, 17, 23],
|
| 168 |
+
'vitg': [9, 19, 29, 39]
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
self.encoder = encoder
|
| 172 |
+
self.pretrained = DINOv2(model_name=encoder)
|
| 173 |
+
|
| 174 |
+
self.depth_head = DPTHead(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
|
| 175 |
+
|
| 176 |
+
def forward(self, x):
|
| 177 |
+
patch_h, patch_w = x.shape[-2] // 14, x.shape[-1] // 14
|
| 178 |
+
|
| 179 |
+
features = self.pretrained.get_intermediate_layers(x, self.intermediate_layer_idx[self.encoder], return_class_token=True)
|
| 180 |
+
|
| 181 |
+
depth = self.depth_head(features, patch_h, patch_w)
|
| 182 |
+
depth = F.relu(depth)
|
| 183 |
+
|
| 184 |
+
return depth.squeeze(1)
|
| 185 |
+
|
| 186 |
+
@torch.no_grad()
|
| 187 |
+
def infer_image(self, raw_image, input_size=518):
|
| 188 |
+
image, (h, w) = self.image2tensor(raw_image, input_size)
|
| 189 |
+
|
| 190 |
+
depth = self.forward(image)
|
| 191 |
+
|
| 192 |
+
depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
|
| 193 |
+
|
| 194 |
+
return depth.cpu().numpy()
|
| 195 |
+
|
| 196 |
+
def image2tensor(self, raw_image, input_size=518):
|
| 197 |
+
transform = Compose([
|
| 198 |
+
Resize(
|
| 199 |
+
width=input_size,
|
| 200 |
+
height=input_size,
|
| 201 |
+
resize_target=False,
|
| 202 |
+
keep_aspect_ratio=True,
|
| 203 |
+
ensure_multiple_of=14,
|
| 204 |
+
resize_method='lower_bound',
|
| 205 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 206 |
+
),
|
| 207 |
+
NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 208 |
+
PrepareForNet(),
|
| 209 |
+
])
|
| 210 |
+
|
| 211 |
+
h, w = raw_image.shape[:2]
|
| 212 |
+
|
| 213 |
+
image = cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB) / 255.0
|
| 214 |
+
|
| 215 |
+
image = transform({'image': image})['image']
|
| 216 |
+
image = torch.from_numpy(image).unsqueeze(0)
|
| 217 |
+
|
| 218 |
+
DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
|
| 219 |
+
image = image.to(DEVICE)
|
| 220 |
+
|
| 221 |
+
return image, (h, w)
|
Depth-Anything-V2/depth_anything_v2/util/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Utility functions for Depth Anything v2
|
Depth-Anything-V2/depth_anything_v2/util/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (216 Bytes). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/util/__pycache__/blocks.cpython-311.pyc
ADDED
|
Binary file (6.03 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/util/__pycache__/transform.cpython-311.pyc
ADDED
|
Binary file (7.69 kB). View file
|
|
|
Depth-Anything-V2/depth_anything_v2/util/blocks.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
|
| 5 |
+
scratch = nn.Module()
|
| 6 |
+
|
| 7 |
+
out_shape1 = out_shape
|
| 8 |
+
out_shape2 = out_shape
|
| 9 |
+
out_shape3 = out_shape
|
| 10 |
+
if len(in_shape) >= 4:
|
| 11 |
+
out_shape4 = out_shape
|
| 12 |
+
|
| 13 |
+
if expand:
|
| 14 |
+
out_shape1 = out_shape
|
| 15 |
+
out_shape2 = out_shape * 2
|
| 16 |
+
out_shape3 = out_shape * 4
|
| 17 |
+
if len(in_shape) >= 4:
|
| 18 |
+
out_shape4 = out_shape * 8
|
| 19 |
+
|
| 20 |
+
scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 21 |
+
scratch.layer2_rn = nn.Conv2d(in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 22 |
+
scratch.layer3_rn = nn.Conv2d(in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 23 |
+
if len(in_shape) >= 4:
|
| 24 |
+
scratch.layer4_rn = nn.Conv2d(in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
|
| 25 |
+
|
| 26 |
+
return scratch
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ResidualConvUnit(nn.Module):
|
| 30 |
+
"""Residual convolution module.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, features, activation, bn):
|
| 34 |
+
"""Init.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
features (int): number of features
|
| 38 |
+
"""
|
| 39 |
+
super().__init__()
|
| 40 |
+
|
| 41 |
+
self.bn = bn
|
| 42 |
+
|
| 43 |
+
self.groups=1
|
| 44 |
+
|
| 45 |
+
self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
|
| 46 |
+
|
| 47 |
+
self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
|
| 48 |
+
|
| 49 |
+
if self.bn == True:
|
| 50 |
+
self.bn1 = nn.BatchNorm2d(features)
|
| 51 |
+
self.bn2 = nn.BatchNorm2d(features)
|
| 52 |
+
|
| 53 |
+
self.activation = activation
|
| 54 |
+
|
| 55 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 56 |
+
|
| 57 |
+
def forward(self, x):
|
| 58 |
+
"""Forward pass.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
x (tensor): input
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
tensor: output
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
out = self.activation(x)
|
| 68 |
+
out = self.conv1(out)
|
| 69 |
+
if self.bn == True:
|
| 70 |
+
out = self.bn1(out)
|
| 71 |
+
|
| 72 |
+
out = self.activation(out)
|
| 73 |
+
out = self.conv2(out)
|
| 74 |
+
if self.bn == True:
|
| 75 |
+
out = self.bn2(out)
|
| 76 |
+
|
| 77 |
+
if self.groups > 1:
|
| 78 |
+
out = self.conv_merge(out)
|
| 79 |
+
|
| 80 |
+
return self.skip_add.add(out, x)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class FeatureFusionBlock(nn.Module):
|
| 84 |
+
"""Feature fusion block.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
features,
|
| 90 |
+
activation,
|
| 91 |
+
deconv=False,
|
| 92 |
+
bn=False,
|
| 93 |
+
expand=False,
|
| 94 |
+
align_corners=True,
|
| 95 |
+
size=None
|
| 96 |
+
):
|
| 97 |
+
"""Init.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
features (int): number of features
|
| 101 |
+
"""
|
| 102 |
+
super(FeatureFusionBlock, self).__init__()
|
| 103 |
+
|
| 104 |
+
self.deconv = deconv
|
| 105 |
+
self.align_corners = align_corners
|
| 106 |
+
|
| 107 |
+
self.groups=1
|
| 108 |
+
|
| 109 |
+
self.expand = expand
|
| 110 |
+
out_features = features
|
| 111 |
+
if self.expand == True:
|
| 112 |
+
out_features = features // 2
|
| 113 |
+
|
| 114 |
+
self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
|
| 115 |
+
|
| 116 |
+
self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
|
| 117 |
+
self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
|
| 118 |
+
|
| 119 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 120 |
+
|
| 121 |
+
self.size=size
|
| 122 |
+
|
| 123 |
+
def forward(self, *xs, size=None):
|
| 124 |
+
"""Forward pass.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
tensor: output
|
| 128 |
+
"""
|
| 129 |
+
output = xs[0]
|
| 130 |
+
|
| 131 |
+
if len(xs) == 2:
|
| 132 |
+
res = self.resConfUnit1(xs[1])
|
| 133 |
+
output = self.skip_add.add(output, res)
|
| 134 |
+
|
| 135 |
+
output = self.resConfUnit2(output)
|
| 136 |
+
|
| 137 |
+
if (size is None) and (self.size is None):
|
| 138 |
+
modifier = {"scale_factor": 2}
|
| 139 |
+
elif size is None:
|
| 140 |
+
modifier = {"size": self.size}
|
| 141 |
+
else:
|
| 142 |
+
modifier = {"size": size}
|
| 143 |
+
|
| 144 |
+
output = nn.functional.interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners)
|
| 145 |
+
|
| 146 |
+
output = self.out_conv(output)
|
| 147 |
+
|
| 148 |
+
return output
|
Depth-Anything-V2/depth_anything_v2/util/transform.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Resize(object):
|
| 6 |
+
"""Resize sample to given size (width, height).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
width,
|
| 12 |
+
height,
|
| 13 |
+
resize_target=True,
|
| 14 |
+
keep_aspect_ratio=False,
|
| 15 |
+
ensure_multiple_of=1,
|
| 16 |
+
resize_method="lower_bound",
|
| 17 |
+
image_interpolation_method=cv2.INTER_AREA,
|
| 18 |
+
):
|
| 19 |
+
"""Init.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
width (int): desired output width
|
| 23 |
+
height (int): desired output height
|
| 24 |
+
resize_target (bool, optional):
|
| 25 |
+
True: Resize the full sample (image, mask, target).
|
| 26 |
+
False: Resize image only.
|
| 27 |
+
Defaults to True.
|
| 28 |
+
keep_aspect_ratio (bool, optional):
|
| 29 |
+
True: Keep the aspect ratio of the input sample.
|
| 30 |
+
Output sample might not have the given width and height, and
|
| 31 |
+
resize behaviour depends on the parameter 'resize_method'.
|
| 32 |
+
Defaults to False.
|
| 33 |
+
ensure_multiple_of (int, optional):
|
| 34 |
+
Output width and height is constrained to be multiple of this parameter.
|
| 35 |
+
Defaults to 1.
|
| 36 |
+
resize_method (str, optional):
|
| 37 |
+
"lower_bound": Output will be at least as large as the given size.
|
| 38 |
+
"upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
|
| 39 |
+
"minimal": Scale as least as possible. (Output size might be smaller than given size.)
|
| 40 |
+
Defaults to "lower_bound".
|
| 41 |
+
"""
|
| 42 |
+
self.__width = width
|
| 43 |
+
self.__height = height
|
| 44 |
+
|
| 45 |
+
self.__resize_target = resize_target
|
| 46 |
+
self.__keep_aspect_ratio = keep_aspect_ratio
|
| 47 |
+
self.__multiple_of = ensure_multiple_of
|
| 48 |
+
self.__resize_method = resize_method
|
| 49 |
+
self.__image_interpolation_method = image_interpolation_method
|
| 50 |
+
|
| 51 |
+
def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
|
| 52 |
+
y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 53 |
+
|
| 54 |
+
if max_val is not None and y > max_val:
|
| 55 |
+
y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 56 |
+
|
| 57 |
+
if y < min_val:
|
| 58 |
+
y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 59 |
+
|
| 60 |
+
return y
|
| 61 |
+
|
| 62 |
+
def get_size(self, width, height):
|
| 63 |
+
# determine new height and width
|
| 64 |
+
scale_height = self.__height / height
|
| 65 |
+
scale_width = self.__width / width
|
| 66 |
+
|
| 67 |
+
if self.__keep_aspect_ratio:
|
| 68 |
+
if self.__resize_method == "lower_bound":
|
| 69 |
+
# scale such that output size is lower bound
|
| 70 |
+
if scale_width > scale_height:
|
| 71 |
+
# fit width
|
| 72 |
+
scale_height = scale_width
|
| 73 |
+
else:
|
| 74 |
+
# fit height
|
| 75 |
+
scale_width = scale_height
|
| 76 |
+
elif self.__resize_method == "upper_bound":
|
| 77 |
+
# scale such that output size is upper bound
|
| 78 |
+
if scale_width < scale_height:
|
| 79 |
+
# fit width
|
| 80 |
+
scale_height = scale_width
|
| 81 |
+
else:
|
| 82 |
+
# fit height
|
| 83 |
+
scale_width = scale_height
|
| 84 |
+
elif self.__resize_method == "minimal":
|
| 85 |
+
# scale as least as possbile
|
| 86 |
+
if abs(1 - scale_width) < abs(1 - scale_height):
|
| 87 |
+
# fit width
|
| 88 |
+
scale_height = scale_width
|
| 89 |
+
else:
|
| 90 |
+
# fit height
|
| 91 |
+
scale_width = scale_height
|
| 92 |
+
else:
|
| 93 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
| 94 |
+
|
| 95 |
+
if self.__resize_method == "lower_bound":
|
| 96 |
+
new_height = self.constrain_to_multiple_of(scale_height * height, min_val=self.__height)
|
| 97 |
+
new_width = self.constrain_to_multiple_of(scale_width * width, min_val=self.__width)
|
| 98 |
+
elif self.__resize_method == "upper_bound":
|
| 99 |
+
new_height = self.constrain_to_multiple_of(scale_height * height, max_val=self.__height)
|
| 100 |
+
new_width = self.constrain_to_multiple_of(scale_width * width, max_val=self.__width)
|
| 101 |
+
elif self.__resize_method == "minimal":
|
| 102 |
+
new_height = self.constrain_to_multiple_of(scale_height * height)
|
| 103 |
+
new_width = self.constrain_to_multiple_of(scale_width * width)
|
| 104 |
+
else:
|
| 105 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
| 106 |
+
|
| 107 |
+
return (new_width, new_height)
|
| 108 |
+
|
| 109 |
+
def __call__(self, sample):
|
| 110 |
+
width, height = self.get_size(sample["image"].shape[1], sample["image"].shape[0])
|
| 111 |
+
|
| 112 |
+
# resize sample
|
| 113 |
+
sample["image"] = cv2.resize(sample["image"], (width, height), interpolation=self.__image_interpolation_method)
|
| 114 |
+
|
| 115 |
+
if self.__resize_target:
|
| 116 |
+
if "depth" in sample:
|
| 117 |
+
sample["depth"] = cv2.resize(sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST)
|
| 118 |
+
|
| 119 |
+
if "mask" in sample:
|
| 120 |
+
sample["mask"] = cv2.resize(sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST)
|
| 121 |
+
|
| 122 |
+
return sample
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class NormalizeImage(object):
|
| 126 |
+
"""Normlize image by given mean and std.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
def __init__(self, mean, std):
|
| 130 |
+
self.__mean = mean
|
| 131 |
+
self.__std = std
|
| 132 |
+
|
| 133 |
+
def __call__(self, sample):
|
| 134 |
+
sample["image"] = (sample["image"] - self.__mean) / self.__std
|
| 135 |
+
|
| 136 |
+
return sample
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class PrepareForNet(object):
|
| 140 |
+
"""Prepare sample for usage as network input.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def __init__(self):
|
| 144 |
+
pass
|
| 145 |
+
|
| 146 |
+
def __call__(self, sample):
|
| 147 |
+
image = np.transpose(sample["image"], (2, 0, 1))
|
| 148 |
+
sample["image"] = np.ascontiguousarray(image).astype(np.float32)
|
| 149 |
+
|
| 150 |
+
if "depth" in sample:
|
| 151 |
+
depth = sample["depth"].astype(np.float32)
|
| 152 |
+
sample["depth"] = np.ascontiguousarray(depth)
|
| 153 |
+
|
| 154 |
+
if "mask" in sample:
|
| 155 |
+
sample["mask"] = sample["mask"].astype(np.float32)
|
| 156 |
+
sample["mask"] = np.ascontiguousarray(sample["mask"])
|
| 157 |
+
|
| 158 |
+
return sample
|