Spaces:
Running on Zero
Running on Zero
FlashReFocus video spotlight demo (SAM 3 + Depth Anything V2 + FlashReFocus renderer)
Browse files- .gitignore +3 -0
- README.md +20 -7
- app.py +202 -0
- engine.py +156 -0
- flashrefocus/README.md +155 -0
- flashrefocus/__init__.py +6 -0
- flashrefocus/_compat.py +9 -0
- flashrefocus/deblurring/__init__.py +4 -0
- flashrefocus/deblurring/deblurrer.py +102 -0
- flashrefocus/deblurring/decoder_refiner.py +112 -0
- flashrefocus/deblurring/one_step_diffusion.py +136 -0
- flashrefocus/image_io.py +72 -0
- flashrefocus/layers.py +95 -0
- flashrefocus/overlays.py +29 -0
- flashrefocus/paths.py +39 -0
- flashrefocus/pipeline.py +121 -0
- flashrefocus/rendering/__init__.py +5 -0
- flashrefocus/rendering/defocus_bias_attention.py +140 -0
- flashrefocus/rendering/depth.py +85 -0
- flashrefocus/rendering/depth_edits.py +138 -0
- flashrefocus/rendering/fused.py +127 -0
- flashrefocus/rendering/renderer.py +151 -0
- flashrefocus/segment.py +104 -0
- flashrefocus/video.py +139 -0
- requirements.txt +11 -0
- third_party/Depth-Anything-V2/LICENSE +201 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2.py +415 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/__init__.py +11 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/attention.py +83 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/block.py +252 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/drop_path.py +35 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/layer_scale.py +28 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/mlp.py +41 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/patch_embed.py +89 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/swiglu_ffn.py +63 -0
- third_party/Depth-Anything-V2/depth_anything_v2/dpt.py +221 -0
- third_party/Depth-Anything-V2/depth_anything_v2/util/blocks.py +148 -0
- third_party/Depth-Anything-V2/depth_anything_v2/util/transform.py +158 -0
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
weights/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
README.md
CHANGED
|
@@ -1,13 +1,26 @@
|
|
| 1 |
---
|
| 2 |
-
title: FlashReFocus Video
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
python_version:
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: FlashReFocus Video Spotlight
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.50.0
|
| 8 |
+
python_version: "3.10"
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
+
short_description: Keep one person sharp in a video and blur everyone else
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# FlashReFocus: Video Spotlight
|
| 15 |
+
|
| 16 |
+
Upload a short clip and click the person to keep sharp. SAM 3 tracks every person, Depth Anything V2 estimates each
|
| 17 |
+
frame's depth, the depth is edited so that everyone but the chosen person is moved away from the focal plane, and the
|
| 18 |
+
FlashReFocus renderer renders each frame. Video frames are already sharp, so restoration (Stage I) is not used.
|
| 19 |
+
|
| 20 |
+
The photo demo (restoration, click-to-focus, two focal planes, tilt-shift) is at
|
| 21 |
+
[ming0531/FlashReFocus](https://huggingface.co/spaces/ming0531/FlashReFocus).
|
| 22 |
+
|
| 23 |
+
[Project page](https://ming053l.github.io/FlashReFocus/) · [Code](https://github.com/ming053l/FlashReFocus)
|
| 24 |
+
|
| 25 |
+
Third-party code and models: SAM 3 (facebook/sam3; see its model card for the licence) and Depth Anything V2 (depth), see
|
| 26 |
+
`third_party/*/LICENSE`.
|
app.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FlashReFocus video spotlight (Hugging Face Space, ZeroGPU).
|
| 2 |
+
|
| 3 |
+
1. Upload a short clip; its first frame is shown. Click the person to keep sharp (default: the most central person).
|
| 4 |
+
2. SAM 3 tracks every instance of the prompt ("person") and keeps the chosen track as the subject.
|
| 5 |
+
3. Every frame: Depth Anything V2 depth (smoothed over time), the spotlight depth edit (subject on the focal plane,
|
| 6 |
+
everything else at least `gap` away), and the FlashReFocus renderer. The audio of the clip is kept.
|
| 7 |
+
"""
|
| 8 |
+
import tempfile
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import numpy as np
|
| 14 |
+
import spaces
|
| 15 |
+
from PIL import Image, ImageDraw
|
| 16 |
+
|
| 17 |
+
import engine
|
| 18 |
+
|
| 19 |
+
MAX_SECONDS = 5.0
|
| 20 |
+
GREEN = np.array([72, 164, 63], np.float32)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _track_seconds(frames, *args):
|
| 24 |
+
return int(min(120, 20 + 0.45 * len(frames)))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _render_seconds(frames, *args):
|
| 28 |
+
return int(min(120, 15 + 0.35 * len(frames)))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@spaces.GPU(duration=_track_seconds)
|
| 32 |
+
def gpu_track(frames, prompt, point):
|
| 33 |
+
t0 = time.perf_counter()
|
| 34 |
+
subject, others = engine.track(frames, prompt, point)
|
| 35 |
+
return subject, others, time.perf_counter() - t0
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@spaces.GPU(duration=_render_seconds)
|
| 39 |
+
def gpu_spotlight(frames, subject, others, strength, gap):
|
| 40 |
+
t0 = time.perf_counter()
|
| 41 |
+
out, depth = engine.spotlight(frames, subject, others, strength=strength, gap=gap)
|
| 42 |
+
return out, depth, time.perf_counter() - t0
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def mark(image, point):
|
| 46 |
+
"""The first frame with a ring at the clicked point."""
|
| 47 |
+
im = image.copy()
|
| 48 |
+
if point is not None:
|
| 49 |
+
d = ImageDraw.Draw(im)
|
| 50 |
+
x, y = point[0] * (im.width - 1), point[1] * (im.height - 1)
|
| 51 |
+
r = max(8, im.width // 60)
|
| 52 |
+
d.ellipse((x - r, y - r, x + r, y + r), outline=(255, 255, 255), width=max(3, r // 3))
|
| 53 |
+
d.ellipse((x - r // 3, y - r // 3, x + r // 3, y + r // 3), fill=(72, 164, 63))
|
| 54 |
+
return im
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def overlay(frame, mask):
|
| 58 |
+
"""Frame with the subject mask in green."""
|
| 59 |
+
a = frame.astype(np.float32).copy()
|
| 60 |
+
a[mask] = 0.55 * a[mask] + 0.45 * GREEN
|
| 61 |
+
return Image.fromarray(a.astype(np.uint8))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def depth_image(depth):
|
| 65 |
+
return Image.fromarray((np.clip(1 - depth, 0, 1) * 255).astype(np.uint8)) # near is bright
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def on_video(video):
|
| 69 |
+
if video is None:
|
| 70 |
+
return None, {"video": None, "point": None, "frame": None}, "Upload a clip first."
|
| 71 |
+
frame = engine.first_frame(video)
|
| 72 |
+
w, h, fps, dur = engine.probe(video)
|
| 73 |
+
state = {"video": video, "point": None, "frame": frame, "duration": dur}
|
| 74 |
+
msg = (f"Clip: {w}×{h}, {fps:.0f} fps, {dur:.1f} s. **Click the person to keep sharp** (otherwise the most central "
|
| 75 |
+
f"person is used), then press 🎬 Spotlight. At most {MAX_SECONDS:.0f} s are processed.")
|
| 76 |
+
return frame, state, msg
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def on_click(state, evt: gr.SelectData):
|
| 80 |
+
if not state or state.get("frame") is None:
|
| 81 |
+
return None, state, "Upload a clip first."
|
| 82 |
+
frame = state["frame"]
|
| 83 |
+
x, y = evt.index
|
| 84 |
+
point = (x / max(1, frame.width - 1), y / max(1, frame.height - 1))
|
| 85 |
+
state = dict(state, point=point)
|
| 86 |
+
return mark(frame, point), state, f"Subject: the person at ({x}, {y}). Press 🎬 Spotlight."
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def on_clear(state):
|
| 90 |
+
if not state or state.get("frame") is None:
|
| 91 |
+
return None, state, "Upload a clip first."
|
| 92 |
+
return state["frame"], dict(state, point=None), "Subject: the most central person. Press 🎬 Spotlight."
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def run(state, prompt, start, seconds, long_side, strength, gap, progress=gr.Progress()):
|
| 96 |
+
if not state or state.get("video") is None:
|
| 97 |
+
raise gr.Error("Upload a clip first.")
|
| 98 |
+
start = max(0.0, min(float(start), max(0.0, state.get("duration", 0) - 0.5)))
|
| 99 |
+
seconds = min(float(seconds), MAX_SECONDS)
|
| 100 |
+
progress(0.05, desc="Reading frames")
|
| 101 |
+
frames, fps = engine.read_clip(state["video"], seconds, int(long_side), start=start)
|
| 102 |
+
if len(frames) == 0:
|
| 103 |
+
raise gr.Error("No frames in this part of the clip.")
|
| 104 |
+
progress(0.15, desc=f"Tracking '{prompt or 'person'}' with SAM 3 ({len(frames)} frames)")
|
| 105 |
+
point = state.get("point") if start == 0 else None
|
| 106 |
+
subject, others, t_track = gpu_track(frames, prompt or "person", point)
|
| 107 |
+
found = subject.reshape(len(subject), -1).any(1)
|
| 108 |
+
if not found.any():
|
| 109 |
+
raise gr.Error(f"SAM 3 found no '{prompt or 'person'}' to keep sharp in this clip.")
|
| 110 |
+
progress(0.55, desc="Depth, spotlight edit and rendering")
|
| 111 |
+
out, depth, t_render = gpu_spotlight(frames, subject, others, float(strength), float(gap))
|
| 112 |
+
progress(0.9, desc="Encoding")
|
| 113 |
+
tmp = Path(tempfile.mkdtemp())
|
| 114 |
+
audio = engine.cut_audio(state["video"], seconds, tmp / "audio.m4a", start=start)
|
| 115 |
+
path = engine.write_video(out, fps, str(tmp / "spotlight.mp4"), audio)
|
| 116 |
+
first = int(np.argmax(found))
|
| 117 |
+
msg = (f"{len(frames)} frames at {frames.shape[2]}×{frames.shape[1]}: SAM 3 tracking {t_track:.1f} s, depth + "
|
| 118 |
+
f"spotlight + rendering {t_render:.1f} s ({1000 * t_render / len(frames):.0f} ms per frame). The subject was "
|
| 119 |
+
f"found in {found.mean():.0%} of the frames.")
|
| 120 |
+
return path, overlay(frames[first], subject[first]), depth_image(depth), msg
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
HEADER = """
|
| 124 |
+
<div id="header">
|
| 125 |
+
<div class="title"><div><h1>FlashReFocus: Video Spotlight</h1><p>Keep one person sharp and blur everyone else, frame
|
| 126 |
+
by frame. SAM 3 tracks the people, Depth Anything V2 gives each frame's depth, and the FlashReFocus renderer renders
|
| 127 |
+
the edited depth.</p></div></div>
|
| 128 |
+
<div class="authors">Ching-Heng Cheng<sup>1*</sup> · <a href="https://ming053l.github.io/" target="_blank">Chia-Ming Lee</a><sup>2,3*</sup> ·
|
| 129 |
+
<a href="https://www.albany.edu/faculty/mchang2/" target="_blank">Ming-Ching Chang</a><sup>2</sup> ·
|
| 130 |
+
<a href="https://scholar.google.com/citations?user=gMBvzGoAAAAJ&hl=en" target="_blank">Xin Li</a><sup>2</sup> ·
|
| 131 |
+
<a href="https://yulunalexliu.github.io/" target="_blank">Yu-Lun Liu</a><sup>3</sup> ·
|
| 132 |
+
<a href="https://cchsu.info/" target="_blank">Chih-Chung Hsu</a><sup>1,3†</sup><br>
|
| 133 |
+
<small><sup>1</sup>National Cheng Kung University · <sup>2</sup>State University of New York at Albany ·
|
| 134 |
+
<sup>3</sup>National Yang Ming Chiao Tung University · * equal contribution · † corresponding author</small></div>
|
| 135 |
+
<div class="links">
|
| 136 |
+
<a href="https://huggingface.co/spaces/ming0531/FlashReFocus" target="_blank">📷 Photo demo</a>
|
| 137 |
+
<a href="https://ming053l.github.io/FlashReFocus/" target="_blank">🌐 Project page</a>
|
| 138 |
+
<a href="https://ming053l.github.io/FlashReFocus/assets/FlashReFocus.pdf" target="_blank">📄 Paper</a>
|
| 139 |
+
<a href="https://github.com/ming053l/FlashReFocus" target="_blank">💻 Code</a>
|
| 140 |
+
</div>
|
| 141 |
+
<div class="tip">A single focal plane cannot do this when the people around the subject stand at nearly the same
|
| 142 |
+
depth: they would stay as sharp as the subject. The spotlight edit moves everyone but the subject away from the
|
| 143 |
+
focal plane in the depth map, so only the subject stays sharp. The renderer was trained on single photographs with
|
| 144 |
+
one focal plane; this use is zero-shot.</div>
|
| 145 |
+
</div>
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
CSS = """
|
| 149 |
+
#header {margin-bottom: 4px}
|
| 150 |
+
#header .title {display: flex; align-items: center; justify-content: center; text-align: center}
|
| 151 |
+
#header h1 {margin: 0; font-size: 2.0em; color: #2E7D32}
|
| 152 |
+
#header .title p {margin: 4px 0 0; color: var(--body-text-color-subdued)}
|
| 153 |
+
#header .authors {text-align: center; margin-top: 10px; line-height: 1.6}
|
| 154 |
+
#header .authors a {color: #2E7D32; text-decoration: none; font-weight: 600}
|
| 155 |
+
#header .authors small {color: var(--body-text-color-subdued)}
|
| 156 |
+
#header .links {display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin: 12px 0}
|
| 157 |
+
#header .links a {padding: 5px 14px; border-radius: 999px; border: 1px solid #48A43F; color: #2E7D32;
|
| 158 |
+
text-decoration: none; font-weight: 600}
|
| 159 |
+
#header .links a:hover {background: #48A43F; color: white}
|
| 160 |
+
#header .tip {background: #f1f8ef; border-left: 4px solid #48A43F; padding: 10px 14px; border-radius: 8px;
|
| 161 |
+
color: #1f3d1f}
|
| 162 |
+
.step h3 {margin: 6px 0 2px; color: #2E7D32}
|
| 163 |
+
#status {background: #f1f8ef; border-left: 4px solid #48A43F; padding: 8px 14px; border-radius: 8px; min-height: 2.4em}
|
| 164 |
+
#status p {margin: 0; color: #1f3d1f}
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
with gr.Blocks(title="FlashReFocus Video Spotlight", theme=gr.themes.Soft(primary_hue="green"), css=CSS) as demo:
|
| 168 |
+
gr.HTML(HEADER)
|
| 169 |
+
state = gr.State({"video": None, "point": None, "frame": None})
|
| 170 |
+
with gr.Row():
|
| 171 |
+
with gr.Column():
|
| 172 |
+
gr.Markdown("### ① Upload a short clip", elem_classes="step")
|
| 173 |
+
video = gr.Video(label="Input clip", sources=["upload"], height=300)
|
| 174 |
+
gr.Markdown("### ② Click the person to keep sharp", elem_classes="step")
|
| 175 |
+
first = gr.Image(label="First frame (click the subject)", type="pil", interactive=False, height=300)
|
| 176 |
+
with gr.Row():
|
| 177 |
+
prompt = gr.Textbox(value="person", label="What to track (SAM 3 text prompt)", scale=3)
|
| 178 |
+
clear = gr.Button("Use the most central", size="sm", scale=1)
|
| 179 |
+
with gr.Accordion("Settings", open=False):
|
| 180 |
+
start = gr.Number(value=0.0, minimum=0.0, label="Start at (seconds; a click is used only from 0 s)")
|
| 181 |
+
seconds = gr.Slider(1, MAX_SECONDS, value=3, step=0.5, label="Length (seconds)")
|
| 182 |
+
long_side = gr.Radio([512, 768, 960], value=768, label="Long side (pixels)")
|
| 183 |
+
strength = gr.Slider(0.5, 2.0, value=1.5, step=0.05, label="🔆 Blur strength K",
|
| 184 |
+
info="1: the widest aperture seen in training; above 1 extrapolates.")
|
| 185 |
+
gap = gr.Slider(0.2, 1.0, value=0.6, step=0.05, label="Depth gap",
|
| 186 |
+
info="How far everything but the subject is moved from the focal plane.")
|
| 187 |
+
btn = gr.Button("🎬 Spotlight", variant="primary", size="lg")
|
| 188 |
+
with gr.Column():
|
| 189 |
+
gr.Markdown("### ③ Result", elem_classes="step")
|
| 190 |
+
status = gr.Markdown("Upload a clip to start.", elem_id="status")
|
| 191 |
+
out = gr.Video(label="Spotlight result", height=360, autoplay=True)
|
| 192 |
+
with gr.Row():
|
| 193 |
+
subj = gr.Image(label="Tracked subject (green)", type="pil", interactive=False, height=180)
|
| 194 |
+
dep = gr.Image(label="Edited depth, first frame (near is bright)", type="pil", interactive=False,
|
| 195 |
+
height=180)
|
| 196 |
+
video.change(on_video, [video], [first, state, status])
|
| 197 |
+
first.select(on_click, [state], [first, state, status])
|
| 198 |
+
clear.click(on_clear, [state], [first, state, status])
|
| 199 |
+
btn.click(run, [state, prompt, start, seconds, long_side, strength, gap], [out, subj, dep, status])
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
demo.queue(max_size=10).launch(show_api=False)
|
engine.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Video spotlight with FlashReFocus for the Hugging Face Space (ZeroGPU), on the flashrefocus package (a copy of the
|
| 2 |
+
repository's).
|
| 3 |
+
|
| 4 |
+
One subject stays sharp and everyone else is blurred, frame by frame: SAM 3 tracks every instance of a text prompt
|
| 5 |
+
("person"), one track is chosen as the subject, Depth Anything V2 estimates each frame's depth (smoothed over time),
|
| 6 |
+
the depth is edited with depth_edits.spotlight (the subject on the focal plane, everything else at least `gap` away
|
| 7 |
+
from it) and the renderer renders the frame. Video frames are already sharp, so Stage I (restoration) is not loaded.
|
| 8 |
+
|
| 9 |
+
ZeroGPU gives a GPU only inside @spaces.GPU calls: the models are built on the CPU and moved to `cuda` at import time;
|
| 10 |
+
frames and masks stay on the CPU between calls. The renderer runs its attention as the fused Triton kernel of
|
| 11 |
+
flashrefocus/rendering/fused.py, with a fallback to the reference attention. The renderer weights come from a private
|
| 12 |
+
model repository and SAM 3 is gated: both are read with the HF_TOKEN secret."""
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import subprocess
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from huggingface_hub import hf_hub_download
|
| 21 |
+
|
| 22 |
+
HERE = Path(__file__).resolve().parent
|
| 23 |
+
WEIGHT_REPO = os.environ.get("FLASHREFOCUS_WEIGHT_REPO", "ming0531/FlashReFocus-weights")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def fetch_weights():
|
| 27 |
+
"""Depth Anything V2 and the renderer into ./weights (skipped when FLASHREFOCUS_WEIGHTS points to a local copy)."""
|
| 28 |
+
if "FLASHREFOCUS_WEIGHTS" in os.environ:
|
| 29 |
+
return
|
| 30 |
+
w = HERE / "weights"
|
| 31 |
+
hf_hub_download("depth-anything/Depth-Anything-V2-Large", "depth_anything_v2_vitl.pth", local_dir=w)
|
| 32 |
+
hf_hub_download(WEIGHT_REPO, "renderer.pt", local_dir=w, token=os.environ.get("HF_TOKEN"))
|
| 33 |
+
os.environ["FLASHREFOCUS_WEIGHTS"] = str(w)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
fetch_weights()
|
| 37 |
+
from transformers import Sam3VideoModel, Sam3VideoProcessor # noqa: E402
|
| 38 |
+
|
| 39 |
+
from flashrefocus import Refocuser, Scene, paths, segment # noqa: E402
|
| 40 |
+
from flashrefocus.image_io import image_to_tensor # noqa: E402
|
| 41 |
+
from flashrefocus.rendering import DepthEstimator, depth_edits, load_renderer # noqa: E402
|
| 42 |
+
from flashrefocus.rendering.fused import enable_fused # noqa: E402
|
| 43 |
+
from flashrefocus.video import ffmpeg_exe # noqa: E402
|
| 44 |
+
|
| 45 |
+
# Depth Anything V2 at its native 518 on the short side: the frames here are at most 960 px wide, and the 1024 used for
|
| 46 |
+
# photographs would upsample them (4.5x slower per frame for no added detail).
|
| 47 |
+
refocuser = Refocuser(None, DepthEstimator.from_pretrained(device="cpu", input_size=518).to("cuda"),
|
| 48 |
+
enable_fused(load_renderer(paths.RENDERER, "cpu")).to("cuda"))
|
| 49 |
+
segment._SAM3[("cuda", torch.bfloat16)] = ( # track_subject finds the model here
|
| 50 |
+
Sam3VideoModel.from_pretrained("facebook/sam3", token=os.environ.get("HF_TOKEN"), dtype=torch.bfloat16).to("cuda").eval(),
|
| 51 |
+
Sam3VideoProcessor.from_pretrained("facebook/sam3", token=os.environ.get("HF_TOKEN")))
|
| 52 |
+
FFMPEG = ffmpeg_exe()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def probe(path):
|
| 56 |
+
"""(width, height, fps, duration) of a video as displayed (ffmpeg applies the rotation tag)."""
|
| 57 |
+
import imageio_ffmpeg
|
| 58 |
+
reader = imageio_ffmpeg.read_frames(str(path))
|
| 59 |
+
meta = next(reader)
|
| 60 |
+
reader.close()
|
| 61 |
+
w, h = first_frame(path).size
|
| 62 |
+
return w, h, float(meta.get("fps") or 30.0), float(meta.get("duration") or 0.0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def first_frame(path):
|
| 66 |
+
"""The first frame as an RGB PIL image, as displayed."""
|
| 67 |
+
import io
|
| 68 |
+
|
| 69 |
+
from PIL import Image
|
| 70 |
+
png = subprocess.run([FFMPEG, "-v", "error", "-i", str(path), "-frames:v", "1", "-f", "image2pipe", "-c:v", "png",
|
| 71 |
+
"-"], capture_output=True, check=True).stdout
|
| 72 |
+
return Image.open(io.BytesIO(png)).convert("RGB")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def read_clip(path, seconds, long_side, max_fps=30.0, start=0.0):
|
| 76 |
+
"""The first `seconds` of a video (from `start`) as (n, h, w, 3) uint8, long side at most `long_side`, both sides
|
| 77 |
+
multiples of 16, at most `max_fps` frames per second. Returns the frames and the frame rate."""
|
| 78 |
+
w, h, fps, _ = probe(path)
|
| 79 |
+
s = min(1.0, long_side / max(w, h))
|
| 80 |
+
w2, h2 = max(16, int(w * s) // 16 * 16), max(16, int(h * s) // 16 * 16)
|
| 81 |
+
fps2 = min(fps, max_fps)
|
| 82 |
+
cmd = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
|
| 83 |
+
"-vf", f"fps={fps2:.6f},scale={w2}:{h2}:flags=lanczos", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
|
| 84 |
+
raw = subprocess.run(cmd, capture_output=True, check=True).stdout
|
| 85 |
+
frames = np.frombuffer(raw, np.uint8).reshape(-1, h2, w2, 3)
|
| 86 |
+
return frames, fps2
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def cut_audio(path, seconds, out, start=0.0):
|
| 90 |
+
"""The audio of the same span as a separate file (None if the video has no audio)."""
|
| 91 |
+
r = subprocess.run([FFMPEG, "-v", "error", "-y", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
|
| 92 |
+
"-vn", "-c:a", "aac", "-b:a", "160k", str(out)], capture_output=True)
|
| 93 |
+
return out if r.returncode == 0 and Path(out).exists() and Path(out).stat().st_size > 0 else None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@torch.no_grad()
|
| 97 |
+
def track(frames, prompt="person", point=None):
|
| 98 |
+
"""SAM 3 subject and other-people masks, (n, h, w) bool each. point: (x, y) fractions of the first frame (the
|
| 99 |
+
track under it), or None for the most central person."""
|
| 100 |
+
select = "point" if point is not None else "most_central"
|
| 101 |
+
subject, others = segment.track_subject(frames, prompt=prompt or "person", select=select,
|
| 102 |
+
point=point or (0.5, 0.5), device="cuda", dtype=torch.bfloat16)
|
| 103 |
+
return subject.numpy(), others.numpy()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _render(scene, strength, focal_depth, depth):
|
| 107 |
+
try:
|
| 108 |
+
return refocuser.render(scene, strength, focal_depth, depth=depth)
|
| 109 |
+
except Exception as e: # the Triton kernel failed to build here: use the reference attention
|
| 110 |
+
if not any("forward" in vars(m) for m in refocuser.renderer.modules()):
|
| 111 |
+
raise
|
| 112 |
+
print(f"fused attention unavailable ({type(e).__name__}: {e}); using the reference attention")
|
| 113 |
+
for m in refocuser.renderer.modules():
|
| 114 |
+
vars(m).pop("forward", None)
|
| 115 |
+
return refocuser.render(scene, strength, focal_depth, depth=depth)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@torch.no_grad()
|
| 119 |
+
def spotlight(frames, subject, others, strength=1.5, gap=0.6, grow=10, depth_smoothing=0.7, focus_smoothing=0.6):
|
| 120 |
+
"""Spotlight video (n, h, w, 3) uint8 and the edited depth of the first frame (h, w; 1 = far).
|
| 121 |
+
|
| 122 |
+
Depth is smoothed over frames with an exponential moving average (depth_smoothing), the focal depth is the median
|
| 123 |
+
depth inside the subject mask (smoothed with focus_smoothing), and frames where the subject is missing are
|
| 124 |
+
rendered with their own depth and the last focal depth."""
|
| 125 |
+
out = np.empty_like(frames)
|
| 126 |
+
prev, d_f, first_depth = None, None, None
|
| 127 |
+
for i, frame in enumerate(frames):
|
| 128 |
+
image = image_to_tensor(frame).cuda()
|
| 129 |
+
depth = refocuser.depth_estimator(image)
|
| 130 |
+
prev = depth if prev is None or depth_smoothing <= 0 else depth_smoothing * prev + (1 - depth_smoothing) * depth
|
| 131 |
+
m = torch.from_numpy(subject[i]).cuda()
|
| 132 |
+
present = int(m.sum()) > 50
|
| 133 |
+
target = float(prev[0][m].median()) if present else (d_f if d_f is not None else float(prev.median()))
|
| 134 |
+
d_f = target if d_f is None or focus_smoothing <= 0 else focus_smoothing * d_f + (1 - focus_smoothing) * target
|
| 135 |
+
if present:
|
| 136 |
+
o = torch.from_numpy(others[i]).cuda()
|
| 137 |
+
edited, _ = depth_edits.spotlight(prev, m[None], d_f, gap, others=o[None], grow=grow)
|
| 138 |
+
else:
|
| 139 |
+
edited = prev
|
| 140 |
+
y = _render(Scene(image, prev), strength, d_f, edited)
|
| 141 |
+
out[i] = (y[0].clamp(0, 1).permute(1, 2, 0) * 255).round().byte().cpu().numpy()
|
| 142 |
+
if first_depth is None:
|
| 143 |
+
first_depth = edited[0].float().cpu().numpy()
|
| 144 |
+
return out, first_depth
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def write_video(frames, fps, path, audio=None):
|
| 148 |
+
"""H.264 (yuv420p, plays in browsers) with the audio track, if any."""
|
| 149 |
+
from flashrefocus.video import VideoWriter
|
| 150 |
+
with VideoWriter(path, fps=fps, quality=18, audio_from=audio) as writer:
|
| 151 |
+
writer.write(frames)
|
| 152 |
+
return path
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if __name__ == "__main__":
|
| 156 |
+
print(json.dumps({"ffmpeg": FFMPEG}))
|
flashrefocus/README.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# `flashrefocus` package: options and details
|
| 2 |
+
|
| 3 |
+
The [top-level README](../README.md) covers the common use. This page lists the remaining options of the Python API.
|
| 4 |
+
|
| 5 |
+
## Loading
|
| 6 |
+
|
| 7 |
+
`Refocuser.from_pretrained(...)` loads Stage I (restoration), the depth estimator and the renderer.
|
| 8 |
+
|
| 9 |
+
| Argument | Default | Effect |
|
| 10 |
+
|---|---|---|
|
| 11 |
+
| `deblurring` | `True` | `False` loads only the depth estimator and the renderer, for images that are already sharp. Stage I and its pinned `diffusers` / `transformers` are then not imported, so this also runs next to a recent `transformers` (needed for SAM 3). |
|
| 12 |
+
| `detail_weight` | `1.25` | ω, the blend of the pixel and pixel + detail predictions of Stage I (higher: more synthesized detail). |
|
| 13 |
+
| `refiner` | released refiner | `None` decodes with the SD 2.1 VAE decoder instead of the decoder refiner. |
|
| 14 |
+
| `refiner_dtype` | `bfloat16` | The cost benchmark (paper, Table 6) uses `float16`. |
|
| 15 |
+
| `render_dtype` | `bfloat16` | `None` renders in fp32. |
|
| 16 |
+
| `channels_last` | `False` | The cost benchmark uses `True`. |
|
| 17 |
+
| `merge_vae_lora` | `False` | Merges the VAE-encoder LoRA: about 20% faster encoder, outputs about 60 dB from the exact ones. |
|
| 18 |
+
| `fused` | `False` | Fused attention kernel for the renderer, see [Speed-ups](#speed-ups). |
|
| 19 |
+
| `compile` | `False` | `"static"` or `"dynamic"`: compiles Stage I, see [Speed-ups](#speed-ups). |
|
| 20 |
+
|
| 21 |
+
Stage I alone: `flashrefocus.deblurring.Deblurrer.from_pretrained()(x)` restores an image `x` in [-1, 1].
|
| 22 |
+
`Deblurrer.from_pretrained(separate_unets=True)` keeps the pixel and pixel + detail U-Nets as two modules instead of
|
| 23 |
+
swapping weights in place (same output, twice the U-Net memory), as the Hugging Face demo does on ZeroGPU.
|
| 24 |
+
|
| 25 |
+
## Scenes and rendering
|
| 26 |
+
|
| 27 |
+
- `refocuser.prepare(image, deblur=True)` returns a `Scene`: the restored image (quantized to 8 bits, as when it is
|
| 28 |
+
saved and reloaded) and its depth. `deblur=False` skips Stage I. Image sides must be multiples of 16
|
| 29 |
+
(`image_io.read_image(path, device, multiple=16)` or `image_io.resize_to_multiple` pad or resize).
|
| 30 |
+
- `scene.focal_depth_at(x, y)` gives the focal depth D_f of a pixel.
|
| 31 |
+
- `refocuser.render(scene, strength, focal_depth, depth=None)` returns the result (b, 3, H, W) in [0, 1]. The strength K
|
| 32 |
+
is trained in [0, 1]; larger values extrapolate. `depth` replaces the scene depth, for the edits in
|
| 33 |
+
[`rendering/depth_edits.py`](rendering/depth_edits.py) (listed in the top-level README under Applications).
|
| 34 |
+
- `render` takes the focal depth rather than a pixel, so a video can be processed as one `Scene` per frame, with D_f
|
| 35 |
+
and K chosen per frame (for example smoothed over time).
|
| 36 |
+
- `refocuser.render_batch(images, depths, strengths, focal_depths)` renders several frames in one call, with one
|
| 37 |
+
strength and focal depth per frame. It gives the same result as rendering them one by one. At video resolutions one
|
| 38 |
+
frame already fills a large GPU, so it is a convenience, not a speed-up.
|
| 39 |
+
|
| 40 |
+
## Depth edits
|
| 41 |
+
|
| 42 |
+
Every effect replaces the depth passed to `render`. The renderer was trained with one focal plane and one strength per
|
| 43 |
+
image, so all of them are zero-shot.
|
| 44 |
+
|
| 45 |
+
| Effect | `depth_edits` function | ComfyUI node |
|
| 46 |
+
|---|---|---|
|
| 47 |
+
| Focus range: a thick focal plane, separate from the aperture | `focus_range` | Focus Range |
|
| 48 |
+
| Radial (Lensbaby-style) focus around a point | `radial_focus` | Radial Focus |
|
| 49 |
+
| Tilt-shift band at any angle | `tilted_band` (`tilt_shift` for horizontal) | Tilt-Shift |
|
| 50 |
+
| Blur only the background, or only the foreground | `one_sided` | One-Sided Blur |
|
| 51 |
+
| Two, three or more focal planes | `focal_planes` (`two_focal_planes`) | Add Focal Plane |
|
| 52 |
+
| Keep a masked subject sharp while the focus moves | `keep_sharp` | Focus on Mask, Mask Depth Edit |
|
| 53 |
+
| Remove a photobomber: push him into the background bokeh (no inpainting) | `set_mask_depth(…, 1.0)` | Mask Depth Edit (`push_far`) |
|
| 54 |
+
| Optical privacy blur for faces or plates | `move_away` | Mask Depth Edit (`move_away`) |
|
| 55 |
+
| Per-layer blur, or a front layer for a flat picture | `set_mask_depth` | Mask Depth Edit (`set_depth`) |
|
| 56 |
+
| Isolate a subject: everything else at least a set distance from focus | `isolate` | Mask Depth Edit (`isolate`) |
|
| 57 |
+
| Portrait mode on a sharp photograph (skip Stage I) | `prepare(image, deblur=False)` | Prepare (`already_sharp`) |
|
| 58 |
+
| Video focus pull | one `Scene` per frame, smoothed depth and focus | Prepare + Focus Point with an image batch |
|
| 59 |
+
| Video spotlight (one subject sharp, everyone else blurred) | `spotlight` + `flashrefocus.segment.track_subject` (SAM 3) | SAM 3 Subject + Spotlight |
|
| 60 |
+
| Burnt-in titles kept sharp in video | `flashrefocus.overlays.fill_region` / `paste_back` | Overlay Fill + Overlay Paste Back |
|
| 61 |
+
|
| 62 |
+
In Python:
|
| 63 |
+
|
| 64 |
+
```python
|
| 65 |
+
from flashrefocus.rendering import depth_edits
|
| 66 |
+
|
| 67 |
+
_, H, W = scene.depth.shape # scene = refocuser.prepare(...); focal_depth = scene.focal_depth_at(x, y)
|
| 68 |
+
edits = {
|
| 69 |
+
"focus_range": (depth_edits.focus_range(scene.depth, focal_depth, width=0.2), focal_depth),
|
| 70 |
+
"background_only": (depth_edits.one_sided(scene.depth, focal_depth, keep="foreground"), focal_depth),
|
| 71 |
+
"three_planes": (depth_edits.focal_planes(scene.depth, [focal_depth, scene.focal_depth_at(x2, y2), 0.9]), focal_depth),
|
| 72 |
+
"radial": (depth_edits.radial_focus(H, W, 0.5, 0.6, radius=0.12, device="cuda"), 0.5),
|
| 73 |
+
"tilt_shift_20deg": (depth_edits.tilted_band(H, W, 0.5, 0.6, angle=20, device="cuda"), 0.5),
|
| 74 |
+
"keep_sharp": (depth_edits.keep_sharp(scene.depth, mask, focal_depth), focal_depth), # mask: H x W bool
|
| 75 |
+
"remove_photobomber": (depth_edits.set_mask_depth(scene.depth, mask, 1.0), focal_depth),
|
| 76 |
+
"privacy_blur": (depth_edits.move_away(scene.depth, mask, focal_depth, 0.3), focal_depth),
|
| 77 |
+
"isolate_subject": (depth_edits.isolate(scene.depth, mask, focal_depth, 0.25), focal_depth),
|
| 78 |
+
}
|
| 79 |
+
for name, (depth, d_f) in edits.items():
|
| 80 |
+
save_image(refocuser.render(scene, 0.8, d_f, depth=depth), f"{name}.png") # about half a second each
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
`mask` is an H x W bool tensor from any segmenter, for example Segment Anything from a click or a box, or CLIPSeg from
|
| 84 |
+
a text prompt.
|
| 85 |
+
|
| 86 |
+
## Video spotlight
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
from flashrefocus.segment import track_subject # SAM 3: transformers >= 4.57, access to facebook/sam3
|
| 90 |
+
from flashrefocus.rendering import depth_edits
|
| 91 |
+
|
| 92 |
+
refocuser = Refocuser.from_pretrained(deblurring=False, fused=True)
|
| 93 |
+
subject, others = track_subject(frames, prompt="person", select="most_central") # frames: (n, h, w, 3) uint8
|
| 94 |
+
for frame, m, o in zip(frames_as_tensors, subject, others):
|
| 95 |
+
scene = refocuser.prepare(frame, deblur=False)
|
| 96 |
+
d_f = float(scene.depth[0][m].median()) # smooth over frames in practice
|
| 97 |
+
depth, _ = depth_edits.spotlight(scene.depth, m[None], d_f, gap=0.6, others=o[None], grow=10)
|
| 98 |
+
out = refocuser.render(scene, 1.5, d_f, depth=depth)
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
- `track_subject(frames, prompt, select, point, chunk)` tracks every instance of `prompt` with SAM 3, in chunks of
|
| 102 |
+
`chunk` frames. It returns the chosen subject's masks and the union of the other tracks. `select` is
|
| 103 |
+
`"most_central"`, `"largest"` or `"point"` (the track under `point`, given as fractions of width and height). The
|
| 104 |
+
subject is carried from one chunk to the next by mask overlap.
|
| 105 |
+
- `spotlight(depth, mask, focal_depth, gap, others, grow)` sets the subject to the focal depth and moves every other
|
| 106 |
+
pixel at least `gap` from it. First it grows the mask by up to `grow` pixels into neighbouring pixels at the
|
| 107 |
+
subject's depth that are not in `others` (hands and hair that segmentation misses).
|
| 108 |
+
- Burnt-in titles: `overlays.fill_region(image, mask)` fills the title from its surroundings before rendering, so the
|
| 109 |
+
renderer does not blur the letters into a flickering glow. `overlays.paste_back(result, original, mask)` then puts
|
| 110 |
+
the sharp title back.
|
| 111 |
+
|
| 112 |
+
## Writing results
|
| 113 |
+
|
| 114 |
+
- `image_io.save_image(x, path, background=True)` copies the image to the CPU at once and compresses and writes the PNG
|
| 115 |
+
on a background thread (the same file, byte for byte). `image_io.wait_for_writes()` waits for pending files.
|
| 116 |
+
- `video.VideoWriter(path, fps, codec="auto", quality=18, audio_from=None)` streams frames into one ffmpeg encode from
|
| 117 |
+
a background thread, so encoding overlaps rendering. It picks the first encoder that works: NVENC, libx264,
|
| 118 |
+
libopenh264, then mpeg4. `audio_from=` copies the audio of the source clip. ffmpeg is taken from
|
| 119 |
+
`$FLASHREFOCUS_FFMPEG`, `imageio-ffmpeg`, or `PATH`.
|
| 120 |
+
|
| 121 |
+
```python
|
| 122 |
+
from flashrefocus.video import VideoWriter
|
| 123 |
+
|
| 124 |
+
with VideoWriter("refocused.mp4", fps=30, audio_from="clip.mp4") as writer:
|
| 125 |
+
for scene, d_f in zip(scenes, focal_depths):
|
| 126 |
+
writer.write(refocuser.render(scene, 1.0, d_f))
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
## Speed-ups
|
| 130 |
+
|
| 131 |
+
Both options are off by default, so the reported numbers are reproduced exactly. ComfyUI and the demo turn `fused` on.
|
| 132 |
+
|
| 133 |
+
- **`fused=True`** runs the renderer's defocus-bias attention as one Triton kernel
|
| 134 |
+
([`rendering/fused.py`](rendering/fused.py)). The kernel computes the defocus bias from the per-token defocus values
|
| 135 |
+
and uses an online softmax, so the per-row and per-column bias and attention matrices are never stored. Weights are
|
| 136 |
+
unchanged, and outputs match the reference path to about 61 dB in bf16 and 80 dB in fp32. On an RTX PRO 6000,
|
| 137 |
+
the renderer alone takes 72 ms instead of 170 ms at 1536×1536. At 3840×1728 it takes 229 ms instead of 740 ms, and
|
| 138 |
+
peak memory drops from 16.1 to 3.0 GiB. Without Triton, or on CPU, the reference code runs.
|
| 139 |
+
`rendering.fused.enable_fused(renderer)` switches a renderer that is already loaded.
|
| 140 |
+
- **`compile="static"`** (or `"dynamic"`) compiles Stage I's two full-resolution parts, the decoder refiner and the VAE
|
| 141 |
+
encoder, with `torch.compile`. Restoration is about 35-40% faster after a one-time compilation of one to two
|
| 142 |
+
minutes, and outputs match the eager path to about 57-62 dB. `"static"` is fastest for many images of one size and
|
| 143 |
+
recompiles for a new size. `"dynamic"` compiles once for all sizes and is about 10% slower.
|
| 144 |
+
|
| 145 |
+
## Reproducibility
|
| 146 |
+
|
| 147 |
+
Outputs are bit-reproducible with `torch.backends.cudnn.benchmark = False`. cuDNN autotuning is faster for a fixed
|
| 148 |
+
input size, but it may pick different convolution algorithms between runs, which changes outputs by a few 1/255.
|
| 149 |
+
|
| 150 |
+
## Tests
|
| 151 |
+
|
| 152 |
+
The regression test restores two small photographs in `tests/data/` and compares the restored image, depth, refocused
|
| 153 |
+
image, two focal planes and tilt-shift with `tests/reference/`: bit-identical on the machine that made the references,
|
| 154 |
+
PSNR >= 45 dB elsewhere (floating-point differences between GPUs and library versions). Regenerate the references with
|
| 155 |
+
`python tests/regression_cases.py` only when an output changes on purpose.
|
flashrefocus/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FlashReFocus: interactive image refocusing. Stage I deblurs once with one-step diffusion (flashrefocus.deblurring),
|
| 2 |
+
Stage II renders every focal edit with a lightweight defocus-aware renderer (flashrefocus.rendering);
|
| 3 |
+
flashrefocus.pipeline combines them."""
|
| 4 |
+
from .pipeline import Refocuser, Scene
|
| 5 |
+
|
| 6 |
+
__all__ = ["Refocuser", "Scene"]
|
flashrefocus/_compat.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compatibility with newer libraries than the ones the code was written for."""
|
| 2 |
+
import huggingface_hub
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def patch_huggingface_hub():
|
| 6 |
+
"""diffusers 0.25 (required by PiSA-SR's model code) imports huggingface_hub.cached_download, removed in hub 0.26.
|
| 7 |
+
Call before importing diffusers."""
|
| 8 |
+
if not hasattr(huggingface_hub, "cached_download"):
|
| 9 |
+
huggingface_hub.cached_download = huggingface_hub.hf_hub_download
|
flashrefocus/deblurring/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage I: one-step diffusion deblurring (Sec. 3.1)."""
|
| 2 |
+
from .deblurrer import Deblurrer
|
| 3 |
+
|
| 4 |
+
__all__ = ["Deblurrer"]
|
flashrefocus/deblurring/deblurrer.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage I end to end: blurred image -> restored all-in-focus image (one-step diffusion, then the decoder refiner or the
|
| 2 |
+
SD2.1 VAE decoder). Images are 1 x 3 x H x W in [-1, 1], H and W multiples of 8."""
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from .. import paths
|
| 6 |
+
from .decoder_refiner import load_decoder_refiner
|
| 7 |
+
from .one_step_diffusion import load_one_step_diffusion
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Deblurrer:
|
| 11 |
+
def __init__(self, model, refiner=None):
|
| 12 |
+
self.model, self.refiner = model, refiner
|
| 13 |
+
self.scaling_factor = model.vae.config.scaling_factor
|
| 14 |
+
self.prompt_embedding = model.empty_prompt_embedding()
|
| 15 |
+
|
| 16 |
+
@classmethod
|
| 17 |
+
def from_pretrained(cls, checkpoint=paths.STAGE1, refiner=paths.REFINER, detail_weight=1.25,
|
| 18 |
+
refiner_dtype=torch.bfloat16, merge_vae_lora=False, separate_unets=False, device="cuda",
|
| 19 |
+
compile=False):
|
| 20 |
+
"""The released Stage I; refiner=None decodes with the SD2.1 VAE decoder instead. See one_step_diffusion for
|
| 21 |
+
separate_unets. The one-step model is built on the device PiSA-SR builds on (cuda, see its code).
|
| 22 |
+
compile: see Deblurrer.compile (False, "static" or "dynamic")."""
|
| 23 |
+
model = load_one_step_diffusion(checkpoint, detail_weight=detail_weight, merge_vae_lora=merge_vae_lora,
|
| 24 |
+
separate_unets=separate_unets)
|
| 25 |
+
refiner = load_decoder_refiner(refiner, dtype=refiner_dtype, device=device) if refiner is not None else None
|
| 26 |
+
deblurrer = cls(model, refiner)
|
| 27 |
+
if compile:
|
| 28 |
+
deblurrer.compile(dynamic=compile == "dynamic")
|
| 29 |
+
return deblurrer
|
| 30 |
+
|
| 31 |
+
def compile(self, dynamic=False):
|
| 32 |
+
"""torch.compile the decoder refiner and the VAE encoder, the two full-resolution parts of Stage I (the refiner
|
| 33 |
+
alone is about 70% of its time): Inductor fuses their many GroupNorm / SiLU / NAF LayerNorm and gating
|
| 34 |
+
operations around the convolutions. Same weights; outputs match the eager path to ~62 dB (bf16 rounding).
|
| 35 |
+
dynamic=False compiles once per input size (fastest, for many images of one size; a new size costs a
|
| 36 |
+
recompilation); dynamic=True compiles shape-generic code once (~10% slower, no recompilation per size). The
|
| 37 |
+
first call compiles (one to two minutes). The U-Net is left eager: its attention already runs
|
| 38 |
+
FlashAttention, and its weights are swapped in place between the two passes."""
|
| 39 |
+
if self.refiner is not None:
|
| 40 |
+
self.refiner.forward = torch.compile(self.refiner.forward, dynamic=dynamic)
|
| 41 |
+
self.model.vae.encoder.forward = torch.compile(self.model.vae.encoder.forward, dynamic=dynamic)
|
| 42 |
+
return self
|
| 43 |
+
|
| 44 |
+
def to(self, device):
|
| 45 |
+
"""Move the modules that run (VAE, U-Net(s), refiner) and the prompt embedding; the text encoder stays."""
|
| 46 |
+
for module in (self.model.vae, self.model.unet, getattr(self.model, "unet_pixel", None), self.refiner):
|
| 47 |
+
if module is not None:
|
| 48 |
+
module.to(device)
|
| 49 |
+
self.prompt_embedding = self.prompt_embedding.to(device)
|
| 50 |
+
return self
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def detail_weight(self):
|
| 54 |
+
return self.model.detail_weight
|
| 55 |
+
|
| 56 |
+
@detail_weight.setter
|
| 57 |
+
def detail_weight(self, omega):
|
| 58 |
+
self.model.detail_weight = omega
|
| 59 |
+
|
| 60 |
+
@torch.no_grad()
|
| 61 |
+
def restored_latent(self, x):
|
| 62 |
+
"""z_hat / scaling_factor, as the VAE decoder takes it."""
|
| 63 |
+
z = self.model.vae.encode(x.to(self.model.weight_dtype)).latent_dist.mode() * self.scaling_factor
|
| 64 |
+
emb = self.prompt_embedding.expand(z.shape[0], -1, -1)
|
| 65 |
+
return (z - self.model.predict_noise(z, emb)) / self.scaling_factor
|
| 66 |
+
|
| 67 |
+
@torch.no_grad()
|
| 68 |
+
def __call__(self, x, refiner_tile=0, refiner_overlap=64):
|
| 69 |
+
"""Restored image in [-1, 1] (not clamped); refiner_tile > 0 runs the refiner on overlapping tiles."""
|
| 70 |
+
latent = self.restored_latent(x)
|
| 71 |
+
if self.refiner is None:
|
| 72 |
+
return self.model.vae.decode(latent).sample
|
| 73 |
+
dtype = next(self.refiner.parameters()).dtype
|
| 74 |
+
x, latent = x.to(dtype), latent.to(dtype)
|
| 75 |
+
if refiner_tile > 0:
|
| 76 |
+
return refine_in_tiles(self.refiner, x, latent, refiner_tile, refiner_overlap)
|
| 77 |
+
return self.refiner(x, latent)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@torch.no_grad()
|
| 81 |
+
def refine_in_tiles(refiner, x, latent, tile, overlap):
|
| 82 |
+
"""The refiner on overlapping pixel tiles (multiples of 8), blended with linear ramps; bounds memory."""
|
| 83 |
+
_, _, H, W = x.shape
|
| 84 |
+
tile, overlap = tile - tile % 8, overlap - overlap % 8
|
| 85 |
+
starts = lambda n: sorted({min(p, max(0, n - tile)) for p in range(0, max(1, n - overlap), tile - overlap)})
|
| 86 |
+
out = torch.zeros_like(x, dtype=torch.float32)
|
| 87 |
+
weight_sum = torch.zeros((1, 1, H, W), device=x.device)
|
| 88 |
+
ramp = torch.linspace(0, 1, overlap + 2, device=x.device)[1:-1]
|
| 89 |
+
for t in starts(H):
|
| 90 |
+
for l in starts(W):
|
| 91 |
+
b, r = min(t + tile, H), min(l + tile, W)
|
| 92 |
+
tile_out = refiner(x[:, :, t:b, l:r], latent[:, :, t // 8:b // 8, l // 8:r // 8]).float()
|
| 93 |
+
wy, wx = torch.ones(b - t, device=x.device), torch.ones(r - l, device=x.device)
|
| 94 |
+
if overlap:
|
| 95 |
+
if t > 0: wy[:overlap] = ramp
|
| 96 |
+
if b < H: wy[-overlap:] = ramp.flip(0)
|
| 97 |
+
if l > 0: wx[:overlap] = ramp
|
| 98 |
+
if r < W: wx[-overlap:] = ramp.flip(0)
|
| 99 |
+
w = (wy[:, None] * wx[None, :])[None, None]
|
| 100 |
+
out[:, :, t:b, l:r] += tile_out * w
|
| 101 |
+
weight_sum[:, :, t:b, l:r] += w
|
| 102 |
+
return out / weight_sum.clamp_min(1e-6)
|
flashrefocus/deblurring/decoder_refiner.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Decoder refiner (Sec. 3.1, Appendix B.2): the Stable Diffusion 1.5 VAE decoder with fusion modules that inject
|
| 2 |
+
features of the blurred input into its up-blocks, recovering structure that VAE decoding loses.
|
| 3 |
+
|
| 4 |
+
SD1.5 and SD2.1 share the VAE encoder and quant_conv, so the refiner decodes the latents of the SD2.1-based Stage I.
|
| 5 |
+
The input enters as (a) the VAE-encoder features at the resolutions of the decoder stages (conv_in, down-blocks 0 and 1,
|
| 6 |
+
matched by spatial size) and (b) a guidance map computed from the image and its high-frequency magnitude
|
| 7 |
+
(Laplacian-pyramid residual), shared by every fusion module. Each fusion module adds a zero-initialised residual to the
|
| 8 |
+
decoder feature, so training starts from the plain decoder. Parameter names follow the released checkpoint."""
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torchvision.transforms.functional import gaussian_blur
|
| 13 |
+
|
| 14 |
+
from .. import paths
|
| 15 |
+
from .._compat import patch_huggingface_hub
|
| 16 |
+
from ..layers import NAFBlock
|
| 17 |
+
|
| 18 |
+
patch_huggingface_hub() # before diffusers is imported
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def high_frequency_residual(image, kernel_size=5, sigma=1.0):
|
| 22 |
+
"""image minus its blurred 2x down-up-sampled version (one Laplacian-pyramid level)."""
|
| 23 |
+
low = gaussian_blur(image, kernel_size=kernel_size, sigma=sigma)[:, :, ::2, ::2]
|
| 24 |
+
up = gaussian_blur(F.interpolate(low, size=image.shape[-2:], mode="bilinear", align_corners=False),
|
| 25 |
+
kernel_size=kernel_size, sigma=sigma)
|
| 26 |
+
return image - up
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class FeatureFusion(nn.Module):
|
| 30 |
+
"""Decoder feature + fusion of (encoder feature, decoder feature, guidance map)."""
|
| 31 |
+
|
| 32 |
+
def __init__(self, decoder_channels, encoder_channels, guidance_channels, depth):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.in_conv = nn.Conv2d(encoder_channels + decoder_channels, decoder_channels, 3, 1, 1)
|
| 35 |
+
self.dm_blocks = nn.ModuleList([NAFBlock(decoder_channels + guidance_channels) for _ in range(depth)])
|
| 36 |
+
self.out_conv = nn.Conv2d(decoder_channels + guidance_channels, decoder_channels, 3, 1, 1)
|
| 37 |
+
|
| 38 |
+
def forward(self, encoder_feat, decoder_feat, guidance):
|
| 39 |
+
if guidance.shape[-2:] != decoder_feat.shape[-2:]:
|
| 40 |
+
guidance = F.interpolate(guidance, size=decoder_feat.shape[-2:], mode="bilinear", align_corners=False)
|
| 41 |
+
fused = torch.cat((self.in_conv(torch.cat((encoder_feat, decoder_feat), dim=1)), guidance), dim=1)
|
| 42 |
+
for block in self.dm_blocks:
|
| 43 |
+
fused = block(fused)
|
| 44 |
+
return self.out_conv(fused) + decoder_feat
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _last_resnet_channels(block):
|
| 48 |
+
return int(block.resnets[-1].out_channels)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class DecoderRefiner(nn.Module):
|
| 52 |
+
ENCODER_STAGES = 2 # down-blocks whose features the decoder can match (the decoder runs at H/4, H/2, H, H)
|
| 53 |
+
|
| 54 |
+
def __init__(self, vae, depth=2, guidance_channels=32):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.vae = vae
|
| 57 |
+
decoder_channels = [_last_resnet_channels(b) for b in vae.decoder.up_blocks]
|
| 58 |
+
encoder_channels = [int(vae.encoder.conv_in.out_channels)] + [_last_resnet_channels(b) for b in vae.encoder.down_blocks]
|
| 59 |
+
n = len(decoder_channels)
|
| 60 |
+
self.fusion_blocks = nn.ModuleList([
|
| 61 |
+
FeatureFusion(dec, encoder_channels[max(0, n - 2 - i)], guidance_channels, depth)
|
| 62 |
+
for i, dec in enumerate(decoder_channels)])
|
| 63 |
+
self.map_init = nn.Sequential(nn.Conv2d(3 + 1, guidance_channels, 3, 1, 1), # image + high frequency
|
| 64 |
+
*[NAFBlock(guidance_channels) for _ in range(depth)])
|
| 65 |
+
for block in self.fusion_blocks:
|
| 66 |
+
nn.init.zeros_(block.out_conv.weight)
|
| 67 |
+
nn.init.zeros_(block.out_conv.bias)
|
| 68 |
+
|
| 69 |
+
def encoder_features(self, image):
|
| 70 |
+
"""VAE-encoder features at the resolutions of the decoder stages: conv_in and the first down-blocks."""
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
h = self.vae.encoder.conv_in(image)
|
| 73 |
+
feats = [h.detach()]
|
| 74 |
+
for block in self.vae.encoder.down_blocks[:self.ENCODER_STAGES]:
|
| 75 |
+
h = block(h)
|
| 76 |
+
feats.append(h.detach())
|
| 77 |
+
return feats
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def _matching_feature(decoder_feat, encoder_features):
|
| 81 |
+
for feat in reversed(encoder_features):
|
| 82 |
+
if feat.shape[0] == decoder_feat.shape[0] and feat.shape[-2:] == decoder_feat.shape[-2:]:
|
| 83 |
+
return feat
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
def forward(self, image, latent):
|
| 87 |
+
"""image: the blurred input in [-1, 1]; latent: the restored latent (unscaled). Returns the image in [-1, 1]."""
|
| 88 |
+
encoder_features = self.encoder_features(image)
|
| 89 |
+
high_freq = high_frequency_residual(image).abs().mean(dim=1, keepdim=True)
|
| 90 |
+
guidance = self.map_init(torch.cat((image, high_freq), dim=1))
|
| 91 |
+
h = self.vae.decoder.mid_block(self.vae.decoder.conv_in(self.vae.post_quant_conv(latent)))
|
| 92 |
+
for block, fusion in zip(self.vae.decoder.up_blocks, self.fusion_blocks):
|
| 93 |
+
h = block(h)
|
| 94 |
+
feat = self._matching_feature(h, encoder_features)
|
| 95 |
+
if feat is not None:
|
| 96 |
+
h = fusion(feat, h, guidance)
|
| 97 |
+
return self.vae.decoder.conv_out(self.vae.decoder.conv_act(self.vae.decoder.conv_norm_out(h)))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def build_decoder_refiner(sd15=paths.SD15):
|
| 101 |
+
from diffusers import AutoencoderKL
|
| 102 |
+
return DecoderRefiner(AutoencoderKL.from_pretrained(str(sd15), subfolder="vae"))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def load_decoder_refiner(path=paths.REFINER, sd15=paths.SD15, device="cuda", dtype=torch.bfloat16):
|
| 106 |
+
"""The released refiner, in bf16 as trained. Its checkpoint stores every parameter except the VAE encoder, which
|
| 107 |
+
comes from SD1.5 (only its first two down-blocks run)."""
|
| 108 |
+
refiner = build_decoder_refiner(sd15)
|
| 109 |
+
res = refiner.load_state_dict(torch.load(str(path), map_location="cpu"), strict=False)
|
| 110 |
+
missing = [k for k in res.missing_keys if not k.startswith(("vae.encoder", "vae.quant_conv", "vae.post_quant_conv"))]
|
| 111 |
+
assert not missing and not res.unexpected_keys, (missing[:5], res.unexpected_keys[:5])
|
| 112 |
+
return refiner.to(device, dtype=dtype).eval()
|
flashrefocus/deblurring/one_step_diffusion.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage I one-step diffusion model (Sec. 3.1): Stable Diffusion 2.1 with a pixel LoRA and a detail LoRA, adapted from
|
| 2 |
+
PiSA-SR (third_party/PiSA-SR). The restored latent is z_hat = z_blur - eps(z_blur), with eps the U-Net prediction at
|
| 3 |
+
timestep 1 and an empty prompt, and
|
| 4 |
+
|
| 5 |
+
eps = eps_pix + omega * (eps_pix+det - eps_pix)
|
| 6 |
+
|
| 7 |
+
where eps_pix uses the pixel LoRA alone, eps_pix+det both LoRAs and omega is the detail weight. omega = 1 is a single
|
| 8 |
+
U-Net pass with both LoRAs merged; any other omega needs both predictions (two passes).
|
| 9 |
+
|
| 10 |
+
With separate_unets=True the two predictions come from two U-Nets (pixel; pixel + detail) instead of one U-Net whose
|
| 11 |
+
weights are swapped in place between the passes: twice the U-Net memory, the same output, and every model is an
|
| 12 |
+
ordinary module, as needed to move it between devices (e.g. Hugging Face ZeroGPU) or to wrap it.
|
| 13 |
+
|
| 14 |
+
PiSA-SR names the detail LoRA "sem" (semantic) and omega "lambda_sem"; these names remain in its checkpoint keys."""
|
| 15 |
+
import argparse
|
| 16 |
+
import copy
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from .. import paths
|
| 21 |
+
from .._compat import patch_huggingface_hub
|
| 22 |
+
|
| 23 |
+
patch_huggingface_hub() # before diffusers is imported
|
| 24 |
+
|
| 25 |
+
NO_TILING = 100000 # tile sizes above any input: the whole image is processed at once
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _pisa_sr_eval_class():
|
| 29 |
+
paths.use_third_party(paths.PISA_SR)
|
| 30 |
+
from pisasr import PiSASR_eval
|
| 31 |
+
return PiSASR_eval
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class OneStepDiffusion(_pisa_sr_eval_class()):
|
| 35 |
+
"""PiSA-SR's evaluation model with the changes needed for deblurring:
|
| 36 |
+
* deterministic VAE encoding (latent_dist.mode()), so the restored image is reproducible;
|
| 37 |
+
* the Stage I extras of our checkpoints (trained U-Net conv_in, LoRA on the VAE encoder);
|
| 38 |
+
* the merged pixel + detail weights of the two-pass mode are built once and reused."""
|
| 39 |
+
|
| 40 |
+
def _load_pretrained_weights(self, pretrained_path):
|
| 41 |
+
sd = torch.load(pretrained_path, map_location="cpu")
|
| 42 |
+
if "conv_in" in sd: # base weights, before the pixel LoRA is merged on top
|
| 43 |
+
self.unet.load_state_dict(sd["conv_in"], strict=False)
|
| 44 |
+
self._load_and_save_ckpt_from_state_dict(sd)
|
| 45 |
+
if "state_dict_vae" in sd:
|
| 46 |
+
from peft import LoraConfig
|
| 47 |
+
self.vae.add_adapter(LoraConfig(r=sd["vae_lora_rank"], init_lora_weights="gaussian",
|
| 48 |
+
target_modules=sd["vae_lora_encoder_modules"]), adapter_name="vae_enc")
|
| 49 |
+
for n, p in self.vae.named_parameters():
|
| 50 |
+
if n in sd["state_dict_vae"]:
|
| 51 |
+
p.data.copy_(sd["state_dict_vae"][n])
|
| 52 |
+
|
| 53 |
+
def _apply_lora_delta(self):
|
| 54 |
+
# back to the pixel + detail weights after the pixel-only pass, without re-adding the deltas every call
|
| 55 |
+
if getattr(self, "_merged_weight", None) is None:
|
| 56 |
+
self._merged_weight = {n: self.lora_deltas_sem[n] + w if n in self.lora_deltas_sem else w
|
| 57 |
+
for n, w in self.ori_unet_weight.items()}
|
| 58 |
+
for name, param in self.unet.named_parameters():
|
| 59 |
+
param.data = self._merged_weight[name]
|
| 60 |
+
|
| 61 |
+
@property
|
| 62 |
+
def detail_weight(self):
|
| 63 |
+
"""omega"""
|
| 64 |
+
return float(self.lambda_sem)
|
| 65 |
+
|
| 66 |
+
@detail_weight.setter
|
| 67 |
+
def detail_weight(self, omega):
|
| 68 |
+
assert not self.single_pass or omega == 1.0, "load the model with detail_weight != 1 to change it"
|
| 69 |
+
self.lambda_sem = torch.tensor([float(omega)], device=self.device)
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def uses_single_pass(self):
|
| 73 |
+
"""One U-Net pass when loaded with omega = 1, or when omega is set back to 1."""
|
| 74 |
+
return self.single_pass or float(self.lambda_sem) == 1.0
|
| 75 |
+
|
| 76 |
+
@torch.no_grad()
|
| 77 |
+
def empty_prompt_embedding(self):
|
| 78 |
+
return self.encode_prompt([""]).to(dtype=self.weight_dtype)
|
| 79 |
+
|
| 80 |
+
def predict_noise(self, z, prompt_embeds):
|
| 81 |
+
"""eps for the latent z (whole latent, no tiling)."""
|
| 82 |
+
if not getattr(self, "separate_unets", False):
|
| 83 |
+
return self._predict_no_tiling(z, prompt_embeds, self.uses_single_pass)
|
| 84 |
+
t = torch.ones(1, dtype=torch.long, device=z.device) # timestep 1
|
| 85 |
+
eps = self.unet(z, t, encoder_hidden_states=prompt_embeds).sample
|
| 86 |
+
if self.uses_single_pass:
|
| 87 |
+
return eps
|
| 88 |
+
eps_pixel = self.unet_pixel(z, t, encoder_hidden_states=prompt_embeds).sample
|
| 89 |
+
eps -= eps_pixel # same operations as PiSA-SR's two passes
|
| 90 |
+
return self.lambda_pix.to(z.device) * eps_pixel + self.lambda_sem.to(z.device) * eps
|
| 91 |
+
|
| 92 |
+
def use_separate_unets(self):
|
| 93 |
+
"""Second U-Net with the pixel LoRA only (unet keeps pixel + detail); drops the weight tables of the swap."""
|
| 94 |
+
self.unet_pixel = copy.deepcopy(self.unet)
|
| 95 |
+
for name, p in self.unet_pixel.named_parameters():
|
| 96 |
+
p.data = self.ori_unet_weight[name].clone()
|
| 97 |
+
del self.ori_unet_weight, self.lora_deltas_sem, self._merged_weight
|
| 98 |
+
self.separate_unets = True
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_one_step_diffusion(checkpoint=paths.STAGE1, sd21=paths.SD21, detail_weight=1.0, precision="fp16",
|
| 102 |
+
merge_vae_lora=False, separate_unets=False):
|
| 103 |
+
"""Stage I in eval mode. detail_weight != 1 selects the two-pass mode, in which it can be changed later; 1 merges
|
| 104 |
+
the detail LoRA into a single pass.
|
| 105 |
+
merge_vae_lora folds the VAE-encoder LoRA into the encoder weights: the encoder runs ~20% faster, but the output is
|
| 106 |
+
no longer bit-identical to the reported results (about 60 dB PSNR apart), so it is off by default."""
|
| 107 |
+
single = detail_weight == 1.0
|
| 108 |
+
args = argparse.Namespace(pretrained_model_path=str(sd21), pretrained_path=str(checkpoint), lambda_pix=1.0,
|
| 109 |
+
lambda_sem=detail_weight, mixed_precision=precision, default=single,
|
| 110 |
+
vae_decoder_tiled_size=NO_TILING, vae_encoder_tiled_size=NO_TILING,
|
| 111 |
+
latent_tiled_size=NO_TILING, latent_tiled_overlap=0, seed=42)
|
| 112 |
+
model = OneStepDiffusion(args)
|
| 113 |
+
model.set_eval()
|
| 114 |
+
model.single_pass = single
|
| 115 |
+
if not single:
|
| 116 |
+
# Use the pixel + detail weights that every two-pass call restores after its pixel-only pass from the start.
|
| 117 |
+
# peft's own merge differs from them in the last bits, which made the first image restored differ slightly
|
| 118 |
+
# (up to 2/255) from later ones.
|
| 119 |
+
model._apply_lora_delta()
|
| 120 |
+
if separate_unets:
|
| 121 |
+
model.use_separate_unets()
|
| 122 |
+
if merge_vae_lora:
|
| 123 |
+
from peft.tuners.lora import LoraLayer
|
| 124 |
+
for mod in model.vae.modules():
|
| 125 |
+
if isinstance(mod, LoraLayer):
|
| 126 |
+
mod.merge()
|
| 127 |
+
return model
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def stage1_parameter_count(model, refiner=None):
|
| 131 |
+
"""Parameters of everything a configuration runs: text encoder, U-Net with merged LoRAs, VAE, and the refiner
|
| 132 |
+
without the VAE encoder it does not run."""
|
| 133 |
+
n = sum(p.numel() for m in (model.text_encoder, model.unet, model.vae) for p in m.parameters())
|
| 134 |
+
if refiner is not None:
|
| 135 |
+
n += sum(v.numel() for k, v in refiner.state_dict().items() if not k.startswith(("vae.encoder", "vae.quant_conv")))
|
| 136 |
+
return n
|
flashrefocus/image_io.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image <-> tensor conversion used everywhere, so that every script feeds the models the same values.
|
| 2 |
+
|
| 3 |
+
Images are 1 x 3 x H x W float tensors in [0, 1]; Stage I works in [-1, 1] (to_signed / to_unit_range). Conversion
|
| 4 |
+
matches torchvision's to_tensor / to_pil_image: division by 255, and quantisation by truncation."""
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def image_to_tensor(image, multiple=1):
|
| 11 |
+
"""PIL image (or HxWx3 uint8 array) -> 1x3xHxW float in [0, 1] on the CPU, cropped (bottom/right) to a multiple."""
|
| 12 |
+
arr = np.asarray(image.convert("RGB") if isinstance(image, Image.Image) else image)
|
| 13 |
+
h, w = arr.shape[0] - arr.shape[0] % multiple, arr.shape[1] - arr.shape[1] % multiple
|
| 14 |
+
return torch.from_numpy(np.array(arr[:h, :w])).permute(2, 0, 1).contiguous().float().div(255)[None]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def read_image(path, device="cpu", multiple=1):
|
| 18 |
+
return image_to_tensor(Image.open(path), multiple).to(device)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def tensor_to_uint8(x):
|
| 22 |
+
"""1x3xHxW float in [0, 1] -> HxWx3 uint8, quantised by truncation (quantised on the tensor's device)."""
|
| 23 |
+
return (x[0].float().clamp(0, 1) * 255.0).to(torch.uint8).permute(1, 2, 0).cpu().numpy()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_WRITER = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _png(arr, path, compress_level):
|
| 30 |
+
Image.fromarray(arr).save(path, compress_level=compress_level)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def save_image(x, path, compress_level=1, background=False):
|
| 34 |
+
"""Lossless PNG of a 1x3xHxW float tensor in [0, 1]; a low zlib level keeps writing fast.
|
| 35 |
+
|
| 36 |
+
PNG compression (zlib, single-threaded) takes far longer than rendering an edit (about 0.13 s at 1536x1536).
|
| 37 |
+
background=True quantises and copies the image to the CPU now (so `x` can be reused at once) and compresses and
|
| 38 |
+
writes the file on a background thread: an interactive caller can show the result without waiting for the file.
|
| 39 |
+
Returns a Future in that case; wait_for_writes() blocks until every pending file is written."""
|
| 40 |
+
arr = tensor_to_uint8(x)
|
| 41 |
+
if not background:
|
| 42 |
+
return _png(arr, path, compress_level)
|
| 43 |
+
global _WRITER
|
| 44 |
+
if _WRITER is None:
|
| 45 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 46 |
+
_WRITER = ThreadPoolExecutor(max_workers=2, thread_name_prefix="flashrefocus-png")
|
| 47 |
+
return _WRITER.submit(_png, arr, path, compress_level)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def wait_for_writes():
|
| 51 |
+
"""Block until every image saved with background=True is on disk."""
|
| 52 |
+
if _WRITER is not None:
|
| 53 |
+
_WRITER.shutdown(wait=True)
|
| 54 |
+
globals()["_WRITER"] = None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def to_signed(x):
|
| 58 |
+
"""[0, 1] -> [-1, 1] (Stage I input range)."""
|
| 59 |
+
return x * 2 - 1
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def to_unit_range(y):
|
| 63 |
+
"""[-1, 1] -> [0, 1] in float32, not clamped."""
|
| 64 |
+
return y.float() * 0.5 + 0.5
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def resize_to_multiple(image, long_side, multiple=16):
|
| 68 |
+
"""PIL image with its long side at most `long_side` and both sides multiples of `multiple` (LANCZOS)."""
|
| 69 |
+
s = min(1.0, long_side / max(image.size))
|
| 70 |
+
w = max(multiple, int(image.width * s) // multiple * multiple)
|
| 71 |
+
h = max(multiple, int(image.height * s) // multiple * multiple)
|
| 72 |
+
return image.convert("RGB").resize((w, h), Image.LANCZOS)
|
flashrefocus/layers.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layers shared by the decoder refiner (Stage I) and the renderer (Stage II): the NAFNet block and its parts."""
|
| 2 |
+
from math import floor
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import nn
|
| 6 |
+
from torch.autograd import Function
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class LayerNormFunction(Function):
|
| 10 |
+
"""Channel LayerNorm of NCHW tensors with an explicit backward (as in NAFNet)."""
|
| 11 |
+
|
| 12 |
+
@staticmethod
|
| 13 |
+
def forward(ctx, x, weight, bias, eps):
|
| 14 |
+
ctx.eps = eps
|
| 15 |
+
_, C, _, _ = x.size()
|
| 16 |
+
mu = x.mean(1, keepdim=True)
|
| 17 |
+
var = (x - mu).pow(2).mean(1, keepdim=True)
|
| 18 |
+
y = (x - mu) / (var + eps).sqrt()
|
| 19 |
+
ctx.save_for_backward(y, var, weight)
|
| 20 |
+
return weight.view(1, C, 1, 1) * y + bias.view(1, C, 1, 1)
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def backward(ctx, grad_output):
|
| 24 |
+
eps = ctx.eps
|
| 25 |
+
_, C, _, _ = grad_output.size()
|
| 26 |
+
y, var, weight = ctx.saved_tensors
|
| 27 |
+
g = grad_output * weight.view(1, C, 1, 1)
|
| 28 |
+
mean_g = g.mean(dim=1, keepdim=True)
|
| 29 |
+
mean_gy = (g * y).mean(dim=1, keepdim=True)
|
| 30 |
+
gx = 1.0 / torch.sqrt(var + eps) * (g - y * mean_gy - mean_g)
|
| 31 |
+
# reduce over W, H, then N, in this order (it fixes the floating-point summation order)
|
| 32 |
+
return gx, (grad_output * y).sum(dim=3).sum(dim=2).sum(dim=0), grad_output.sum(dim=3).sum(dim=2).sum(dim=0), None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class LayerNorm2d(nn.Module):
|
| 36 |
+
def __init__(self, channels, eps=1e-6):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.weight = nn.Parameter(torch.ones(channels))
|
| 39 |
+
self.bias = nn.Parameter(torch.zeros(channels))
|
| 40 |
+
self.eps = eps
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
return LayerNormFunction.apply(x, self.weight, self.bias, self.eps)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class InvertedConvolution(nn.Module):
|
| 47 |
+
"""1x1 convolution followed by a depthwise k x k convolution."""
|
| 48 |
+
|
| 49 |
+
def __init__(self, in_channels, out_channels, kernel_size):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.conv1 = nn.Conv2d(in_channels, out_channels, 1)
|
| 52 |
+
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size, padding="same", groups=out_channels)
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
return self.conv2(self.conv1(x))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ChannelAttention(nn.Module):
|
| 59 |
+
def __init__(self, channels):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.model = nn.Sequential(
|
| 62 |
+
nn.AdaptiveAvgPool2d(1),
|
| 63 |
+
nn.Conv2d(channels, channels // 2, 1),
|
| 64 |
+
nn.ReLU(inplace=True),
|
| 65 |
+
nn.Conv2d(channels // 2, channels, 1),
|
| 66 |
+
nn.Sigmoid(),
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def forward(self, x):
|
| 70 |
+
return self.model(x)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class NAFBlock(nn.Module):
|
| 74 |
+
"""NAFNet block (GELU, channel attention, inverted first convolution). With cond_channels > 0 the first convolution
|
| 75 |
+
also reads condition maps (the renderer's M_C, resized to the block's resolution)."""
|
| 76 |
+
|
| 77 |
+
def __init__(self, channels, cond_channels=0, ffn_expand=2.0, kernel_size=3):
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.norm1 = LayerNorm2d(channels)
|
| 80 |
+
self.conv1 = InvertedConvolution(channels + cond_channels, channels, kernel_size)
|
| 81 |
+
self.activation = nn.GELU()
|
| 82 |
+
self.attention = ChannelAttention(channels)
|
| 83 |
+
self.conv2 = nn.Conv2d(channels, channels, 1)
|
| 84 |
+
ffn_channels = floor(ffn_expand * channels)
|
| 85 |
+
self.norm2 = LayerNorm2d(channels)
|
| 86 |
+
self.conv3 = nn.Conv2d(channels, ffn_channels, 1)
|
| 87 |
+
self.conv4 = nn.Conv2d(ffn_channels, channels, 1)
|
| 88 |
+
self.beta = nn.Parameter(torch.zeros((1, channels, 1, 1)))
|
| 89 |
+
self.gamma = nn.Parameter(torch.zeros((1, channels, 1, 1)))
|
| 90 |
+
|
| 91 |
+
def forward(self, x, cond=None):
|
| 92 |
+
y = self.norm1(x) if cond is None else torch.cat((self.norm1(x), cond), dim=1)
|
| 93 |
+
y = self.activation(self.conv1(y))
|
| 94 |
+
y = x + self.conv2(y * self.attention(y)) * self.beta
|
| 95 |
+
return y + self.conv4(self.activation(self.conv3(self.norm2(y)))) * self.gamma
|
flashrefocus/overlays.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Burnt-in overlays (titles, captions, logos) in refocused video.
|
| 2 |
+
|
| 3 |
+
The renderer would blur a title together with the scene, and as the focus changes from frame to frame the blurred
|
| 4 |
+
letters glow and flicker. Fill the overlay from its surroundings before depth and rendering (fill_region), and paste
|
| 5 |
+
the sharp overlay back from the input afterwards (paste_back)."""
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def fill_region(image, mask, passes=4, kernel=15):
|
| 11 |
+
"""image (b, 3, h, w) in [0, 1]; mask (b or 1, 1, h, w) bool or float (1 = overlay). The masked pixels are replaced
|
| 12 |
+
by a normalized convolution of the unmasked ones at half resolution (the overlay disappears into its background)."""
|
| 13 |
+
m = mask.to(image.dtype)
|
| 14 |
+
m = (F.max_pool2d(m, 7, 1, 3) > 0.02).to(image.dtype) # a little wider than the overlay's anti-aliasing
|
| 15 |
+
keep = 1 - m
|
| 16 |
+
xs, ks = F.avg_pool2d(image * keep, 2), F.avg_pool2d(keep, 2)
|
| 17 |
+
for _ in range(passes):
|
| 18 |
+
xs = F.avg_pool2d(xs, kernel, 1, kernel // 2, count_include_pad=False)
|
| 19 |
+
ks = F.avg_pool2d(ks, kernel, 1, kernel // 2, count_include_pad=False)
|
| 20 |
+
fill = F.interpolate(xs / ks.clamp_min(1e-4), size=image.shape[-2:], mode="bilinear", align_corners=False)
|
| 21 |
+
return image * keep + fill * (1 - keep)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def paste_back(rendered, original, mask, feather=3):
|
| 25 |
+
"""Put the overlay pixels of `original` back onto `rendered` (both (b, 3, h, w)), with a soft edge."""
|
| 26 |
+
a = mask.to(rendered.dtype)
|
| 27 |
+
if feather > 0:
|
| 28 |
+
a = F.avg_pool2d(a, 2 * feather + 1, 1, feather, count_include_pad=False)
|
| 29 |
+
return rendered * (1 - a) + original * a
|
flashrefocus/paths.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Locations of weights, datasets and outputs. Defaults are folders inside the repository; set an environment variable
|
| 2 |
+
to point elsewhere:
|
| 3 |
+
|
| 4 |
+
FLASHREFOCUS_WEIGHTS weights/ stable-diffusion-2-1-base/, stable-diffusion-v1-5/ (VAE only),
|
| 5 |
+
stage1.pkl, refiner.pt, renderer.pt (FlashReFocus weights),
|
| 6 |
+
depth_anything_v2_vitl.pth, ram_plus_swin_large_14m.pth (Stage I training only)
|
| 7 |
+
FLASHREFOCUS_DATA data/ DPDD (dd_dp_dataset_png/), RealDOF/, div2k/, 3CReal/, RealBokeh/, LFDOF/
|
| 8 |
+
FLASHREFOCUS_WORK work/ evaluation outputs and intermediate files
|
| 9 |
+
FLASHREFOCUS_BASELINES baselines/ code of compared methods (GenRefocus, Depth Pro, ...), for the evaluation scripts
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
REPO = Path(__file__).resolve().parents[1]
|
| 16 |
+
WEIGHTS = Path(os.environ.get("FLASHREFOCUS_WEIGHTS", REPO / "weights"))
|
| 17 |
+
DATA = Path(os.environ.get("FLASHREFOCUS_DATA", REPO / "data"))
|
| 18 |
+
WORK = Path(os.environ.get("FLASHREFOCUS_WORK", REPO / "work"))
|
| 19 |
+
BASELINES = Path(os.environ.get("FLASHREFOCUS_BASELINES", REPO / "baselines"))
|
| 20 |
+
|
| 21 |
+
SD21 = WEIGHTS / "stable-diffusion-2-1-base"
|
| 22 |
+
SD15 = WEIGHTS / "stable-diffusion-v1-5"
|
| 23 |
+
STAGE1 = WEIGHTS / "stage1.pkl"
|
| 24 |
+
REFINER = WEIGHTS / "refiner.pt"
|
| 25 |
+
RENDERER = WEIGHTS / "renderer.pt"
|
| 26 |
+
DEPTH_ANYTHING_V2 = WEIGHTS / "depth_anything_v2_vitl.pth"
|
| 27 |
+
RAM_PLUS = WEIGHTS / "ram_plus_swin_large_14m.pth"
|
| 28 |
+
|
| 29 |
+
PISA_SR = REPO / "third_party" / "PiSA-SR"
|
| 30 |
+
DEPTH_ANYTHING_V2_CODE = REPO / "third_party" / "Depth-Anything-V2"
|
| 31 |
+
RAM_PLUS_CODE = REPO / "third_party" / "recognize-anything"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def use_third_party(*roots):
|
| 35 |
+
"""Make third-party code importable (git submodules under third_party/). recognize-anything must precede
|
| 36 |
+
PiSA-SR, whose older `ram` package would otherwise shadow RAM++."""
|
| 37 |
+
for root in roots:
|
| 38 |
+
if str(root) not in sys.path:
|
| 39 |
+
sys.path.insert(0, str(root))
|
flashrefocus/pipeline.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Interactive refocusing: deblur and estimate depth once per image, then render any number of focal edits.
|
| 2 |
+
|
| 3 |
+
refocuser = Refocuser.from_pretrained()
|
| 4 |
+
scene = refocuser.prepare(read_image("photo.png", "cuda")) # Stage I + depth, once per image
|
| 5 |
+
bokeh = refocuser.render(scene, strength=0.5, focal_depth=scene.focal_depth_at(x, y)) # Stage II, per edit
|
| 6 |
+
|
| 7 |
+
A Scene holds everything an edit needs, so a video can be processed as one Scene per frame, with the focal depth
|
| 8 |
+
D_f and the strength K chosen per frame (for example smoothed over time) and frames rendered in batches.
|
| 9 |
+
Images are 1 x 3 x H x W in [0, 1] on the GPU; sides should be multiples of 16."""
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from . import paths
|
| 15 |
+
from .image_io import read_image, save_image, to_signed, to_unit_range
|
| 16 |
+
from .rendering.depth import DepthEstimator
|
| 17 |
+
from .rendering.depth_edits import depth_at
|
| 18 |
+
from .rendering.renderer import load_renderer
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def quantize_to_8_bits(image):
|
| 22 |
+
"""As saving to an 8-bit PNG and reading it back. The divisor is a tensor: CUDA divides by a Python scalar via its
|
| 23 |
+
reciprocal, which differs in the last bit from image_io.image_to_tensor (division on the CPU)."""
|
| 24 |
+
return (image.clamp(0, 1) * 255.0).to(torch.uint8).float() / torch.tensor(255.0, device=image.device)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class Scene:
|
| 29 |
+
"""The restored all-in-focus image I_AiF (1, 3, H, W) in [0, 1] and its depth D (1, H, W), 1 = far."""
|
| 30 |
+
image: torch.Tensor
|
| 31 |
+
depth: torch.Tensor
|
| 32 |
+
|
| 33 |
+
def focal_depth_at(self, x, y):
|
| 34 |
+
"""D_f of the focal point (x, y) in pixels."""
|
| 35 |
+
return float(depth_at(self.depth, x, y))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Refocuser:
|
| 39 |
+
def __init__(self, deblurrer, depth_estimator, renderer, render_dtype=torch.bfloat16, channels_last=False):
|
| 40 |
+
self.deblurrer, self.depth_estimator, self.renderer = deblurrer, depth_estimator, renderer
|
| 41 |
+
self.render_dtype, self.channels_last = render_dtype, channels_last
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def from_pretrained(cls, detail_weight=1.25, refiner=paths.REFINER, refiner_dtype=torch.bfloat16,
|
| 45 |
+
render_dtype=torch.bfloat16, channels_last=False, merge_vae_lora=False, deblurring=True,
|
| 46 |
+
device="cuda", fused=False, compile=False):
|
| 47 |
+
"""The released models. Reported results use the defaults; the cost benchmark (Table 6) also uses
|
| 48 |
+
refiner_dtype=float16 and channels_last=True. render_dtype=None renders in fp32. deblurring=False loads only
|
| 49 |
+
the depth estimator and the renderer, for images that are already all-in-focus. fused=True runs the renderer's
|
| 50 |
+
defocus-bias attention as one Triton kernel (flashrefocus/rendering/fused.py): same weights and, up to
|
| 51 |
+
floating-point rounding, the same output, several times less memory and faster at high resolution. It is off by
|
| 52 |
+
default so that the reported numbers are reproduced exactly; deployment (ComfyUI, the demo) turns it on.
|
| 53 |
+
compile ("static" or "dynamic") compiles Stage I's full-resolution parts (Deblurrer.compile): about 35-40%
|
| 54 |
+
faster restoration after a one-time compilation of one to two minutes; off by default for the same reason."""
|
| 55 |
+
if deblurring: # Stage I (and its pinned diffusers / transformers) only when restoring
|
| 56 |
+
from .deblurring.deblurrer import Deblurrer
|
| 57 |
+
deblurrer = Deblurrer.from_pretrained(refiner=refiner, detail_weight=detail_weight, refiner_dtype=refiner_dtype,
|
| 58 |
+
merge_vae_lora=merge_vae_lora, compile=compile) if deblurring else None
|
| 59 |
+
refocuser = cls(deblurrer, DepthEstimator.from_pretrained(device=device), load_renderer(paths.RENDERER, device),
|
| 60 |
+
render_dtype, channels_last)
|
| 61 |
+
if fused:
|
| 62 |
+
from .rendering.fused import enable_fused
|
| 63 |
+
enable_fused(refocuser.renderer)
|
| 64 |
+
if channels_last:
|
| 65 |
+
modules = [refocuser.renderer]
|
| 66 |
+
if deblurrer is not None:
|
| 67 |
+
modules += [deblurrer.model.vae, deblurrer.model.unet] + ([deblurrer.refiner] if deblurrer.refiner is not None else [])
|
| 68 |
+
for module in modules:
|
| 69 |
+
module.to(memory_format=torch.channels_last)
|
| 70 |
+
return refocuser
|
| 71 |
+
|
| 72 |
+
def scene_from_file(self, path, deblur=False):
|
| 73 |
+
"""Scene of an image file (by default already all-in-focus)."""
|
| 74 |
+
return self.prepare(read_image(path, self.renderer.mean.device), deblur=deblur)
|
| 75 |
+
|
| 76 |
+
def render_to_file(self, scene, strength, focal_depth, path, depth=None):
|
| 77 |
+
bokeh = self.render(scene, strength, focal_depth, depth)
|
| 78 |
+
save_image(bokeh, path)
|
| 79 |
+
return bokeh
|
| 80 |
+
|
| 81 |
+
def _memory_format(self, x):
|
| 82 |
+
return x.contiguous(memory_format=torch.channels_last) if self.channels_last else x
|
| 83 |
+
|
| 84 |
+
@torch.no_grad()
|
| 85 |
+
def deblur(self, image):
|
| 86 |
+
"""Stage I: blurred image -> all-in-focus image, both in [0, 1] (the output is not clamped)."""
|
| 87 |
+
return to_unit_range(self.deblurrer(self._memory_format(to_signed(image))))
|
| 88 |
+
|
| 89 |
+
@torch.no_grad()
|
| 90 |
+
def prepare(self, image, deblur=True):
|
| 91 |
+
"""Scene of an image: Stage I (skipped for an image that is already all-in-focus) and its depth. The restored
|
| 92 |
+
image is quantised to 8 bits, as when it is saved and reloaded."""
|
| 93 |
+
aif = quantize_to_8_bits(self.deblur(image)) if deblur else image
|
| 94 |
+
return Scene(aif, self.depth_estimator(aif))
|
| 95 |
+
|
| 96 |
+
@torch.no_grad()
|
| 97 |
+
def render(self, scene, strength, focal_depth, depth=None):
|
| 98 |
+
"""Stage II: bokeh (b, 3, H, W) in [0, 1] with blur strength K and focal depth D_f. `depth` replaces the
|
| 99 |
+
scene depth, for depth edits (two focal planes, tilt-shift)."""
|
| 100 |
+
depth = scene.depth if depth is None else depth
|
| 101 |
+
image = self._memory_format(scene.image)
|
| 102 |
+
device = image.device
|
| 103 |
+
with torch.autocast(device.type, dtype=self.render_dtype or torch.float32, enabled=self.render_dtype is not None):
|
| 104 |
+
return self.renderer(image, torch.tensor([[float(strength)]], device=device), depth[None],
|
| 105 |
+
torch.tensor([[float(focal_depth)]], device=device)).float()
|
| 106 |
+
|
| 107 |
+
@torch.no_grad()
|
| 108 |
+
def render_batch(self, images, depths, strengths, focal_depths):
|
| 109 |
+
"""Stage II for several frames in one pass (video): images (b, 3, H, W), depths (b, H, W), one strength and one
|
| 110 |
+
focal depth per frame (sequences or scalars). The same result as rendering the frames one by one, up to
|
| 111 |
+
rounding; at video resolutions one frame already fills a large GPU, so this is a convenience, not a speed-up."""
|
| 112 |
+
b = images.shape[0]
|
| 113 |
+
device = images.device
|
| 114 |
+
|
| 115 |
+
def per_frame(v):
|
| 116 |
+
t = torch.as_tensor(v, dtype=torch.float32, device=device).flatten()
|
| 117 |
+
return (t.expand(b) if t.numel() == 1 else t).view(b, 1)
|
| 118 |
+
|
| 119 |
+
with torch.autocast(device.type, dtype=self.render_dtype or torch.float32, enabled=self.render_dtype is not None):
|
| 120 |
+
return self.renderer(self._memory_format(images), per_frame(strengths), depths.view(b, 1, *depths.shape[-2:]),
|
| 121 |
+
per_frame(focal_depths)).float()
|
flashrefocus/rendering/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage II: defocus-aware bokeh rendering (Sec. 3.2)."""
|
| 2 |
+
from .depth import DepthEstimator
|
| 3 |
+
from .renderer import Renderer, load_renderer
|
| 4 |
+
|
| 5 |
+
__all__ = ["DepthEstimator", "Renderer", "load_renderer"]
|
flashrefocus/rendering/defocus_bias_attention.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bottleneck of the renderer (Sec. 3.2, Appendix C.1): defocus-bias attention, defocus-aware attention blocks (DAABs)
|
| 2 |
+
and defocus residual groups (DRGs). Tokens are channels-last (b, h, w, c)."""
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from timm.layers import DropPath
|
| 6 |
+
from torch import nn
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DWConv2d(nn.Module):
|
| 10 |
+
"""Depthwise convolution on channels-last (b, h, w, c) tensors."""
|
| 11 |
+
|
| 12 |
+
def __init__(self, dim, kernel_size, padding):
|
| 13 |
+
super().__init__()
|
| 14 |
+
self.conv = nn.Conv2d(dim, dim, kernel_size, 1, padding, groups=dim)
|
| 15 |
+
|
| 16 |
+
def forward(self, x):
|
| 17 |
+
return self.conv(x.permute(0, 3, 1, 2)).permute(0, 2, 3, 1)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class FeedForwardNetwork(nn.Module):
|
| 21 |
+
def __init__(self, embed_dim, ffn_dim):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.fc1 = nn.Linear(embed_dim, ffn_dim)
|
| 24 |
+
self.fc2 = nn.Linear(ffn_dim, embed_dim)
|
| 25 |
+
|
| 26 |
+
def forward(self, x):
|
| 27 |
+
return self.fc2(F.gelu(self.fc1(x)))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DefocusBiasAttention(nn.Module):
|
| 31 |
+
"""Defocus-bias attention (Sec. 3.2, Appendix C.1), axial: along each row, then along each column.
|
| 32 |
+
|
| 33 |
+
A_ij = softmax_j(q_i^T k_j / sqrt(d) + gamma_b * alpha * B_ij), B_ij = -|T_D,i - T_D,j|, T_D = phi_D(M),
|
| 34 |
+
where phi_D maps the defocus magnitude M to fixed log features at several scales and then, with a learned linear
|
| 35 |
+
layer (defocus_head_proj), to one value per head; alpha (defocus_alpha) is learned per head and
|
| 36 |
+
gamma_b = exp(clip(w_b K + c_b, -4, 4)) (aperture_scale_proj); gamma_K = gamma_b * alpha in the main paper.
|
| 37 |
+
The output is W_o(sum_j A_ij v_j + LePE(V)_i), with LePE a depthwise 5x5 convolution of the values."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, embed_dim, num_heads):
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.num_heads = num_heads
|
| 42 |
+
self.key_dim = embed_dim // num_heads # d
|
| 43 |
+
self.scaling = self.key_dim ** -0.5
|
| 44 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim) # W_q
|
| 45 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim) # W_k
|
| 46 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim) # W_v
|
| 47 |
+
self.lepe = DWConv2d(embed_dim, 5, 2)
|
| 48 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim) # W_o
|
| 49 |
+
self.num_log_features = max(embed_dim // 4, 1)
|
| 50 |
+
self.defocus_head_proj = nn.Linear(self.num_log_features, num_heads) # linear layer of phi_D
|
| 51 |
+
self.defocus_alpha = nn.Parameter(torch.ones(num_heads)) # alpha
|
| 52 |
+
self.aperture_scale_proj = nn.Linear(1, num_heads) # w_b, c_b
|
| 53 |
+
|
| 54 |
+
def _log_features(self, defocus):
|
| 55 |
+
"""M (b, 1, h, w) -> (b, h, w, n) features log(1 + M / s) / log(1 + 1 / s), scales s from 1/n to 1."""
|
| 56 |
+
n = self.num_log_features
|
| 57 |
+
min_scale = 1.0 / max(float(n), 16.0)
|
| 58 |
+
scales = torch.logspace(torch.log10(defocus.new_tensor(min_scale)), torch.log10(defocus.new_tensor(1.0)),
|
| 59 |
+
steps=n, dtype=defocus.dtype, device=defocus.device).view(1, n, 1, 1)
|
| 60 |
+
features = torch.log1p(defocus.clamp(0.0, 1.0) / scales) / torch.log1p(1.0 / scales)
|
| 61 |
+
return features.permute(0, 2, 3, 1).contiguous()
|
| 62 |
+
|
| 63 |
+
def _defocus_bias(self, defocus):
|
| 64 |
+
"""B along rows (b, h, heads, w, w) and along columns (b, w, heads, h, h)."""
|
| 65 |
+
t_d = self.defocus_head_proj(self._log_features(defocus)) # T_D = phi_D(M): b, h, w, heads
|
| 66 |
+
t_rows = t_d.permute(0, 1, 3, 2).contiguous() # b, h, heads, w
|
| 67 |
+
t_cols = t_d.permute(0, 2, 3, 1).contiguous() # b, w, heads, h
|
| 68 |
+
return (-torch.abs(t_rows.unsqueeze(-1) - t_rows.unsqueeze(-2)),
|
| 69 |
+
-torch.abs(t_cols.unsqueeze(-1) - t_cols.unsqueeze(-2)))
|
| 70 |
+
|
| 71 |
+
def _gamma_b(self, x, strength):
|
| 72 |
+
raw = self.aperture_scale_proj(strength.to(device=x.device, dtype=x.dtype))
|
| 73 |
+
return torch.exp(torch.clamp(raw, min=-4.0, max=4.0)).view(x.size(0), 1, self.num_heads, 1, 1)
|
| 74 |
+
|
| 75 |
+
def forward(self, x, defocus, strength):
|
| 76 |
+
b, h, w, _ = x.size()
|
| 77 |
+
q = self.q_proj(x)
|
| 78 |
+
k = self.k_proj(x) * self.scaling
|
| 79 |
+
v = self.v_proj(x)
|
| 80 |
+
lepe = self.lepe(v)
|
| 81 |
+
q = q.view(b, h, w, self.num_heads, self.key_dim).permute(0, 3, 1, 2, 4) # b, heads, h, w, d
|
| 82 |
+
k = k.view(b, h, w, self.num_heads, self.key_dim).permute(0, 3, 1, 2, 4)
|
| 83 |
+
|
| 84 |
+
bias_rows, bias_cols = self._defocus_bias(defocus)
|
| 85 |
+
scale = self._gamma_b(x, strength) * self.defocus_alpha.view(1, 1, self.num_heads, 1, 1) # gamma_b * alpha
|
| 86 |
+
|
| 87 |
+
v = v.reshape(b, h, w, self.num_heads, -1).permute(0, 1, 3, 2, 4) # b, h, heads, w, d
|
| 88 |
+
attn = torch.softmax(q.transpose(1, 2) @ k.transpose(1, 2).transpose(-1, -2) + scale * bias_rows, dim=-1)
|
| 89 |
+
v = (attn @ v).permute(0, 3, 2, 1, 4) # b, w, heads, h, d
|
| 90 |
+
attn = torch.softmax(q.permute(0, 3, 1, 2, 4) @ k.permute(0, 3, 1, 2, 4).transpose(-1, -2)
|
| 91 |
+
+ scale * bias_cols, dim=-1)
|
| 92 |
+
out = (attn @ v).permute(0, 3, 1, 2, 4).flatten(-2, -1) # b, h, w, c
|
| 93 |
+
return self.out_proj(out + lepe)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class DefocusAwareAttentionBlock(nn.Module):
|
| 97 |
+
"""Defocus-aware attention block (DAAB, Fig. 3C): depthwise positional convolution, defocus-bias attention, FFN."""
|
| 98 |
+
|
| 99 |
+
def __init__(self, embed_dim, num_heads, ffn_dim, drop_path=0.0):
|
| 100 |
+
super().__init__()
|
| 101 |
+
self.pos = DWConv2d(embed_dim, 3, 1)
|
| 102 |
+
self.attention_layer_norm = nn.LayerNorm(embed_dim, eps=1e-6)
|
| 103 |
+
self.attention = DefocusBiasAttention(embed_dim, num_heads)
|
| 104 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=1e-6)
|
| 105 |
+
self.ffn = FeedForwardNetwork(embed_dim, ffn_dim)
|
| 106 |
+
self.drop_path = DropPath(drop_path)
|
| 107 |
+
|
| 108 |
+
def forward(self, x, defocus, strength):
|
| 109 |
+
x = x + self.pos(x)
|
| 110 |
+
x = x + self.drop_path(self.attention(self.attention_layer_norm(x), defocus, strength))
|
| 111 |
+
return x + self.drop_path(self.ffn(self.final_layer_norm(x)))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class DAABStack(nn.Module):
|
| 115 |
+
"""The N DAABs of a DRG; the defocus magnitude M is resized to the token grid once for all of them."""
|
| 116 |
+
|
| 117 |
+
def __init__(self, embed_dim, depth, num_heads, ffn_dim, drop_path):
|
| 118 |
+
super().__init__()
|
| 119 |
+
self.blocks = nn.ModuleList(
|
| 120 |
+
[DefocusAwareAttentionBlock(embed_dim, num_heads, ffn_dim, drop_path[i]) for i in range(depth)])
|
| 121 |
+
|
| 122 |
+
def forward(self, x, defocus, strength):
|
| 123 |
+
defocus = F.interpolate(defocus.to(x.dtype), size=x.shape[1:3], mode="bilinear", align_corners=False)
|
| 124 |
+
for daab in self.blocks:
|
| 125 |
+
x = daab(x, defocus, strength)
|
| 126 |
+
return x
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class DefocusResidualGroup(nn.Module):
|
| 130 |
+
"""Defocus residual group (DRG, Fig. 3B): N DAABs, then a 3x3 convolution over the features and M_C, with a
|
| 131 |
+
residual connection."""
|
| 132 |
+
|
| 133 |
+
def __init__(self, embed_dim, cond_channels, depth, num_heads, ffn_dim, drop_path):
|
| 134 |
+
super().__init__()
|
| 135 |
+
self.residual_group = DAABStack(embed_dim, depth, num_heads, ffn_dim, drop_path)
|
| 136 |
+
self.conv = nn.Conv2d(embed_dim + cond_channels, embed_dim, 3, 1, 1)
|
| 137 |
+
|
| 138 |
+
def forward(self, x, cond, defocus, strength):
|
| 139 |
+
y = self.residual_group(x, defocus, strength).permute(0, 3, 1, 2)
|
| 140 |
+
return self.conv(torch.cat((y, cond), dim=1)).permute(0, 2, 3, 1) + x
|
flashrefocus/rendering/depth.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Depth D for the renderer from Depth Anything V2 (DA-V2): D = 1 - minmax(DA-V2 output), in [0, 1], 1 = far.
|
| 2 |
+
|
| 3 |
+
The DA-V2 attention runs through scaled_dot_product_attention (same result up to floating-point reordering, 4.2x faster
|
| 4 |
+
at 1536x1536); pre- and post-processing run on the GPU."""
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
from .. import paths
|
| 10 |
+
|
| 11 |
+
DA2_CONFIGS = {
|
| 12 |
+
"vits": {"encoder": "vits", "features": 64, "out_channels": [48, 96, 192, 384]},
|
| 13 |
+
"vitb": {"encoder": "vitb", "features": 128, "out_channels": [96, 192, 384, 768]},
|
| 14 |
+
"vitl": {"encoder": "vitl", "features": 256, "out_channels": [256, 512, 1024, 1024]},
|
| 15 |
+
"vitg": {"encoder": "vitg", "features": 384, "out_channels": [1536, 1536, 1536, 1536]},
|
| 16 |
+
}
|
| 17 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 18 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _sdpa_attention_forward(self, x, attn_bias=None):
|
| 22 |
+
assert attn_bias is None
|
| 23 |
+
B, N, C = x.shape
|
| 24 |
+
q, k, v = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
| 25 |
+
x = F.scaled_dot_product_attention(q, k, v, scale=self.scale).transpose(1, 2).reshape(B, N, C)
|
| 26 |
+
return self.proj_drop(self.proj(x))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def use_sdpa_attention():
|
| 30 |
+
"""Route the DA-V2 (DINOv2) attention through torch's scaled_dot_product_attention."""
|
| 31 |
+
paths.use_third_party(paths.DEPTH_ANYTHING_V2_CODE)
|
| 32 |
+
from depth_anything_v2.dinov2_layers import attention
|
| 33 |
+
attention.Attention.forward = _sdpa_attention_forward
|
| 34 |
+
attention.MemEffAttention.forward = _sdpa_attention_forward
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_depth_anything_v2(encoder="vitl", checkpoint=paths.DEPTH_ANYTHING_V2, device="cuda"):
|
| 38 |
+
paths.use_third_party(paths.DEPTH_ANYTHING_V2_CODE)
|
| 39 |
+
from depth_anything_v2.dpt import DepthAnythingV2
|
| 40 |
+
model = DepthAnythingV2(**DA2_CONFIGS[encoder])
|
| 41 |
+
model.load_state_dict(torch.load(checkpoint, map_location="cpu"))
|
| 42 |
+
return model.to(device).eval()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def disparity_to_depth(disparity):
|
| 46 |
+
"""Relative inverse depth -> D = 1 - minmax(disparity), finite values only (zeros if the map is constant)."""
|
| 47 |
+
d = torch.nan_to_num(disparity, nan=0.0, posinf=0.0, neginf=0.0)
|
| 48 |
+
lo, hi = d.min(), d.max()
|
| 49 |
+
d = (d - lo) / (hi - lo) if float(hi - lo) > 1e-12 else torch.zeros_like(d)
|
| 50 |
+
return (1.0 - d).clamp(0, 1)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class DepthEstimator(nn.Module):
|
| 54 |
+
"""image (1, 3, H, W) in [0, 1] -> D (1, H, W). DA-V2 runs at `input_size` on the short side (a multiple of 14),
|
| 55 |
+
in fp16 autocast."""
|
| 56 |
+
|
| 57 |
+
def __init__(self, model, input_size=1024):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.model, self.input_size = model, input_size
|
| 60 |
+
self.register_buffer("mean", torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1), persistent=False)
|
| 61 |
+
self.register_buffer("std", torch.tensor(IMAGENET_STD).view(1, 3, 1, 1), persistent=False)
|
| 62 |
+
|
| 63 |
+
@classmethod
|
| 64 |
+
def from_pretrained(cls, encoder="vitl", checkpoint=paths.DEPTH_ANYTHING_V2, input_size=1024, device="cuda",
|
| 65 |
+
sdpa=True):
|
| 66 |
+
if sdpa:
|
| 67 |
+
use_sdpa_attention()
|
| 68 |
+
return cls(load_depth_anything_v2(encoder, checkpoint, device), input_size).to(device)
|
| 69 |
+
|
| 70 |
+
def _network_size(self, h, w):
|
| 71 |
+
from depth_anything_v2.util.transform import Resize
|
| 72 |
+
s = self.input_size
|
| 73 |
+
tw, th = Resize(width=s, height=s, resize_target=False, keep_aspect_ratio=True, ensure_multiple_of=14,
|
| 74 |
+
resize_method="lower_bound").get_size(w, h)
|
| 75 |
+
return th, tw
|
| 76 |
+
|
| 77 |
+
@torch.no_grad()
|
| 78 |
+
def forward(self, image):
|
| 79 |
+
h, w = image.shape[-2:]
|
| 80 |
+
x = F.interpolate(image, self._network_size(h, w), mode="bicubic", align_corners=False)
|
| 81 |
+
x = (x - self.mean.to(x)) / self.std.to(x)
|
| 82 |
+
with torch.autocast(image.device.type, dtype=torch.float16):
|
| 83 |
+
disparity = self.model(x)
|
| 84 |
+
disparity = F.interpolate(disparity[:, None].float(), (h, w), mode="bilinear", align_corners=True)[0]
|
| 85 |
+
return disparity_to_depth(disparity)
|
flashrefocus/rendering/depth_edits.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Depth edits (Sec. 4.3 and the appendix): the renderer reads an explicit depth map, so replacing it changes how the image
|
| 2 |
+
is focused without retraining. Every function returns a depth map (1, H, W) in [0, 1] to render with."""
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def depth_at(depth, x, y):
|
| 7 |
+
"""D at pixel (x, y), clamped to the image: the focal depth D_f of a focal point."""
|
| 8 |
+
_, h, w = depth.shape
|
| 9 |
+
return depth[0, max(0, min(h - 1, int(round(y)))), max(0, min(w - 1, int(round(x))))]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def two_focal_planes(depth, focal_depth_a, focal_depth_b):
|
| 13 |
+
"""D' = D_A + min(|D - D_A|, |D - D_B|): every pixel is blurred by its distance to the nearer of two focal planes.
|
| 14 |
+
Render D' with focal depth D_A. If adding the distance would clip more pixels at 1 than subtracting it would clip at
|
| 15 |
+
0 (a far plane A), it is subtracted instead: adding it to D_A = 1 would make the whole image sharp."""
|
| 16 |
+
da, db = float(focal_depth_a), float(focal_depth_b)
|
| 17 |
+
distance = torch.minimum((depth - da).abs(), (depth - db).abs())
|
| 18 |
+
subtract = int((da - distance < 0).sum()) < int((da + distance > 1).sum())
|
| 19 |
+
return (da - distance if subtract else da + distance).clamp(0, 1)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def tilt_shift(height, width, row, slope=3.0, band=0.06, device="cpu"):
|
| 23 |
+
"""A vertical ramp with a flat band of half-height `band` centred at `row` (fractions of the height): a horizontal
|
| 24 |
+
band stays sharp and blur grows above and below it. Render it with the focal point at (W / 2, row * H)."""
|
| 25 |
+
yy = torch.linspace(0, 1, height, device=device).view(height, 1).expand(height, width)
|
| 26 |
+
dy = (yy - row).abs().sub(band).clamp(min=0) * torch.sign(yy - row)
|
| 27 |
+
return (0.5 + slope * dy / 2).clamp(0, 1)[None]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _grid(height, width, device):
|
| 31 |
+
"""Row and column coordinates in [0, 1], each H x W."""
|
| 32 |
+
yy = torch.linspace(0, 1, height, device=device).view(height, 1).expand(height, width)
|
| 33 |
+
xx = torch.linspace(0, 1, width, device=device).view(1, width).expand(height, width)
|
| 34 |
+
return yy, xx
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _ramp(signed_distance, band, slope):
|
| 38 |
+
"""0.5 within `band` of zero, growing (or falling, for negative distances) linearly beyond it."""
|
| 39 |
+
d = signed_distance.abs().sub(band).clamp(min=0) * torch.sign(signed_distance)
|
| 40 |
+
return (0.5 + slope * d / 2).clamp(0, 1)[None]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def focus_range(depth, focal_depth, width):
|
| 44 |
+
"""A thick focal plane: D' = D_f + sign(D - D_f) max(|D - D_f| - width, 0). Every depth within `width` of D_f stays
|
| 45 |
+
sharp, and the rest keeps its distance minus `width`. Render with the same D_f."""
|
| 46 |
+
s = depth - float(focal_depth)
|
| 47 |
+
return (float(focal_depth) + torch.sign(s) * (s.abs() - width).clamp(min=0)).clamp(0, 1)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def radial_focus(height, width, center_x, center_y, radius=0.12, slope=2.2, device="cpu"):
|
| 51 |
+
"""Lensbaby-style focus: a sharp disc of `radius` (fraction of the height) around (center_x, center_y) (fractions of
|
| 52 |
+
the width and height), with blur growing outward. Render with focal depth 0.5."""
|
| 53 |
+
yy, xx = _grid(height, width, device)
|
| 54 |
+
dist = torch.sqrt(((xx - center_x) * width / height) ** 2 + (yy - center_y) ** 2)
|
| 55 |
+
return _ramp(dist, radius, slope)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def tilted_band(height, width, center_x=0.5, center_y=0.5, angle=0.0, band=0.06, slope=3.0, device="cpu"):
|
| 59 |
+
"""Tilt-shift at any angle: a sharp band of half-width `band` (fraction of the height) through (center_x, center_y),
|
| 60 |
+
rotated by `angle` degrees (0 = horizontal), with blur growing on both sides. Render with focal depth 0.5;
|
| 61 |
+
angle 0 gives the same map as tilt_shift."""
|
| 62 |
+
import math
|
| 63 |
+
yy, xx = _grid(height, width, device)
|
| 64 |
+
t = math.radians(angle)
|
| 65 |
+
signed = -(xx - center_x) * width / height * math.sin(t) + (yy - center_y) * math.cos(t)
|
| 66 |
+
return _ramp(signed, band, slope)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def one_sided(depth, focal_depth, keep="foreground"):
|
| 70 |
+
"""Blur only one side of the focal plane. keep="foreground" clamps everything nearer than D_f onto the focal plane
|
| 71 |
+
(only the background blurs); keep="background" clamps everything farther (only the foreground blurs)."""
|
| 72 |
+
df = torch.tensor(float(focal_depth), device=depth.device)
|
| 73 |
+
return torch.maximum(depth, df) if keep == "foreground" else torch.minimum(depth, df)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def focal_planes(depth, focal_depths):
|
| 77 |
+
"""Several focal planes: every pixel is blurred by its distance to the nearest of `focal_depths`. Render with the
|
| 78 |
+
first focal depth. Generalises two_focal_planes (same rule for choosing the side of the first plane)."""
|
| 79 |
+
d0 = float(focal_depths[0])
|
| 80 |
+
distance = torch.stack([(depth - float(d)).abs() for d in focal_depths]).min(0).values
|
| 81 |
+
subtract = int((d0 - distance < 0).sum()) < int((d0 + distance > 1).sum())
|
| 82 |
+
return (d0 - distance if subtract else d0 + distance).clamp(0, 1)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def keep_sharp(depth, mask, focal_depth):
|
| 86 |
+
"""Place the masked pixels (mask: H x W or 1 x H x W, bool) on the focal plane, so they stay sharp."""
|
| 87 |
+
return torch.where(mask.view_as(depth), torch.full_like(depth, float(focal_depth)), depth)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def set_mask_depth(depth, mask, value):
|
| 91 |
+
"""Move the masked pixels to depth `value` (0 = near, 1 = far): for example 1.0 pushes a photobomber into the far
|
| 92 |
+
background, so he melts into the bokeh while the subject stays sharp. No inpainting is involved."""
|
| 93 |
+
return torch.where(mask.view_as(depth), torch.full_like(depth, float(value)), depth)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def move_away(depth, mask, focal_depth, distance):
|
| 97 |
+
"""Move the masked pixels at least `distance` away from the focal plane, on their own side (or the side with more
|
| 98 |
+
room): optical privacy blur for faces, or extra blur for one layer."""
|
| 99 |
+
df = float(focal_depth)
|
| 100 |
+
s = depth - df
|
| 101 |
+
side = torch.where(s.abs() > 1e-3, torch.sign(s), torch.full_like(s, 1.0 if df < 0.5 else -1.0))
|
| 102 |
+
moved = (df + side * torch.maximum(s.abs(), torch.full_like(s, distance))).clamp(0, 1)
|
| 103 |
+
return torch.where(mask.view_as(depth), moved, depth)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def isolate(depth, mask, focal_depth, gap):
|
| 107 |
+
"""Keep the masked pixels on the focal plane and move every other pixel at least `gap` away from it, so everything
|
| 108 |
+
around the subject blurs strongly."""
|
| 109 |
+
return keep_sharp(move_away(depth, ~mask.view_as(depth), focal_depth, gap), mask, focal_depth)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def grow_mask(mask, depth, focal_depth, others=None, radius=10, tolerance=0.05):
|
| 113 |
+
"""Add to a subject mask the pixels next to it (within `radius` pixels) that sit near the focal depth and belong to
|
| 114 |
+
no other person (`others`, optional bool mask): segmentation often misses fingers, hair and motion-blurred hands,
|
| 115 |
+
which would otherwise be pushed out of focus. Only grown pixels connected to the mask are kept; holes are filled."""
|
| 116 |
+
import numpy as np
|
| 117 |
+
from scipy import ndimage
|
| 118 |
+
m = mask.view(depth.shape[-2:]).cpu().numpy().astype(bool)
|
| 119 |
+
if not m.any():
|
| 120 |
+
return mask
|
| 121 |
+
d = depth.view(depth.shape[-2:]).float().cpu().numpy()
|
| 122 |
+
ring = ndimage.binary_dilation(m, iterations=int(radius)) & ~m
|
| 123 |
+
if others is not None:
|
| 124 |
+
ring &= ~others.view(depth.shape[-2:]).cpu().numpy().astype(bool)
|
| 125 |
+
grown = m | (ring & (np.abs(d - float(focal_depth)) < tolerance))
|
| 126 |
+
lab, _ = ndimage.label(grown)
|
| 127 |
+
keep = np.unique(lab[m])
|
| 128 |
+
grown = ndimage.binary_fill_holes(np.isin(lab, keep[keep > 0]))
|
| 129 |
+
return torch.from_numpy(grown).to(mask.device).view_as(mask)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def spotlight(depth, mask, focal_depth, gap=0.6, others=None, grow=10):
|
| 133 |
+
"""Spotlight on a subject (for example the lead singer in a concert video): the subject mask, grown by `grow`
|
| 134 |
+
pixels into its missed hands and hair (grow_mask), goes on the focal plane and every other pixel moves at least
|
| 135 |
+
`gap` away from it, so the people around the subject blur strongly. Returns the edited depth and the grown mask."""
|
| 136 |
+
if grow > 0:
|
| 137 |
+
mask = grow_mask(mask, depth, focal_depth, others, radius=grow)
|
| 138 |
+
return isolate(depth, mask, focal_depth, gap), mask
|
flashrefocus/rendering/fused.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fused inference path for the renderer (deployment only; the released weights and outputs are unchanged).
|
| 2 |
+
|
| 3 |
+
The defocus-bias attention (defocus_bias_attention.py) builds, for every row and then every column of the bottleneck
|
| 4 |
+
token grid, the bias B_ij = -|T_D,i - T_D,j| and the full attention matrix in memory: O(L^2) per row or column, which
|
| 5 |
+
dominates both time and peak memory at high resolution. Here one Triton kernel does both axial passes as a
|
| 6 |
+
FlashAttention-style loop with an online softmax, and computes gamma_b * alpha * B_ij on the fly from the per-token
|
| 7 |
+
values T_D, so neither the bias nor the attention matrix is ever stored. It reads q, k, v and T_D in their original
|
| 8 |
+
channels-last layout through strides (no transposed copies) and writes the row pass in the layout the column pass reads.
|
| 9 |
+
|
| 10 |
+
from flashrefocus.rendering.fused import enable_fused
|
| 11 |
+
enable_fused(renderer) # every DefocusBiasAttention of the renderer uses the fused kernel on CUDA
|
| 12 |
+
|
| 13 |
+
Without Triton or on CPU the reference implementation is used.
|
| 14 |
+
"""
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
import triton
|
| 19 |
+
import triton.language as tl
|
| 20 |
+
HAVE_TRITON = True
|
| 21 |
+
except ImportError: # pragma: no cover
|
| 22 |
+
HAVE_TRITON = False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if HAVE_TRITON:
|
| 26 |
+
@triton.autotune(
|
| 27 |
+
configs=[triton.Config({"BLOCK_M": bm, "BLOCK_N": bn}, num_warps=nw, num_stages=ns)
|
| 28 |
+
for bm, bn, nw, ns in [(128, 32, 4, 3), (128, 64, 4, 2), (128, 32, 2, 3), (64, 64, 4, 2),
|
| 29 |
+
(32, 64, 2, 3), (64, 128, 4, 2)]],
|
| 30 |
+
key=["L", "D"])
|
| 31 |
+
@triton.jit
|
| 32 |
+
def _axial_bias_attention_kernel(
|
| 33 |
+
Q, K, V, T, S, O,
|
| 34 |
+
sq_b, sq_i, sq_l, sq_h, # q strides: batch, inner (the other axis), sequence, head
|
| 35 |
+
sk_b, sk_i, sk_l, sk_h,
|
| 36 |
+
sv_b, sv_i, sv_l, sv_h,
|
| 37 |
+
so_b, so_i, so_l, so_h,
|
| 38 |
+
st_b, st_i, st_l, st_h, # T_D strides (no channel dimension)
|
| 39 |
+
inner, heads, L,
|
| 40 |
+
D: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 41 |
+
pid_m = tl.program_id(0)
|
| 42 |
+
z = tl.program_id(1)
|
| 43 |
+
hd = z % heads
|
| 44 |
+
zi = (z // heads) % inner
|
| 45 |
+
zb = z // (heads * inner)
|
| 46 |
+
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 47 |
+
offs_n = tl.arange(0, BLOCK_N)
|
| 48 |
+
offs_d = tl.arange(0, D)
|
| 49 |
+
q_base = Q + zb * sq_b + zi * sq_i + hd * sq_h
|
| 50 |
+
k_base = K + zb * sk_b + zi * sk_i + hd * sk_h
|
| 51 |
+
v_base = V + zb * sv_b + zi * sv_i + hd * sv_h
|
| 52 |
+
t_base = T + zb * st_b + zi * st_i + hd * st_h
|
| 53 |
+
mask_m = offs_m < L
|
| 54 |
+
q = tl.load(q_base + offs_m[:, None] * sq_l + offs_d[None, :], mask=mask_m[:, None], other=0.0)
|
| 55 |
+
t_q = tl.load(t_base + offs_m * st_l, mask=mask_m, other=0.0).to(tl.float32)
|
| 56 |
+
s = tl.load(S + zb * heads + hd).to(tl.float32) # gamma_b * alpha of this image and head
|
| 57 |
+
m_i = tl.full([BLOCK_M], float("-inf"), tl.float32)
|
| 58 |
+
l_i = tl.zeros([BLOCK_M], tl.float32)
|
| 59 |
+
acc = tl.zeros([BLOCK_M, D], tl.float32)
|
| 60 |
+
for start_n in range(0, L, BLOCK_N):
|
| 61 |
+
cols = start_n + offs_n
|
| 62 |
+
mask_n = cols < L
|
| 63 |
+
k = tl.load(k_base + cols[:, None] * sk_l + offs_d[None, :], mask=mask_n[:, None], other=0.0)
|
| 64 |
+
t_k = tl.load(t_base + cols * st_l, mask=mask_n, other=0.0).to(tl.float32)
|
| 65 |
+
qk = tl.dot(q, tl.trans(k)) # fp32 accumulate
|
| 66 |
+
qk = qk - s * tl.abs(t_q[:, None] - t_k[None, :])
|
| 67 |
+
qk = tl.where(mask_n[None, :], qk, float("-inf"))
|
| 68 |
+
m_new = tl.maximum(m_i, tl.max(qk, 1))
|
| 69 |
+
p = tl.exp(qk - m_new[:, None])
|
| 70 |
+
alpha = tl.exp(m_i - m_new)
|
| 71 |
+
l_i = l_i * alpha + tl.sum(p, 1)
|
| 72 |
+
v = tl.load(v_base + cols[:, None] * sv_l + offs_d[None, :], mask=mask_n[:, None], other=0.0)
|
| 73 |
+
acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v)
|
| 74 |
+
m_i = m_new
|
| 75 |
+
acc = acc / l_i[:, None]
|
| 76 |
+
o_base = O + zb * so_b + zi * so_i + hd * so_h
|
| 77 |
+
tl.store(o_base + offs_m[:, None] * so_l + offs_d[None, :], acc.to(O.dtype.element_ty), mask=mask_m[:, None])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _axial_pass(q, k, v, t, scale, axis):
|
| 81 |
+
"""One axial pass. q, k, v: (b, h, w, heads, d) views; t: (b, h, w, heads); scale: (b, heads).
|
| 82 |
+
axis = 2 attends along w (each row), axis = 1 along h (each column). Returns (b, h, w, heads, d) contiguous."""
|
| 83 |
+
b, h, w, heads, d = q.shape
|
| 84 |
+
out = torch.empty((b, h, w, heads, d), device=q.device, dtype=q.dtype)
|
| 85 |
+
other = 1 if axis == 2 else 2
|
| 86 |
+
inner, L = q.shape[other], q.shape[axis]
|
| 87 |
+
|
| 88 |
+
def st5(x):
|
| 89 |
+
return x.stride(0), x.stride(other), x.stride(axis), x.stride(3)
|
| 90 |
+
|
| 91 |
+
st_t = (t.stride(0), t.stride(other), t.stride(axis), t.stride(3))
|
| 92 |
+
for x in (q, k, v, out):
|
| 93 |
+
assert x.stride(4) == 1
|
| 94 |
+
grid = lambda meta: (triton.cdiv(L, meta["BLOCK_M"]), b * inner * heads) # noqa: E731
|
| 95 |
+
_axial_bias_attention_kernel[grid](q, k, v, t, scale, out, *st5(q), *st5(k), *st5(v), *st5(out), *st_t,
|
| 96 |
+
inner, heads, L, D=d)
|
| 97 |
+
return out
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def fused_attention_forward(self, x, defocus, strength):
|
| 101 |
+
"""Drop-in forward of DefocusBiasAttention using the fused kernel (same parameters, same output)."""
|
| 102 |
+
if not (HAVE_TRITON and x.is_cuda) or self.training or self.key_dim not in (16, 32, 64, 128):
|
| 103 |
+
return type(self).forward(self, x, defocus, strength)
|
| 104 |
+
b, h, w, c = x.shape
|
| 105 |
+
q = self.q_proj(x)
|
| 106 |
+
k = self.k_proj(x) * self.scaling
|
| 107 |
+
v = self.v_proj(x)
|
| 108 |
+
lepe = self.lepe(v)
|
| 109 |
+
dt = q.dtype
|
| 110 |
+
q5 = q.view(b, h, w, self.num_heads, self.key_dim)
|
| 111 |
+
k5 = k.to(dt).view(b, h, w, self.num_heads, self.key_dim)
|
| 112 |
+
v5 = v.view(b, h, w, self.num_heads, self.key_dim)
|
| 113 |
+
t_d = self.defocus_head_proj(self._log_features(defocus)).float().contiguous() # T_D: b, h, w, heads
|
| 114 |
+
scale = (self._gamma_b(x, strength).view(b, self.num_heads).float()
|
| 115 |
+
* self.defocus_alpha.float().view(1, self.num_heads)).contiguous() # gamma_b * alpha: b, heads
|
| 116 |
+
rows = _axial_pass(q5, k5, v5, t_d, scale, axis=2)
|
| 117 |
+
out = _axial_pass(q5, k5, rows, t_d, scale, axis=1)
|
| 118 |
+
return self.out_proj(out.view(b, h, w, c) + lepe)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def enable_fused(renderer):
|
| 122 |
+
"""Switch every DefocusBiasAttention in `renderer` to the fused kernel. Returns the renderer."""
|
| 123 |
+
from .defocus_bias_attention import DefocusBiasAttention
|
| 124 |
+
for m in renderer.modules():
|
| 125 |
+
if isinstance(m, DefocusBiasAttention):
|
| 126 |
+
m.forward = fused_attention_forward.__get__(m)
|
| 127 |
+
return renderer
|
flashrefocus/rendering/renderer.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage II renderer R_psi (Sec. 3.2, Fig. 3): a NAF U-Net whose bottleneck stacks defocus residual groups (DRGs).
|
| 2 |
+
|
| 3 |
+
Inputs, with the notation of the paper: the all-in-focus image I_AiF, the blur strength K in [0, 1], the depth
|
| 4 |
+
D in [0, 1] (1 = far; inverted, min-max normalized Depth Anything V2 output) and the focal depth D_f = D(p_f).
|
| 5 |
+
The condition maps M_C (Eq. 6) are the signed defocus M^s = D - D_f (Eq. 5), the mask M^fg = 1[M^s <= 0] of the focal
|
| 6 |
+
plane and what lies before it (dilated by a 5x5 max filter) and the constant map K; every NAF block and every DRG
|
| 7 |
+
reads M_C at its resolution, and the defocus-bias attention reads the magnitude M = |M^s|. The output is
|
| 8 |
+
I_bokeh = I_AiF + Delta I."""
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torch.nn.init import trunc_normal_
|
| 13 |
+
|
| 14 |
+
from ..layers import NAFBlock
|
| 15 |
+
from .defocus_bias_attention import DefocusResidualGroup
|
| 16 |
+
|
| 17 |
+
COND_CHANNELS = 3 # M_C = [M^s, M^fg, K]
|
| 18 |
+
RGB_MEAN = (0.4488, 0.4371, 0.4040)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def constant_map(like, strength):
|
| 22 |
+
"""K as a constant (b, 1, h, w) map of the size of `like`."""
|
| 23 |
+
return strength.to(device=like.device, dtype=like.dtype).view(like.size(0), 1, 1, 1).expand(-1, -1, *like.shape[-2:])
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def resize_bilinear(x, size):
|
| 27 |
+
return F.interpolate(x, size=size, mode="bilinear", align_corners=False)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def condition_maps(depth, focal_depth, strength, size):
|
| 31 |
+
"""M^s = D - D_f and M_C = [M^s, M^fg, K] at `size` (the size of depth)."""
|
| 32 |
+
signed_defocus = depth - focal_depth.to(depth).view(-1, 1, 1, 1) # M^s
|
| 33 |
+
front_mask = F.max_pool2d((signed_defocus < 1e-3).to(signed_defocus.dtype), 5, stride=1, padding=2) # M^fg
|
| 34 |
+
cond = torch.cat((resize_bilinear(signed_defocus, size), front_mask, constant_map(signed_defocus, strength)), dim=1)
|
| 35 |
+
return signed_defocus, cond
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Renderer(nn.Module):
|
| 39 |
+
def __init__(self, u_width=16, u_depth=2, embed_dim=96, num_groups=3, group_depth=3, num_heads=3, mlp_ratio=2,
|
| 40 |
+
drop_path_rate=0.1, noise_level=0.05):
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.u_depth = u_depth
|
| 43 |
+
self.noise_level = noise_level # training only: Gaussian noise on the bottleneck input and output
|
| 44 |
+
self.register_buffer("mean", torch.tensor(RGB_MEAN).view(1, 3, 1, 1), persistent=False)
|
| 45 |
+
|
| 46 |
+
# input: I_AiF, M_C and the K map once more
|
| 47 |
+
self.in_stage = nn.Conv2d(3 + COND_CHANNELS + 1, u_width, 3, 1, 1)
|
| 48 |
+
self.in_stage_2 = nn.Conv2d(u_width, u_width, 3, 1, 1)
|
| 49 |
+
self.encoders, self.downs = nn.ModuleList(), nn.ModuleList()
|
| 50 |
+
chan = u_width
|
| 51 |
+
for _ in range(u_depth):
|
| 52 |
+
self.encoders.append(nn.ModuleList([NAFBlock(chan, COND_CHANNELS)]))
|
| 53 |
+
self.downs.append(nn.Conv2d(chan, chan * 2, 2, 2))
|
| 54 |
+
chan *= 2
|
| 55 |
+
|
| 56 |
+
# bottleneck: DRGs on channels-last tokens (parameter names follow the released checkpoint)
|
| 57 |
+
self.conv_prep = nn.Conv2d(chan, embed_dim, 3, 1, 1)
|
| 58 |
+
self.defocus_fuse = nn.Conv2d(embed_dim + COND_CHANNELS, embed_dim, 3, 1, 1)
|
| 59 |
+
self.patch_embed = nn.Module()
|
| 60 |
+
self.patch_embed.norm = nn.LayerNorm(embed_dim)
|
| 61 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_groups * group_depth)]
|
| 62 |
+
self.blocks = nn.ModuleList([ # the DRGs
|
| 63 |
+
DefocusResidualGroup(embed_dim, COND_CHANNELS, group_depth, num_heads, mlp_ratio * embed_dim,
|
| 64 |
+
dpr[i * group_depth:(i + 1) * group_depth]) for i in range(num_groups)])
|
| 65 |
+
self.norm = nn.LayerNorm(embed_dim, eps=1e-6)
|
| 66 |
+
self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
|
| 67 |
+
self.conv_last = nn.Conv2d(embed_dim + COND_CHANNELS, chan, 3, 1, 1)
|
| 68 |
+
|
| 69 |
+
self.ups, self.decoders = nn.ModuleList(), nn.ModuleList()
|
| 70 |
+
for level in range(u_depth):
|
| 71 |
+
self.ups.append(nn.Sequential(nn.Conv2d(chan, 2 * chan, 1, bias=False), nn.PixelShuffle(2)))
|
| 72 |
+
chan //= 2
|
| 73 |
+
n = 4 if level == u_depth - 1 else 2
|
| 74 |
+
self.decoders.append(nn.ModuleList([NAFBlock(chan, COND_CHANNELS) for _ in range(n)]))
|
| 75 |
+
self.out_stage = nn.Conv2d(u_width + COND_CHANNELS, 3, 3, 1, 1)
|
| 76 |
+
self.apply(self._init_weights)
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def _init_weights(m):
|
| 80 |
+
if isinstance(m, nn.Linear):
|
| 81 |
+
trunc_normal_(m.weight, std=0.02)
|
| 82 |
+
if m.bias is not None:
|
| 83 |
+
nn.init.constant_(m.bias, 0)
|
| 84 |
+
elif isinstance(m, nn.LayerNorm):
|
| 85 |
+
nn.init.constant_(m.bias, 0)
|
| 86 |
+
nn.init.constant_(m.weight, 1.0)
|
| 87 |
+
|
| 88 |
+
def _add_training_noise(self, x):
|
| 89 |
+
return x + torch.randn_like(x) * self.noise_level if self.training and self.noise_level > 0 else x
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def _pad_to_multiple(x, multiple):
|
| 93 |
+
h, w = x.shape[-2:]
|
| 94 |
+
ph, pw = (multiple - h % multiple) % multiple, (multiple - w % multiple) % multiple
|
| 95 |
+
if ph == 0 and pw == 0:
|
| 96 |
+
return x
|
| 97 |
+
return F.pad(x, (0, pw, 0, ph), "reflect" if ph < h and pw < w else "replicate")
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
def _cond_at_level(cond, level):
|
| 101 |
+
"""M_C at U-Net level `level` (resolution 1 / 2^level)."""
|
| 102 |
+
return F.interpolate(cond, scale_factor=1 / 2 ** level, mode="bilinear", align_corners=False)
|
| 103 |
+
|
| 104 |
+
def forward(self, image, strength, depth, focal_depth):
|
| 105 |
+
"""image I_AiF (b, 3, h, w) in [0, 1]; strength K (b, 1); depth D (b, 1, h, w); focal_depth D_f (b, 1).
|
| 106 |
+
Returns I_bokeh (b, 3, h, w)."""
|
| 107 |
+
h, w = image.shape[-2:]
|
| 108 |
+
strength = strength.view(-1, 1)
|
| 109 |
+
multiple = 2 ** self.u_depth
|
| 110 |
+
image, depth = self._pad_to_multiple(image, multiple), self._pad_to_multiple(depth.to(image), multiple)
|
| 111 |
+
x = image - self.mean
|
| 112 |
+
signed_defocus, cond = condition_maps(depth, focal_depth.to(image), strength, x.shape[-2:])
|
| 113 |
+
|
| 114 |
+
x = self.in_stage_2(self.in_stage(torch.cat((x, cond, constant_map(x, strength)), dim=1)))
|
| 115 |
+
skips = []
|
| 116 |
+
for level, (encoder, down) in enumerate(zip(self.encoders, self.downs)):
|
| 117 |
+
for block in encoder:
|
| 118 |
+
x = block(x, self._cond_at_level(cond, level))
|
| 119 |
+
skips.append(x)
|
| 120 |
+
x = down(x)
|
| 121 |
+
|
| 122 |
+
feat = self.conv_prep(self._add_training_noise(x))
|
| 123 |
+
defocus = resize_bilinear(signed_defocus.abs().to(feat.dtype), feat.shape[-2:]).clamp(0.0, 1.0) # M
|
| 124 |
+
cond_bottleneck = self._cond_at_level(cond, self.u_depth)
|
| 125 |
+
feat = self.defocus_fuse(torch.cat((feat, cond_bottleneck), dim=1))
|
| 126 |
+
tokens = self.patch_embed.norm(feat.permute(0, 2, 3, 1)) # b, h, w, c
|
| 127 |
+
for drg in self.blocks:
|
| 128 |
+
tokens = drg(tokens, cond_bottleneck, defocus, strength)
|
| 129 |
+
feat = self.conv_after_body(self.norm(tokens).permute(0, 3, 1, 2)) + feat
|
| 130 |
+
x = self._add_training_noise(x + self.conv_last(torch.cat((feat, cond_bottleneck), dim=1)))
|
| 131 |
+
|
| 132 |
+
for i, (decoder, up, skip) in enumerate(zip(self.decoders, self.ups, skips[::-1])):
|
| 133 |
+
x = up(x) + skip
|
| 134 |
+
for block in decoder:
|
| 135 |
+
x = block(x, self._cond_at_level(cond, self.u_depth - 1 - i))
|
| 136 |
+
residual = self.out_stage(torch.cat((x, cond), dim=1)) + self.mean # Delta I
|
| 137 |
+
return (residual + image)[:, :, :h, :w]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def load_renderer_state(model, path):
|
| 141 |
+
"""Load a training checkpoint ({"model": state_dict}) or a bare state_dict strictly. Older checkpoints also store
|
| 142 |
+
the table of a relative-position bias ("Relpos") that the defocus-bias attention does not use."""
|
| 143 |
+
state = torch.load(path, map_location="cpu")
|
| 144 |
+
state = state.get("model", state)
|
| 145 |
+
state = {k.removeprefix("module."): v for k, v in state.items() if ".Relpos." not in k}
|
| 146 |
+
model.load_state_dict(state, strict=True)
|
| 147 |
+
return model
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_renderer(path, device="cuda"):
|
| 151 |
+
return load_renderer_state(Renderer(), path).to(device).eval()
|
flashrefocus/segment.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Subject masks for video with SAM 3 (text-prompted video segmentation and tracking).
|
| 2 |
+
|
| 3 |
+
SAM 3 segments and tracks every instance of a text prompt (for example "person") through a clip; one track is chosen
|
| 4 |
+
as the subject and the union of the others is returned too (for depth_edits.spotlight, which must not grow the
|
| 5 |
+
subject mask into a neighbour). Long clips are processed in chunks; the subject is carried from one chunk to the next
|
| 6 |
+
by the overlap of its last mask with the tracks of the next chunk.
|
| 7 |
+
|
| 8 |
+
Needs transformers >= 4.57 (Sam3VideoModel) and access to the gated checkpoint facebook/sam3 on Hugging Face. Stage I
|
| 9 |
+
pins an older transformers; the spotlight path (restoration off) does not use Stage I, so it can run in an
|
| 10 |
+
environment with a recent transformers.
|
| 11 |
+
|
| 12 |
+
from flashrefocus.segment import track_subject
|
| 13 |
+
subject, others = track_subject(frames, prompt="person", select="most_central") # frames: (n, h, w, 3) uint8
|
| 14 |
+
"""
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
_SAM3 = {}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _load(device, dtype):
|
| 22 |
+
try:
|
| 23 |
+
from transformers import Sam3VideoModel, Sam3VideoProcessor
|
| 24 |
+
except ImportError as e: # pragma: no cover
|
| 25 |
+
raise ImportError("SAM 3 needs transformers >= 4.57 (pip install -U transformers) and access to "
|
| 26 |
+
"facebook/sam3 on Hugging Face.") from e
|
| 27 |
+
key = (str(device), dtype)
|
| 28 |
+
if key not in _SAM3:
|
| 29 |
+
_SAM3.clear()
|
| 30 |
+
_SAM3[key] = (Sam3VideoModel.from_pretrained("facebook/sam3").to(device, dtype=dtype).eval(),
|
| 31 |
+
Sam3VideoProcessor.from_pretrained("facebook/sam3"))
|
| 32 |
+
return _SAM3[key]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _tracks(frames, prompt, device, dtype):
|
| 36 |
+
"""All tracks of `prompt` in a chunk: list over frames of {track id: bool mask (h, w)}."""
|
| 37 |
+
model, proc = _load(device, dtype)
|
| 38 |
+
sess = proc.init_video_session(video=list(frames), inference_device=device, processing_device="cpu",
|
| 39 |
+
video_storage_device="cpu", dtype=dtype)
|
| 40 |
+
sess = proc.add_text_prompt(inference_session=sess, text=prompt)
|
| 41 |
+
out = [dict() for _ in frames]
|
| 42 |
+
with torch.no_grad():
|
| 43 |
+
for o in model.propagate_in_video_iterator(inference_session=sess):
|
| 44 |
+
p = proc.postprocess_outputs(sess, o)
|
| 45 |
+
ids = p["object_ids"]
|
| 46 |
+
ids = ids.tolist() if torch.is_tensor(ids) else list(ids)
|
| 47 |
+
if not ids:
|
| 48 |
+
continue
|
| 49 |
+
masks = p["masks"].cpu().numpy()
|
| 50 |
+
masks = masks > 0.5 if masks.dtype != bool else masks
|
| 51 |
+
out[o.frame_idx] = {int(i): m for i, m in zip(ids, masks)}
|
| 52 |
+
return out
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _choose(tracks, select, point, previous):
|
| 56 |
+
ids = sorted({i for f in tracks for i in f})
|
| 57 |
+
if not ids:
|
| 58 |
+
return None
|
| 59 |
+
if previous is not None: # continue the subject of the previous chunk
|
| 60 |
+
first = next((f for f in tracks if f), {})
|
| 61 |
+
iou = {i: (m & previous).sum() / max(1, (m | previous).sum()) for i, m in first.items()}
|
| 62 |
+
if iou and max(iou.values()) > 0.1:
|
| 63 |
+
return max(iou, key=iou.get)
|
| 64 |
+
if select == "point":
|
| 65 |
+
h, w = next(iter(next(f for f in tracks if f).values())).shape
|
| 66 |
+
x, y = int(point[0] * (w - 1)), int(point[1] * (h - 1))
|
| 67 |
+
for f in tracks:
|
| 68 |
+
hit = [i for i, m in f.items() if m[y, x]]
|
| 69 |
+
if hit:
|
| 70 |
+
return hit[0]
|
| 71 |
+
select = "most_central"
|
| 72 |
+
score = dict.fromkeys(ids, 0.0)
|
| 73 |
+
for f in tracks:
|
| 74 |
+
for i, m in f.items():
|
| 75 |
+
area = float(m.mean())
|
| 76 |
+
if select == "largest":
|
| 77 |
+
score[i] += area
|
| 78 |
+
else: # most_central: area weighted by closeness to the centre
|
| 79 |
+
cols = np.nonzero(m.any(0))[0]
|
| 80 |
+
cx = cols.mean() / m.shape[1] if len(cols) else 0.5
|
| 81 |
+
score[i] += area * (1 - 2 * abs(cx - 0.5))
|
| 82 |
+
return max(score, key=score.get)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def track_subject(frames, prompt="person", select="most_central", point=(0.5, 0.5), chunk=300, device="cuda",
|
| 86 |
+
dtype=torch.bfloat16):
|
| 87 |
+
"""frames: (n, h, w, 3) uint8 array or tensor. select: "most_central", "largest" or "point" (the track under
|
| 88 |
+
`point`, fractions of width and height, on the first frame where a track covers it). Returns two bool tensors
|
| 89 |
+
(n, h, w): the subject mask and the union of the other tracks (all False where the subject is not found)."""
|
| 90 |
+
frames = frames.cpu().numpy() if torch.is_tensor(frames) else np.asarray(frames)
|
| 91 |
+
n, h, w = frames.shape[:3]
|
| 92 |
+
subject, others = np.zeros((n, h, w), bool), np.zeros((n, h, w), bool)
|
| 93 |
+
previous = None
|
| 94 |
+
for s in range(0, n, chunk):
|
| 95 |
+
tracks = _tracks(frames[s:s + chunk], prompt, device, dtype)
|
| 96 |
+
sid = _choose(tracks, select, point, previous)
|
| 97 |
+
for k, f in enumerate(tracks):
|
| 98 |
+
for i, m in f.items():
|
| 99 |
+
if i == sid:
|
| 100 |
+
subject[s + k] = m
|
| 101 |
+
else:
|
| 102 |
+
others[s + k] |= m
|
| 103 |
+
previous = subject[s + len(tracks) - 1] if sid is not None and subject[s + len(tracks) - 1].any() else None
|
| 104 |
+
return torch.from_numpy(subject), torch.from_numpy(others)
|
flashrefocus/video.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Writing refocused video without per-frame image files.
|
| 2 |
+
|
| 3 |
+
Frames are quantised on the GPU, copied to the CPU and streamed to one ffmpeg process that encodes the whole clip; the
|
| 4 |
+
pipe is fed from a background thread, so encoding overlaps rendering. The encoder is chosen automatically from what
|
| 5 |
+
this ffmpeg build has: NVENC (h264_nvenc, on the GPU) if a GPU accepts it, else libx264, libopenh264 or mpeg4.
|
| 6 |
+
|
| 7 |
+
from flashrefocus.video import VideoWriter
|
| 8 |
+
with VideoWriter("out.mp4", fps=30) as writer:
|
| 9 |
+
for frame in frames: # (1, 3, H, W) or (b, 3, H, W) float in [0, 1], any device
|
| 10 |
+
writer.write(refocuser.render(...))
|
| 11 |
+
|
| 12 |
+
ffmpeg: $FLASHREFOCUS_FFMPEG, else imageio-ffmpeg's binary if installed, else `ffmpeg` on the PATH.
|
| 13 |
+
"""
|
| 14 |
+
import os
|
| 15 |
+
import queue
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
import threading
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
_WORKS = {}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def ffmpeg_exe():
|
| 26 |
+
exe = os.environ.get("FLASHREFOCUS_FFMPEG")
|
| 27 |
+
if exe:
|
| 28 |
+
return exe
|
| 29 |
+
try:
|
| 30 |
+
import imageio_ffmpeg
|
| 31 |
+
return imageio_ffmpeg.get_ffmpeg_exe()
|
| 32 |
+
except ImportError:
|
| 33 |
+
pass
|
| 34 |
+
exe = shutil.which("ffmpeg")
|
| 35 |
+
if exe is None:
|
| 36 |
+
raise FileNotFoundError("ffmpeg not found: install it, pip install imageio-ffmpeg, or set FLASHREFOCUS_FFMPEG")
|
| 37 |
+
return exe
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def encoder_works(codec, exe=None):
|
| 41 |
+
"""True if this ffmpeg can actually encode with `codec` here (a short test encode, cached): a build may list an
|
| 42 |
+
encoder whose library or GPU is missing."""
|
| 43 |
+
exe = exe or ffmpeg_exe()
|
| 44 |
+
key = (exe, codec)
|
| 45 |
+
if key not in _WORKS:
|
| 46 |
+
r = subprocess.run([exe, "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=size=256x256:rate=30",
|
| 47 |
+
"-t", "0.2", "-c:v", codec, "-pix_fmt", "yuv420p", "-f", "null", "-"], capture_output=True)
|
| 48 |
+
_WORKS[key] = r.returncode == 0
|
| 49 |
+
return _WORKS[key]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def available_encoders(exe=None):
|
| 53 |
+
"""Video encoder names of this ffmpeg build."""
|
| 54 |
+
exe = exe or ffmpeg_exe()
|
| 55 |
+
out = subprocess.run([exe, "-hide_banner", "-encoders"], capture_output=True, text=True).stdout
|
| 56 |
+
return {line.split()[1] for line in out.splitlines() if line.startswith(" V")}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def pick_encoder(exe=None):
|
| 60 |
+
exe = exe or ffmpeg_exe()
|
| 61 |
+
names = available_encoders(exe)
|
| 62 |
+
for name in ("h264_nvenc", "libx264", "libopenh264", "mpeg4"):
|
| 63 |
+
if name in names and encoder_works(name, exe):
|
| 64 |
+
return name
|
| 65 |
+
raise RuntimeError(f"no working H.264 or MPEG-4 encoder in {exe}")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def to_uint8_frames(x):
|
| 69 |
+
"""(b, 3, H, W) or (3, H, W) float in [0, 1] -> (b, H, W, 3) uint8 numpy, quantised on the tensor's device."""
|
| 70 |
+
x = x[None] if x.dim() == 3 else x
|
| 71 |
+
return (x.float().clamp(0, 1) * 255.0).to(torch.uint8).permute(0, 2, 3, 1).contiguous().cpu().numpy()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class VideoWriter:
|
| 75 |
+
"""Streams frames to one ffmpeg encode. codec: "auto" (see pick_encoder) or an ffmpeg encoder name; quality: CRF
|
| 76 |
+
for libx264, CQ for NVENC (lower is better). audio_from: a video file whose audio track is copied in."""
|
| 77 |
+
|
| 78 |
+
def __init__(self, path, fps=30.0, codec="auto", quality=18, preset=None, audio_from=None, queue_frames=8):
|
| 79 |
+
self.path, self.fps, self.quality, self.audio_from = str(path), fps, quality, audio_from
|
| 80 |
+
self.exe = ffmpeg_exe()
|
| 81 |
+
self.codec = pick_encoder(self.exe) if codec == "auto" else codec
|
| 82 |
+
self.preset = preset or {"h264_nvenc": "p5", "libx264": "veryfast"}.get(self.codec)
|
| 83 |
+
self.proc, self.size = None, None
|
| 84 |
+
self.q = queue.Queue(maxsize=queue_frames)
|
| 85 |
+
self.error = None
|
| 86 |
+
self.thread = threading.Thread(target=self._pump, daemon=True)
|
| 87 |
+
|
| 88 |
+
def _start(self, w, h):
|
| 89 |
+
rate = f"{self.fps}"
|
| 90 |
+
cmd = [self.exe, "-hide_banner", "-loglevel", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24",
|
| 91 |
+
"-s", f"{w}x{h}", "-r", rate, "-i", "-"]
|
| 92 |
+
if self.audio_from:
|
| 93 |
+
cmd += ["-i", str(self.audio_from), "-map", "0:v", "-map", "1:a?", "-c:a", "copy", "-shortest"]
|
| 94 |
+
q = {"h264_nvenc": ["-cq", str(self.quality)], "libx264": ["-crf", str(self.quality)],
|
| 95 |
+
"libopenh264": ["-b:v", "20M"], "mpeg4": ["-q:v", "2"]}.get(self.codec, [])
|
| 96 |
+
preset = ["-preset", self.preset] if self.preset else []
|
| 97 |
+
cmd += ["-c:v", self.codec, *preset, *q, "-pix_fmt", "yuv420p", "-movflags", "+faststart", self.path]
|
| 98 |
+
self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
|
| 99 |
+
self.size = (w, h)
|
| 100 |
+
self.thread.start()
|
| 101 |
+
|
| 102 |
+
def _pump(self):
|
| 103 |
+
try:
|
| 104 |
+
while True:
|
| 105 |
+
arr = self.q.get()
|
| 106 |
+
if arr is None:
|
| 107 |
+
break
|
| 108 |
+
self.proc.stdin.write(arr.tobytes())
|
| 109 |
+
except Exception as e: # pragma: no cover
|
| 110 |
+
self.error = e
|
| 111 |
+
|
| 112 |
+
def write(self, frames):
|
| 113 |
+
"""Append frames: a tensor (b, 3, H, W) / (3, H, W) in [0, 1], or uint8 arrays (b, H, W, 3) / (H, W, 3)."""
|
| 114 |
+
if self.error:
|
| 115 |
+
raise self.error
|
| 116 |
+
arr = to_uint8_frames(frames) if torch.is_tensor(frames) else frames
|
| 117 |
+
arr = arr[None] if arr.ndim == 3 else arr
|
| 118 |
+
if self.proc is None:
|
| 119 |
+
self._start(arr.shape[2], arr.shape[1])
|
| 120 |
+
assert (arr.shape[2], arr.shape[1]) == self.size, "every frame must have the size of the first"
|
| 121 |
+
for a in arr:
|
| 122 |
+
self.q.put(a)
|
| 123 |
+
|
| 124 |
+
def close(self):
|
| 125 |
+
if self.proc is None:
|
| 126 |
+
return
|
| 127 |
+
self.q.put(None)
|
| 128 |
+
self.thread.join()
|
| 129 |
+
self.proc.stdin.close()
|
| 130 |
+
if self.proc.wait() != 0:
|
| 131 |
+
raise RuntimeError(f"ffmpeg failed writing {self.path}")
|
| 132 |
+
if self.error:
|
| 133 |
+
raise self.error
|
| 134 |
+
|
| 135 |
+
def __enter__(self):
|
| 136 |
+
return self
|
| 137 |
+
|
| 138 |
+
def __exit__(self, *exc):
|
| 139 |
+
self.close()
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.8.0
|
| 2 |
+
torchvision==0.23.0
|
| 3 |
+
transformers==5.20.2
|
| 4 |
+
accelerate==1.15.0
|
| 5 |
+
timm==1.0.30
|
| 6 |
+
einops==0.8.2
|
| 7 |
+
opencv-python-headless==5.0.0.93
|
| 8 |
+
safetensors==0.8.0
|
| 9 |
+
numpy==2.2.6
|
| 10 |
+
scipy
|
| 11 |
+
imageio-ffmpeg
|
third_party/Depth-Anything-V2/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
third_party/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 |
+
)
|
third_party/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
|
third_party/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 |
+
|
third_party/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
|
third_party/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)
|
third_party/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
|
third_party/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
|
third_party/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
|
third_party/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 |
+
)
|
third_party/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)
|
third_party/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
|
third_party/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
|