Spaces:
Running

ming0531 commited on
Commit
35bbb5b
·
verified ·
1 Parent(s): 7b6dbcc

FlashReFocus on a free CPU (sharp photographs, no restoration)

Browse files
Files changed (44) hide show
  1. .gitattributes +3 -0
  2. .gitignore +3 -0
  3. README.md +20 -6
  4. app.py +291 -0
  5. engine.py +62 -0
  6. examples/dock.jpg +3 -0
  7. examples/flower.jpg +3 -0
  8. examples/portrait_aquarium.jpg +0 -0
  9. examples/portrait_city.jpg +0 -0
  10. examples/sculpture.jpg +3 -0
  11. flashrefocus/README.md +180 -0
  12. flashrefocus/__init__.py +6 -0
  13. flashrefocus/_compat.py +9 -0
  14. flashrefocus/deblurring/__init__.py +4 -0
  15. flashrefocus/deblurring/deblurrer.py +102 -0
  16. flashrefocus/deblurring/decoder_refiner.py +112 -0
  17. flashrefocus/deblurring/one_step_diffusion.py +136 -0
  18. flashrefocus/image_io.py +72 -0
  19. flashrefocus/layers.py +95 -0
  20. flashrefocus/overlays.py +29 -0
  21. flashrefocus/paths.py +39 -0
  22. flashrefocus/pipeline.py +134 -0
  23. flashrefocus/rendering/__init__.py +5 -0
  24. flashrefocus/rendering/defocus_bias_attention.py +140 -0
  25. flashrefocus/rendering/depth.py +85 -0
  26. flashrefocus/rendering/depth_edits.py +138 -0
  27. flashrefocus/rendering/fused.py +156 -0
  28. flashrefocus/rendering/renderer.py +151 -0
  29. flashrefocus/segment.py +104 -0
  30. flashrefocus/video.py +139 -0
  31. requirements.txt +8 -0
  32. third_party/Depth-Anything-V2/LICENSE +201 -0
  33. third_party/Depth-Anything-V2/depth_anything_v2/dinov2.py +415 -0
  34. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/__init__.py +11 -0
  35. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/attention.py +83 -0
  36. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/block.py +252 -0
  37. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/drop_path.py +35 -0
  38. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/layer_scale.py +28 -0
  39. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/mlp.py +41 -0
  40. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/patch_embed.py +89 -0
  41. third_party/Depth-Anything-V2/depth_anything_v2/dinov2_layers/swiglu_ffn.py +63 -0
  42. third_party/Depth-Anything-V2/depth_anything_v2/dpt.py +221 -0
  43. third_party/Depth-Anything-V2/depth_anything_v2/util/blocks.py +148 -0
  44. third_party/Depth-Anything-V2/depth_anything_v2/util/transform.py +158 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/dock.jpg filter=lfs diff=lfs merge=lfs -text
37
+ examples/flower.jpg filter=lfs diff=lfs merge=lfs -text
38
+ examples/sculpture.jpg filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ weights/
2
+ __pycache__/
3
+ *.pyc
README.md CHANGED
@@ -1,13 +1,27 @@
1
  ---
2
- title: FlashReFocus CPU
3
- emoji: 🏆
4
- colorFrom: gray
5
  colorTo: gray
6
  sdk: gradio
7
- sdk_version: 6.32.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: FlashReFocus (CPU)
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: Refocus sharp photos on a free CPU
12
  ---
13
 
14
+ # FlashReFocus on the CPU
15
+
16
+ Refocus a photograph that is already sharp: Depth Anything V2 estimates its depth once, then each click runs only the
17
+ 1.3M-parameter FlashReFocus renderer, here on a free CPU (a few seconds per click). One or two focal planes, tilt-shift,
18
+ the depth curve and your own depth map are supported.
19
+
20
+ Restoring blurred photographs (Stage I, one-step diffusion) needs a GPU: use the GPU demo
21
+ [ming0531/FlashReFocus](https://huggingface.co/spaces/ming0531/FlashReFocus). Video spotlight:
22
+ [ming0531/FlashReFocus-Video](https://huggingface.co/spaces/ming0531/FlashReFocus-Video).
23
+
24
+ [Project page](https://ming053l.github.io/FlashReFocus/) · [Code](https://github.com/ming053l/FlashReFocus)
25
+
26
+ Third-party code: Depth Anything V2 (depth), see `third_party/*/LICENSE`. Example portraits are from
27
+ [Unsplash](https://unsplash.com) under the Unsplash License.
app.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FlashReFocus on the CPU (free Hugging Face CPU Space): interactive refocusing of photographs that are already sharp.
2
+
3
+ 1. Estimate depth: Depth Anything V2 estimates the depth of the uploaded photograph once (no restoration on the CPU).
4
+ 2. Click the image (or the depth map) to focus; only the 1.3M-parameter renderer runs per edit.
5
+ Modes: one focal plane; two focal planes (first click A, second click B); tilt-shift (a click sets the sharp row).
6
+ 3. The aperture (blur strength K), the depth curve and an optional user depth map re-render the current edit.
7
+ """
8
+ import time
9
+
10
+ import gradio as gr
11
+ import numpy as np
12
+ from PIL import Image, ImageDraw, ImageFont
13
+
14
+ import engine
15
+
16
+ SINGLE, DUAL, TILT = "📍 One focal plane", "👥 Two focal planes", "🏙️ Tilt-shift"
17
+ EXAMPLES = ["examples/portrait_city.jpg", "examples/portrait_aquarium.jpg", "examples/flower.jpg",
18
+ "examples/dock.jpg", "examples/sculpture.jpg"]
19
+ FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
20
+ try:
21
+ ImageFont.truetype(FONT, 12)
22
+ except OSError:
23
+ FONT = None
24
+
25
+
26
+ def fit(img, long_side):
27
+ """Long side at most `long_side`, both sides multiples of 16."""
28
+ w, h = img.size
29
+ s = min(1.0, long_side / max(w, h))
30
+ w2, h2 = max(16, int(w * s) // 16 * 16), max(16, int(h * s) // 16 * 16)
31
+ return img.convert("RGB").resize((w2, h2), Image.LANCZOS)
32
+
33
+
34
+ def cpu_depth(rgb, omega):
35
+ t0 = time.perf_counter()
36
+ aif, depth = engine.restore(rgb, omega)
37
+ return aif, depth, time.perf_counter() - t0
38
+
39
+
40
+ def cpu_render(aif, depth, focal_depth, strength):
41
+ t0 = time.perf_counter()
42
+ out = engine.render(aif, depth, focal_depth, strength)
43
+ return out, time.perf_counter() - t0
44
+
45
+
46
+ def depth_image(depth):
47
+ return Image.fromarray((np.clip(1 - depth, 0, 1) * 255).astype(np.uint8)) # near is bright
48
+
49
+
50
+ def scene_depth(state, gamma):
51
+ """The depth the edits start from: the estimate (or the user's map), with the depth curve D^gamma applied."""
52
+ d = state["user_depth"] if state.get("user_depth") is not None else state["depth"]
53
+ return np.power(np.clip(d, 0, 1), float(gamma)).astype(np.float32)
54
+
55
+
56
+ def depth_at(depth, point):
57
+ h, w = depth.shape
58
+ return float(depth[min(max(point[1], 0), h - 1), min(max(point[0], 0), w - 1)])
59
+
60
+
61
+ def edit(state, mode, gamma, band):
62
+ """(depth to render, focal depth D_f) for the current mode, or None when a focal point is still missing."""
63
+ d = scene_depth(state, gamma)
64
+ h, w = d.shape
65
+ if mode == TILT:
66
+ return engine.tilt_shift(h, w, state.get("tilt_row", 0.5), float(band)), 0.5
67
+ pts = state["pts"]
68
+ if not pts:
69
+ return None
70
+ if mode == DUAL and len(pts) == 2:
71
+ da, db = depth_at(d, pts[0]), depth_at(d, pts[1])
72
+ return engine.two_focal_planes(d, da, db), da
73
+ return d, depth_at(d, pts[0])
74
+
75
+
76
+ def restore(img, long_side, omega, gamma):
77
+ if img is None:
78
+ return None, None, None, None, "Upload an image or pick an example first."
79
+ rgb = np.asarray(fit(img, int(long_side)))
80
+ aif, depth, t = cpu_depth(rgb, float(omega))
81
+ state = {"aif": aif, "depth": depth, "user_depth": None, "pts": [], "tilt_row": 0.5}
82
+ msg = (f"Estimated the depth of the {aif.shape[1]}×{aif.shape[0]} image in {t:.1f} s on the CPU. "
83
+ "**Click the image or the depth map to focus.**")
84
+ return Image.fromarray(aif), depth_image(scene_depth(state, gamma)), None, state, msg
85
+
86
+
87
+ def render(state, strength, mode, gamma, band, show_marker):
88
+ """(refocused image, depth view, message)."""
89
+ edited = edit(state, mode, gamma, band)
90
+ if edited is None:
91
+ return None, depth_image(scene_depth(state, gamma)), "Click the image or the depth map to focus."
92
+ depth, focal_depth = edited
93
+ out, dt = cpu_render(state["aif"], depth, focal_depth, float(strength))
94
+ out = Image.fromarray(out)
95
+ if show_marker:
96
+ out = draw_markers(out, state, mode)
97
+ k = f"aperture K = {float(strength):.2f}" + (" (extrapolated)" if float(strength) > 1 else "")
98
+ if mode == TILT:
99
+ msg = f"Tilt-shift band at {state.get('tilt_row', 0.5):.0%} of the height, {k}: rendered in {dt:.2f} s."
100
+ elif mode == DUAL and len(state["pts"]) == 2:
101
+ msg = f"Two focal planes A {state['pts'][0]} and B {state['pts'][1]}, {k}: rendered in {dt:.2f} s."
102
+ elif mode == DUAL:
103
+ msg = f"Plane A {state['pts'][0]} set (rendered in {dt:.2f} s). Click a second point for plane B."
104
+ else:
105
+ msg = f"Focus {state['pts'][0]} (D_f = {focal_depth:.2f}), {k}: rendered in {dt:.2f} s."
106
+ return out, depth_image(depth), msg
107
+
108
+
109
+ def draw_markers(im, state, mode):
110
+ """Focal points (A / B with two planes), or the sharp row of tilt-shift, on a 3x supersampled overlay."""
111
+ im = im.convert("RGBA"); S = 3
112
+ ov = Image.new("RGBA", (im.width * S, im.height * S), (0, 0, 0, 0)); d = ImageDraw.Draw(ov)
113
+ r = max(9, round(min(im.size) * 0.022)) * S; lw = max(2, round(r / 6))
114
+ if mode == TILT:
115
+ y = state.get("tilt_row", 0.5) * ov.height
116
+ for x in range(0, ov.width, 12 * lw):
117
+ d.line([x, y, x + 6 * lw, y], fill=(255, 255, 255, 220), width=lw)
118
+ return Image.alpha_composite(im, ov.resize(im.size, Image.LANCZOS)).convert("RGB")
119
+ font = ImageFont.truetype(FONT, round(r * 1.25)) if FONT else ImageFont.load_default()
120
+ for i, (x, y) in enumerate(state["pts"]):
121
+ cx, cy = x * S, y * S
122
+ d.ellipse([cx - r - lw, cy - r - lw, cx + r + lw, cy + r + lw], outline=(0, 0, 0, 170), width=lw * 3)
123
+ d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(255, 255, 255, 255), width=lw)
124
+ dot = lw * 1.3
125
+ d.ellipse([cx - dot, cy - dot, cx + dot, cy + dot], fill=(255, 255, 255, 255))
126
+ if mode == DUAL:
127
+ tx = cx + r + lw * 2 if cx + r * 3 < ov.width else cx - r * 2.2
128
+ d.text((tx, max(0, cy - r * 1.9)), "AB"[i], font=font, fill=(255, 255, 255, 255),
129
+ stroke_width=max(2, lw), stroke_fill=(0, 0, 0, 200))
130
+ return Image.alpha_composite(im, ov.resize(im.size, Image.LANCZOS)).convert("RGB")
131
+
132
+
133
+ def aif_view(state, mode):
134
+ return draw_markers(Image.fromarray(state["aif"]), state, mode)
135
+
136
+
137
+ def on_click(state, strength, mode, gamma, band, show_marker, evt: gr.SelectData):
138
+ if not state:
139
+ return None, None, None, state, "Estimate the depth of an image first."
140
+ p = (int(evt.index[0]), int(evt.index[1]))
141
+ if mode == TILT:
142
+ state = dict(state, tilt_row=p[1] / state["aif"].shape[0])
143
+ else:
144
+ state = dict(state, pts=state["pts"] + [p] if mode == DUAL and len(state["pts"]) == 1 else [p])
145
+ out, depth_view, msg = render(state, strength, mode, gamma, band, show_marker)
146
+ return aif_view(state, mode), out, depth_view, state, msg
147
+
148
+
149
+ def on_change(state, strength, mode, gamma, band, show_marker):
150
+ if not state:
151
+ return gr.update(), None, gr.update(), state, ""
152
+ if mode != DUAL and len(state["pts"]) > 1:
153
+ state = dict(state, pts=state["pts"][:1])
154
+ out, depth_view, msg = render(state, strength, mode, gamma, band, show_marker)
155
+ return aif_view(state, mode), out, depth_view, state, msg
156
+
157
+
158
+ def on_user_depth(state, user_depth, strength, mode, gamma, band, show_marker):
159
+ if not state:
160
+ return gr.update(), None, gr.update(), state, "Estimate the depth of an image first, then upload your depth map."
161
+ h, w = state["aif"].shape[:2]
162
+ state = dict(state, user_depth=None if user_depth is None else engine.depth_from_image(user_depth, h, w))
163
+ out, depth_view, msg = render(state, strength, mode, gamma, band, show_marker)
164
+ note = "Using your depth map. " if user_depth is not None else "Using the estimated depth again. "
165
+ return aif_view(state, mode), out, depth_view, state, note + msg
166
+
167
+
168
+ def on_clear(state, gamma):
169
+ if not state:
170
+ return gr.update(), None, gr.update(), state, ""
171
+ state = dict(state, pts=[], tilt_row=0.5)
172
+ return (Image.fromarray(state["aif"]), None, depth_image(scene_depth(state, gamma)), state,
173
+ "Focal points cleared. Click the image or the depth map to focus.")
174
+
175
+
176
+ RECOMMENDED = {"long_side": 768, "omega": 1.25, "gamma": 1.0, "band": 0.06, "strength": 0.5, "mode": SINGLE,
177
+ "show_marker": False}
178
+
179
+
180
+ def on_reset(state):
181
+ """Recommended settings (the paper's defaults), the estimated depth again; focal points are kept."""
182
+ r = RECOMMENDED
183
+ controls = [r["long_side"], r["omega"], r["gamma"], r["band"], r["strength"], r["mode"], r["show_marker"], None]
184
+ if not state:
185
+ return controls + [gr.update(), None, gr.update(), state, "Settings reset to the recommended values."]
186
+ state = dict(state, user_depth=None, pts=state["pts"][:1])
187
+ out, depth_view, msg = render(state, r["strength"], r["mode"], r["gamma"], r["band"], r["show_marker"])
188
+ note = "Settings reset to the recommended values. "
189
+ return controls + [aif_view(state, r["mode"]), out, depth_view, state, note + msg]
190
+
191
+
192
+ LOGO = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><circle cx="32" cy="32" r="30" fill="#FFFFFF" stroke="#2E7D32" stroke-width="3"/><g fill="#48A43F" stroke="#FFFFFF" stroke-width="1.6" stroke-linejoin="round"><path d="M32 4 A28 28 0 0 1 56.2 18 L40.6 27 Z" transform="rotate(0 32 32)"/><path d="M32 4 A28 28 0 0 1 56.2 18 L40.6 27 Z" transform="rotate(60 32 32)"/><path d="M32 4 A28 28 0 0 1 56.2 18 L40.6 27 Z" transform="rotate(120 32 32)"/><path d="M32 4 A28 28 0 0 1 56.2 18 L40.6 27 Z" transform="rotate(180 32 32)"/><path d="M32 4 A28 28 0 0 1 56.2 18 L40.6 27 Z" transform="rotate(240 32 32)"/><path d="M32 4 A28 28 0 0 1 56.2 18 L40.6 27 Z" transform="rotate(300 32 32)"/></g><path d="M35.5 19 L25.5 34 H31.5 L28.5 45 L39 29 H33 Z" fill="#FFD21E" stroke="#363636" stroke-width="1.4" stroke-linejoin="round"/></svg>
193
+ """
194
+
195
+ HEADER = f"""
196
+ <div id="header">
197
+ <div class="title">{LOGO}<div><h1>FlashReFocus (CPU)</h1><p>This version runs on a free CPU and refocuses photographs that are
198
+ already sharp. For blurred photographs, restoration needs a GPU: use the
199
+ <a href="https://huggingface.co/spaces/ming0531/FlashReFocus" target="_blank">GPU demo</a>.</p></div></div>
200
+ <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> ·
201
+ <a href="https://www.albany.edu/faculty/mchang2/" target="_blank">Ming-Ching Chang</a><sup>2</sup> ·
202
+ <a href="https://scholar.google.com/citations?user=gMBvzGoAAAAJ&hl=en" target="_blank">Xin Li</a><sup>2</sup> ·
203
+ <a href="https://yulunalexliu.github.io/" target="_blank">Yu-Lun Liu</a><sup>3</sup> ·
204
+ <a href="https://cchsu.info/" target="_blank">Chih-Chung Hsu</a><sup>1,3&dagger;</sup><br>
205
+ <small><sup>1</sup>National Cheng Kung University · <sup>2</sup>State University of New York at Albany ·
206
+ <sup>3</sup>National Yang Ming Chiao Tung University · * equal contribution · &dagger; corresponding author</small></div>
207
+ <div class="links">
208
+ <a href="https://huggingface.co/spaces/ming0531/FlashReFocus" target="_blank">⚡ GPU demo (with restoration)</a>
209
+ <a href="https://huggingface.co/spaces/ming0531/FlashReFocus-Video" target="_blank">🎥 Video spotlight demo</a>
210
+ <a href="https://ming053l.github.io/FlashReFocus/" target="_blank">🌐 Project page</a>
211
+ <a href="https://ming053l.github.io/FlashReFocus/assets/FlashReFocus.pdf" target="_blank">📄 Paper</a>
212
+ <a href="https://github.com/ming053l/FlashReFocus" target="_blank">💻 Code</a>
213
+ <a href="https://youtu.be/g032M7moWQ4" target="_blank">🎬 Video</a>
214
+ <a href="https://huggingface.co/datasets/ming0531/3CReal" target="_blank">🗂️ 3CReal dataset</a>
215
+ </div>
216
+ <div class="tip">👉 <b>Try this first:</b> pick the aquarium example → <b>Estimate depth</b> → choose
217
+ <b>👥 Two focal planes</b> → click the face, then the shark. Every click runs only the 1.3M-parameter renderer, which
218
+ takes a few seconds on this CPU (a fraction of a second on a GPU).</div>
219
+ </div>
220
+ """
221
+
222
+ CSS = """
223
+ #header {margin-bottom: 4px}
224
+ #header .title {display: flex; align-items: center; justify-content: center; gap: 16px}
225
+ #header h1 {margin: 0; font-size: 2.1em; color: #2E7D32}
226
+ #header .title p {margin: 2px 0 0; color: var(--body-text-color-subdued)}
227
+ #header .authors {text-align: center; margin-top: 10px; line-height: 1.6}
228
+ #header .authors a {color: #2E7D32; text-decoration: none; font-weight: 600}
229
+ #header .authors small {color: var(--body-text-color-subdued)}
230
+ #header .links {display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin: 12px 0}
231
+ #header .links a {padding: 5px 14px; border-radius: 999px; border: 1px solid #48A43F; color: #2E7D32;
232
+ text-decoration: none; font-weight: 600}
233
+ #header .links a:hover {background: #48A43F; color: white}
234
+ #header .tip {background: #f1f8ef; border-left: 4px solid #48A43F; padding: 10px 14px; border-radius: 8px;
235
+ color: #1f3d1f}
236
+ .step h3 {margin: 6px 0 2px; color: #2E7D32}
237
+ #status {background: #f1f8ef; border-left: 4px solid #48A43F; padding: 8px 14px; border-radius: 8px; min-height: 2.4em}
238
+ #status p {margin: 0; color: #1f3d1f}
239
+ """
240
+
241
+ with gr.Blocks(title="FlashReFocus (CPU)", theme=gr.themes.Soft(primary_hue="green"), css=CSS) as demo:
242
+ gr.HTML(HEADER)
243
+ state = gr.State(None)
244
+ with gr.Row():
245
+ with gr.Column():
246
+ gr.Markdown("### ① Upload a sharp photo and estimate its depth once", elem_classes="step")
247
+ inp = gr.Image(label="Input photograph", type="pil", sources=["upload", "clipboard"], height=320)
248
+ gr.Examples(EXAMPLES, inputs=inp, label="Examples (Unsplash portraits and our own photographs)")
249
+ with gr.Accordion("Image size", open=False):
250
+ long_side = gr.Slider(384, 1024, value=768, step=64, label="Long side (pixels)",
251
+ info="Rendering time on the CPU grows quickly with the size.")
252
+ omega = gr.Slider(0.0, 1.5, value=1.25, step=0.25, label="Detail weight ω", visible=False)
253
+ btn = gr.Button("✨ Estimate depth", variant="primary", size="lg")
254
+ gr.Markdown("### ③ Depth map", elem_classes="step")
255
+ depth = gr.Image(label="Depth used for rendering (near is bright): click to focus", type="pil",
256
+ interactive=False, height=280)
257
+ with gr.Accordion("Depth controls", open=False):
258
+ gamma = gr.Slider(0.4, 2.5, value=1.0, step=0.05, label="Depth curve γ (D → D^γ)",
259
+ info="< 1 spreads out the near range, > 1 the far range; blur follows the new spacing.")
260
+ band = gr.Slider(0.02, 0.3, value=0.06, step=0.01, label="Tilt-shift: half-height of the sharp band")
261
+ user_depth = gr.Image(label="Your own depth map (optional; near is bright, any size)", type="numpy",
262
+ sources=["upload", "clipboard"], height=150)
263
+ with gr.Column():
264
+ gr.Markdown("### ② Click the image to focus", elem_classes="step")
265
+ aif = gr.Image(label="Your photograph (click to focus)", type="pil", interactive=False,
266
+ height=320)
267
+ mode = gr.Radio([SINGLE, DUAL, TILT], value=SINGLE, label="Focus mode",
268
+ info="Two planes: the first click sets A, the second B. Tilt-shift: click the row to keep sharp.")
269
+ strength = gr.Slider(0.0, 1.5, value=0.5, step=0.05, label="🔆 Aperture (blur strength K)",
270
+ info="0: everything sharp; 1: the widest aperture seen in training; above 1 extrapolates.")
271
+ with gr.Row():
272
+ show_marker = gr.Checkbox(value=False, label="Show focal markers")
273
+ clear = gr.Button("Clear focal points", size="sm")
274
+ reset = gr.Button("↺ Recommended settings", size="sm")
275
+ status = gr.Markdown("Upload a sharp photo or pick an example, then press ✨ Estimate depth.", elem_id="status")
276
+ out = gr.Image(label="Refocused result", type="pil", interactive=False, height=430, format="png")
277
+ controls = [state, strength, mode, gamma, band, show_marker]
278
+ outputs = [aif, out, depth, state, status]
279
+ btn.click(restore, [inp, long_side, omega, gamma], [aif, depth, out, state, status])
280
+ aif.select(on_click, controls, outputs)
281
+ depth.select(on_click, controls, outputs)
282
+ for slider in (strength, gamma, band):
283
+ slider.release(on_change, controls, outputs)
284
+ mode.change(on_change, controls, outputs)
285
+ show_marker.change(on_change, controls, outputs)
286
+ user_depth.change(on_user_depth, [state, user_depth, strength, mode, gamma, band, show_marker], outputs)
287
+ clear.click(on_clear, [state, gamma], outputs)
288
+ reset.click(on_reset, [state], [long_side, omega, gamma, band, strength, mode, show_marker, user_depth] + outputs)
289
+
290
+ if __name__ == "__main__":
291
+ demo.queue(max_size=20).launch(show_api=False)
engine.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FlashReFocus on the CPU (free Hugging Face CPU Space), on the flashrefocus package (a copy of the repository's).
2
+
3
+ Photographs that are already sharp only: Stage I (restoration) needs a GPU and is not loaded. Depth Anything V2 runs
4
+ once per photograph at its native input size (518 on the short side), and the 1.3M-parameter renderer renders every
5
+ edit, both in fp32 with the CPU attention path of flashrefocus/rendering/fused.py (same output as the reference up to
6
+ fp32 rounding). The renderer weights come from a private model repository read with the HF_TOKEN secret."""
7
+ import os
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import torch
12
+ from huggingface_hub import hf_hub_download
13
+ from PIL import Image
14
+
15
+ HERE = Path(__file__).resolve().parent
16
+ WEIGHT_REPO = os.environ.get("FLASHREFOCUS_WEIGHT_REPO", "ming0531/FlashReFocus-weights")
17
+ torch.set_num_threads(max(1, os.cpu_count() or 1))
18
+
19
+
20
+ def fetch_weights():
21
+ if "FLASHREFOCUS_WEIGHTS" in os.environ:
22
+ return
23
+ w = HERE / "weights"
24
+ hf_hub_download("depth-anything/Depth-Anything-V2-Large", "depth_anything_v2_vitl.pth", local_dir=w)
25
+ hf_hub_download(WEIGHT_REPO, "renderer.pt", local_dir=w, token=os.environ.get("HF_TOKEN"))
26
+ os.environ["FLASHREFOCUS_WEIGHTS"] = str(w)
27
+
28
+
29
+ fetch_weights()
30
+ from flashrefocus import Refocuser, Scene # noqa: E402
31
+ from flashrefocus.image_io import image_to_tensor, tensor_to_uint8 # noqa: E402
32
+ from flashrefocus.rendering import depth_edits # noqa: E402
33
+
34
+ refocuser = Refocuser.from_pretrained(deblurring=False, device="cpu", fused=True, depth_input_size=518)
35
+
36
+
37
+ @torch.no_grad()
38
+ def restore(rgb, omega=None):
39
+ """HxWx3 uint8 (sides multiples of 16) -> the same image and its depth (HxW float32, 1 = far). No restoration."""
40
+ scene = refocuser.prepare(image_to_tensor(rgb), deblur=False)
41
+ return np.asarray(rgb), scene.depth[0].numpy()
42
+
43
+
44
+ @torch.no_grad()
45
+ def render(rgb, depth, focal_depth, strength):
46
+ """Bokeh (HxWx3 uint8) with blur strength K and focal depth D_f; depth may be edited."""
47
+ d = torch.from_numpy(np.ascontiguousarray(depth, dtype=np.float32))[None]
48
+ return tensor_to_uint8(refocuser.render(Scene(image_to_tensor(rgb), d), strength, focal_depth))
49
+
50
+
51
+ def two_focal_planes(depth, focal_depth_a, focal_depth_b):
52
+ return depth_edits.two_focal_planes(torch.from_numpy(depth)[None], focal_depth_a, focal_depth_b)[0].numpy()
53
+
54
+
55
+ def tilt_shift(height, width, row, band=0.06):
56
+ return depth_edits.tilt_shift(height, width, row, band=band)[0].numpy()
57
+
58
+
59
+ def depth_from_image(image, height, width):
60
+ """A user depth map (near is bright, any size) -> D in [0, 1], 1 = far."""
61
+ grey = Image.fromarray(np.asarray(image)).convert("L").resize((width, height), Image.BILINEAR)
62
+ return (1.0 - np.asarray(grey, dtype=np.float32) / 255.0).astype(np.float32)
examples/dock.jpg ADDED

Git LFS Details

  • SHA256: b0f6b1ecc174d269edd7fd90e44efe1287fdacda991759fb839d80dba527a6bb
  • Pointer size: 131 Bytes
  • Size of remote file: 299 kB
examples/flower.jpg ADDED

Git LFS Details

  • SHA256: f66782457244dc306a0c5da96efd5beed57c29b759c645f4e7b706ef3c17377c
  • Pointer size: 131 Bytes
  • Size of remote file: 255 kB
examples/portrait_aquarium.jpg ADDED
examples/portrait_city.jpg ADDED
examples/sculpture.jpg ADDED

Git LFS Details

  • SHA256: 888bbb28bde07b134921128f6542943116a80c0b2c93258f95b6d3877c6fcc61
  • Pointer size: 131 Bytes
  • Size of remote file: 355 kB
flashrefocus/README.md ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ | `depth_input_size` | `1024` | Short side at which Depth Anything V2 runs. 518 (its native size) is about 5x faster on the CPU. |
21
+ | `device` | `"cuda"` | `"cpu"` with `deblurring=False`, see [Running on the CPU](#running-on-the-cpu). |
22
+
23
+ Stage I alone: `flashrefocus.deblurring.Deblurrer.from_pretrained()(x)` restores an image `x` in [-1, 1].
24
+ `Deblurrer.from_pretrained(separate_unets=True)` keeps the pixel and pixel + detail U-Nets as two modules instead of
25
+ swapping weights in place (same output, twice the U-Net memory), as the Hugging Face demo does on ZeroGPU.
26
+
27
+ ## Scenes and rendering
28
+
29
+ - `refocuser.prepare(image, deblur=True)` returns a `Scene`: the restored image (quantized to 8 bits, as when it is
30
+ saved and reloaded) and its depth. `deblur=False` skips Stage I. Image sides must be multiples of 16
31
+ (`image_io.read_image(path, device, multiple=16)` or `image_io.resize_to_multiple` pad or resize).
32
+ - `scene.focal_depth_at(x, y)` gives the focal depth D_f of a pixel.
33
+ - `refocuser.render(scene, strength, focal_depth, depth=None)` returns the result (b, 3, H, W) in [0, 1]. The strength K
34
+ is trained in [0, 1]; larger values extrapolate. `depth` replaces the scene depth, for the edits in
35
+ [`rendering/depth_edits.py`](rendering/depth_edits.py) (listed in the top-level README under Applications).
36
+ - `render` takes the focal depth rather than a pixel, so a video can be processed as one `Scene` per frame, with D_f
37
+ and K chosen per frame (for example smoothed over time).
38
+ - `refocuser.render_batch(images, depths, strengths, focal_depths)` renders several frames in one call, with one
39
+ strength and focal depth per frame. It gives the same result as rendering them one by one. At video resolutions one
40
+ frame already fills a large GPU, so it is a convenience, not a speed-up.
41
+
42
+ ## Depth edits
43
+
44
+ Every effect replaces the depth passed to `render`. The renderer was trained with one focal plane and one strength per
45
+ image, so all of them are zero-shot.
46
+
47
+ | Effect | `depth_edits` function | ComfyUI node |
48
+ |---|---|---|
49
+ | Focus range: a thick focal plane, separate from the aperture | `focus_range` | Focus Range |
50
+ | Radial (Lensbaby-style) focus around a point | `radial_focus` | Radial Focus |
51
+ | Tilt-shift band at any angle | `tilted_band` (`tilt_shift` for horizontal) | Tilt-Shift |
52
+ | Blur only the background, or only the foreground | `one_sided` | One-Sided Blur |
53
+ | Two, three or more focal planes | `focal_planes` (`two_focal_planes`) | Add Focal Plane |
54
+ | Keep a masked subject sharp while the focus moves | `keep_sharp` | Focus on Mask, Mask Depth Edit |
55
+ | Remove a photobomber: push him into the background bokeh (no inpainting) | `set_mask_depth(…, 1.0)` | Mask Depth Edit (`push_far`) |
56
+ | Optical privacy blur for faces or plates | `move_away` | Mask Depth Edit (`move_away`) |
57
+ | Per-layer blur, or a front layer for a flat picture | `set_mask_depth` | Mask Depth Edit (`set_depth`) |
58
+ | Isolate a subject: everything else at least a set distance from focus | `isolate` | Mask Depth Edit (`isolate`) |
59
+ | Portrait mode on a sharp photograph (skip Stage I) | `prepare(image, deblur=False)` | Prepare (`already_sharp`) |
60
+ | Video focus pull | one `Scene` per frame, smoothed depth and focus | Prepare + Focus Point with an image batch |
61
+ | Video spotlight (one subject sharp, everyone else blurred) | `spotlight` + `flashrefocus.segment.track_subject` (SAM 3) | SAM 3 Subject + Spotlight |
62
+ | Burnt-in titles kept sharp in video | `flashrefocus.overlays.fill_region` / `paste_back` | Overlay Fill + Overlay Paste Back |
63
+
64
+ In Python:
65
+
66
+ ```python
67
+ from flashrefocus.rendering import depth_edits
68
+
69
+ _, H, W = scene.depth.shape # scene = refocuser.prepare(...); focal_depth = scene.focal_depth_at(x, y)
70
+ edits = {
71
+ "focus_range": (depth_edits.focus_range(scene.depth, focal_depth, width=0.2), focal_depth),
72
+ "background_only": (depth_edits.one_sided(scene.depth, focal_depth, keep="foreground"), focal_depth),
73
+ "three_planes": (depth_edits.focal_planes(scene.depth, [focal_depth, scene.focal_depth_at(x2, y2), 0.9]), focal_depth),
74
+ "radial": (depth_edits.radial_focus(H, W, 0.5, 0.6, radius=0.12, device="cuda"), 0.5),
75
+ "tilt_shift_20deg": (depth_edits.tilted_band(H, W, 0.5, 0.6, angle=20, device="cuda"), 0.5),
76
+ "keep_sharp": (depth_edits.keep_sharp(scene.depth, mask, focal_depth), focal_depth), # mask: H x W bool
77
+ "remove_photobomber": (depth_edits.set_mask_depth(scene.depth, mask, 1.0), focal_depth),
78
+ "privacy_blur": (depth_edits.move_away(scene.depth, mask, focal_depth, 0.3), focal_depth),
79
+ "isolate_subject": (depth_edits.isolate(scene.depth, mask, focal_depth, 0.25), focal_depth),
80
+ }
81
+ for name, (depth, d_f) in edits.items():
82
+ save_image(refocuser.render(scene, 0.8, d_f, depth=depth), f"{name}.png") # about half a second each
83
+ ```
84
+
85
+ `mask` is an H x W bool tensor from any segmenter, for example Segment Anything from a click or a box, or CLIPSeg from
86
+ a text prompt.
87
+
88
+ ## Video spotlight
89
+
90
+ ```python
91
+ from flashrefocus.segment import track_subject # SAM 3: transformers >= 5.0, access to facebook/sam3
92
+ from flashrefocus.rendering import depth_edits
93
+
94
+ refocuser = Refocuser.from_pretrained(deblurring=False, fused=True)
95
+ subject, others = track_subject(frames, prompt="person", select="most_central") # frames: (n, h, w, 3) uint8
96
+ for frame, m, o in zip(frames_as_tensors, subject, others):
97
+ scene = refocuser.prepare(frame, deblur=False)
98
+ d_f = float(scene.depth[0][m].median()) # smooth over frames in practice
99
+ depth, _ = depth_edits.spotlight(scene.depth, m[None], d_f, gap=0.6, others=o[None], grow=10)
100
+ out = refocuser.render(scene, 1.5, d_f, depth=depth)
101
+ ```
102
+
103
+ - `track_subject(frames, prompt, select, point, chunk)` tracks every instance of `prompt` with SAM 3, in chunks of
104
+ `chunk` frames. It returns the chosen subject's masks and the union of the other tracks. `select` is
105
+ `"most_central"`, `"largest"` or `"point"` (the track under `point`, given as fractions of width and height). The
106
+ subject is carried from one chunk to the next by mask overlap.
107
+ - `spotlight(depth, mask, focal_depth, gap, others, grow)` sets the subject to the focal depth and moves every other
108
+ pixel at least `gap` from it. First it grows the mask by up to `grow` pixels into neighbouring pixels at the
109
+ subject's depth that are not in `others` (hands and hair that segmentation misses).
110
+ - Burnt-in titles: `overlays.fill_region(image, mask)` fills the title from its surroundings before rendering, so the
111
+ renderer does not blur the letters into a flickering glow. `overlays.paste_back(result, original, mask)` then puts
112
+ the sharp title back.
113
+
114
+ ## Writing results
115
+
116
+ - `image_io.save_image(x, path, background=True)` copies the image to the CPU at once and compresses and writes the PNG
117
+ on a background thread (the same file, byte for byte). `image_io.wait_for_writes()` waits for pending files.
118
+ - `video.VideoWriter(path, fps, codec="auto", quality=18, audio_from=None)` streams frames into one ffmpeg encode from
119
+ a background thread, so encoding overlaps rendering. It picks the first encoder that works: NVENC, libx264,
120
+ libopenh264, then mpeg4. `audio_from=` copies the audio of the source clip. ffmpeg is taken from
121
+ `$FLASHREFOCUS_FFMPEG`, `imageio-ffmpeg`, or `PATH`.
122
+
123
+ ```python
124
+ from flashrefocus.video import VideoWriter
125
+
126
+ with VideoWriter("refocused.mp4", fps=30, audio_from="clip.mp4") as writer:
127
+ for scene, d_f in zip(scenes, focal_depths):
128
+ writer.write(refocuser.render(scene, 1.0, d_f))
129
+ ```
130
+
131
+ ## Speed-ups
132
+
133
+ Both options are off by default, so the reported numbers are reproduced exactly. ComfyUI and the demo turn `fused` on.
134
+
135
+ - **`fused=True`** runs the renderer's defocus-bias attention as one Triton kernel
136
+ ([`rendering/fused.py`](rendering/fused.py)). The kernel computes the defocus bias from the per-token defocus values
137
+ and uses an online softmax, so the per-row and per-column bias and attention matrices are never stored. Weights are
138
+ unchanged, and outputs match the reference path to about 61 dB in bf16 and 80 dB in fp32. On an RTX PRO 6000,
139
+ 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
140
+ peak memory drops from 16.1 to 3.0 GiB. Without Triton, or on CPU, the reference code runs.
141
+ `rendering.fused.enable_fused(renderer)` switches a renderer that is already loaded.
142
+ - **`compile="static"`** (or `"dynamic"`) compiles Stage I's two full-resolution parts, the decoder refiner and the VAE
143
+ encoder, with `torch.compile`. Restoration is about 35-40% faster after a one-time compilation of one to two
144
+ minutes, and outputs match the eager path to about 57-62 dB. `"static"` is fastest for many images of one size and
145
+ recompiles for a new size. `"dynamic"` compiles once for all sizes and is about 10% slower.
146
+
147
+ ## Running on the CPU
148
+
149
+ The depth estimator and the renderer run without a GPU, for images that are already sharp (Stage I needs CUDA):
150
+
151
+ ```python
152
+ refocuser = Refocuser.from_pretrained(deblurring=False, device="cpu", fused=True, depth_input_size=518)
153
+ scene = refocuser.prepare(read_image("photo.jpg", "cpu", multiple=16), deblur=False)
154
+ bokeh = refocuser.render(scene, 0.8, scene.focal_depth_at(x, y))
155
+ ```
156
+
157
+ On the CPU both models run in fp32 (bf16 and fp16 are emulated on most CPUs and much slower), and the renderer uses
158
+ channels-last tensors. `fused=True` selects a CPU attention path: the defocus bias from one `torch.cdist` and the
159
+ attention from PyTorch's fused `scaled_dot_product_attention`, with outputs equal to the reference up to fp32 rounding.
160
+ Measured with 16 threads of a Threadripper 3960X (AVX2) shared with other jobs:
161
+
162
+ | 768x512 image | Time |
163
+ |---|---|
164
+ | Depth, `depth_input_size=1024` / `518` | 18.9 s / 3.4 s (once per image) |
165
+ | Render, reference / `fused=True` | 2.1 s / 1.2 s (per edit) |
166
+
167
+ At 1024x672 a render takes 4.4 s with the reference path and 2.9 s with `fused=True`. INT8 dynamic quantization of
168
+ the depth model gave only about 15% more speed and a larger depth error than `depth_input_size=518`.
169
+
170
+ ## Reproducibility
171
+
172
+ Outputs are bit-reproducible with `torch.backends.cudnn.benchmark = False`. cuDNN autotuning is faster for a fixed
173
+ input size, but it may pick different convolution algorithms between runs, which changes outputs by a few 1/255.
174
+
175
+ ## Tests
176
+
177
+ The regression test restores two small photographs in `tests/data/` and compares the restored image, depth, refocused
178
+ image, two focal planes and tilt-shift with `tests/reference/`: bit-identical on the machine that made the references,
179
+ PSNR >= 45 dB elsewhere (floating-point differences between GPUs and library versions). Regenerate the references with
180
+ `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,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (or the CPU, without Stage I); 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, depth_input_size=1024):
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
+ depth_input_size: short side at which Depth Anything V2 runs (1024 for the reported results; 518, its native
56
+ size, is about 5x faster on the CPU).
57
+
58
+ device="cpu" needs deblurring=False (Stage I builds on CUDA). On the CPU the depth model and the renderer run in
59
+ fp32 (bf16 and fp16 are emulated on most CPUs), the renderer uses channels-last tensors, and fused=True selects
60
+ a CPU attention path (flashrefocus/rendering/fused.py); the output matches the reference to fp32 rounding."""
61
+ if str(device).startswith("cpu"):
62
+ if deblurring:
63
+ raise ValueError("Stage I needs CUDA: use deblurring=False on the CPU (for images that are already sharp)")
64
+ channels_last = True
65
+ if deblurring: # Stage I (and its pinned diffusers / transformers) only when restoring
66
+ from .deblurring.deblurrer import Deblurrer
67
+ deblurrer = Deblurrer.from_pretrained(refiner=refiner, detail_weight=detail_weight, refiner_dtype=refiner_dtype,
68
+ merge_vae_lora=merge_vae_lora, compile=compile) if deblurring else None
69
+ refocuser = cls(deblurrer, DepthEstimator.from_pretrained(device=device, input_size=depth_input_size),
70
+ load_renderer(paths.RENDERER, device),
71
+ render_dtype, channels_last)
72
+ if fused:
73
+ from .rendering.fused import enable_fused
74
+ enable_fused(refocuser.renderer)
75
+ if channels_last:
76
+ modules = [refocuser.renderer]
77
+ if deblurrer is not None:
78
+ modules += [deblurrer.model.vae, deblurrer.model.unet] + ([deblurrer.refiner] if deblurrer.refiner is not None else [])
79
+ for module in modules:
80
+ module.to(memory_format=torch.channels_last)
81
+ return refocuser
82
+
83
+ def scene_from_file(self, path, deblur=False):
84
+ """Scene of an image file (by default already all-in-focus)."""
85
+ return self.prepare(read_image(path, self.renderer.mean.device), deblur=deblur)
86
+
87
+ def render_to_file(self, scene, strength, focal_depth, path, depth=None):
88
+ bokeh = self.render(scene, strength, focal_depth, depth)
89
+ save_image(bokeh, path)
90
+ return bokeh
91
+
92
+ def _memory_format(self, x):
93
+ return x.contiguous(memory_format=torch.channels_last) if self.channels_last else x
94
+
95
+ @torch.no_grad()
96
+ def deblur(self, image):
97
+ """Stage I: blurred image -> all-in-focus image, both in [0, 1] (the output is not clamped)."""
98
+ return to_unit_range(self.deblurrer(self._memory_format(to_signed(image))))
99
+
100
+ @torch.no_grad()
101
+ def prepare(self, image, deblur=True):
102
+ """Scene of an image: Stage I (skipped for an image that is already all-in-focus) and its depth. The restored
103
+ image is quantised to 8 bits, as when it is saved and reloaded."""
104
+ aif = quantize_to_8_bits(self.deblur(image)) if deblur else image
105
+ return Scene(aif, self.depth_estimator(aif))
106
+
107
+ @torch.no_grad()
108
+ def render(self, scene, strength, focal_depth, depth=None):
109
+ """Stage II: bokeh (b, 3, H, W) in [0, 1] with blur strength K and focal depth D_f. `depth` replaces the
110
+ scene depth, for depth edits (two focal planes, tilt-shift)."""
111
+ depth = scene.depth if depth is None else depth
112
+ image = self._memory_format(scene.image)
113
+ device = image.device
114
+ with torch.autocast(device.type, dtype=self.render_dtype or torch.float32,
115
+ enabled=self.render_dtype is not None and device.type == "cuda"): # fp32 on the CPU
116
+ return self.renderer(image, torch.tensor([[float(strength)]], device=device), depth[None],
117
+ torch.tensor([[float(focal_depth)]], device=device)).float()
118
+
119
+ @torch.no_grad()
120
+ def render_batch(self, images, depths, strengths, focal_depths):
121
+ """Stage II for several frames in one pass (video): images (b, 3, H, W), depths (b, H, W), one strength and one
122
+ focal depth per frame (sequences or scalars). The same result as rendering the frames one by one, up to
123
+ rounding; at video resolutions one frame already fills a large GPU, so this is a convenience, not a speed-up."""
124
+ b = images.shape[0]
125
+ device = images.device
126
+
127
+ def per_frame(v):
128
+ t = torch.as_tensor(v, dtype=torch.float32, device=device).flatten()
129
+ return (t.expand(b) if t.numel() == 1 else t).view(b, 1)
130
+
131
+ with torch.autocast(device.type, dtype=self.render_dtype or torch.float32,
132
+ enabled=self.render_dtype is not None and device.type == "cuda"):
133
+ return self.renderer(self._memory_format(images), per_frame(strengths), depths.view(b, 1, *depths.shape[-2:]),
134
+ 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 on CUDA and in fp32 on the CPU (fp16 is emulated there and far slower)."""
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, enabled=image.is_cuda): # fp32 on the CPU
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,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ On the CPU, enable_fused uses a second path (cpu_attention_forward): |T_D,i - T_D,j| comes from one torch.cdist and
14
+ the attention from PyTorch's fused scaled_dot_product_attention, with the scaled bias as its additive mask. It still
15
+ stores the bias, but replaces the separate subtract, abs, negate, scale and add passes and the separate softmax
16
+ (about 40% of the CPU time of the reference); outputs match the reference to fp32 rounding. Without Triton on CUDA
17
+ the reference implementation is used.
18
+ """
19
+ import torch
20
+ import torch.nn.functional as F
21
+
22
+ try:
23
+ import triton
24
+ import triton.language as tl
25
+ HAVE_TRITON = True
26
+ except ImportError: # pragma: no cover
27
+ HAVE_TRITON = False
28
+
29
+
30
+ if HAVE_TRITON:
31
+ @triton.autotune(
32
+ configs=[triton.Config({"BLOCK_M": bm, "BLOCK_N": bn}, num_warps=nw, num_stages=ns)
33
+ for bm, bn, nw, ns in [(128, 32, 4, 3), (128, 64, 4, 2), (128, 32, 2, 3), (64, 64, 4, 2),
34
+ (32, 64, 2, 3), (64, 128, 4, 2)]],
35
+ key=["L", "D"])
36
+ @triton.jit
37
+ def _axial_bias_attention_kernel(
38
+ Q, K, V, T, S, O,
39
+ sq_b, sq_i, sq_l, sq_h, # q strides: batch, inner (the other axis), sequence, head
40
+ sk_b, sk_i, sk_l, sk_h,
41
+ sv_b, sv_i, sv_l, sv_h,
42
+ so_b, so_i, so_l, so_h,
43
+ st_b, st_i, st_l, st_h, # T_D strides (no channel dimension)
44
+ inner, heads, L,
45
+ D: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
46
+ pid_m = tl.program_id(0)
47
+ z = tl.program_id(1)
48
+ hd = z % heads
49
+ zi = (z // heads) % inner
50
+ zb = z // (heads * inner)
51
+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
52
+ offs_n = tl.arange(0, BLOCK_N)
53
+ offs_d = tl.arange(0, D)
54
+ q_base = Q + zb * sq_b + zi * sq_i + hd * sq_h
55
+ k_base = K + zb * sk_b + zi * sk_i + hd * sk_h
56
+ v_base = V + zb * sv_b + zi * sv_i + hd * sv_h
57
+ t_base = T + zb * st_b + zi * st_i + hd * st_h
58
+ mask_m = offs_m < L
59
+ q = tl.load(q_base + offs_m[:, None] * sq_l + offs_d[None, :], mask=mask_m[:, None], other=0.0)
60
+ t_q = tl.load(t_base + offs_m * st_l, mask=mask_m, other=0.0).to(tl.float32)
61
+ s = tl.load(S + zb * heads + hd).to(tl.float32) # gamma_b * alpha of this image and head
62
+ m_i = tl.full([BLOCK_M], float("-inf"), tl.float32)
63
+ l_i = tl.zeros([BLOCK_M], tl.float32)
64
+ acc = tl.zeros([BLOCK_M, D], tl.float32)
65
+ for start_n in range(0, L, BLOCK_N):
66
+ cols = start_n + offs_n
67
+ mask_n = cols < L
68
+ k = tl.load(k_base + cols[:, None] * sk_l + offs_d[None, :], mask=mask_n[:, None], other=0.0)
69
+ t_k = tl.load(t_base + cols * st_l, mask=mask_n, other=0.0).to(tl.float32)
70
+ qk = tl.dot(q, tl.trans(k)) # fp32 accumulate
71
+ qk = qk - s * tl.abs(t_q[:, None] - t_k[None, :])
72
+ qk = tl.where(mask_n[None, :], qk, float("-inf"))
73
+ m_new = tl.maximum(m_i, tl.max(qk, 1))
74
+ p = tl.exp(qk - m_new[:, None])
75
+ alpha = tl.exp(m_i - m_new)
76
+ l_i = l_i * alpha + tl.sum(p, 1)
77
+ v = tl.load(v_base + cols[:, None] * sv_l + offs_d[None, :], mask=mask_n[:, None], other=0.0)
78
+ acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v)
79
+ m_i = m_new
80
+ acc = acc / l_i[:, None]
81
+ o_base = O + zb * so_b + zi * so_i + hd * so_h
82
+ tl.store(o_base + offs_m[:, None] * so_l + offs_d[None, :], acc.to(O.dtype.element_ty), mask=mask_m[:, None])
83
+
84
+
85
+ def _axial_pass(q, k, v, t, scale, axis):
86
+ """One axial pass. q, k, v: (b, h, w, heads, d) views; t: (b, h, w, heads); scale: (b, heads).
87
+ axis = 2 attends along w (each row), axis = 1 along h (each column). Returns (b, h, w, heads, d) contiguous."""
88
+ b, h, w, heads, d = q.shape
89
+ out = torch.empty((b, h, w, heads, d), device=q.device, dtype=q.dtype)
90
+ other = 1 if axis == 2 else 2
91
+ inner, L = q.shape[other], q.shape[axis]
92
+
93
+ def st5(x):
94
+ return x.stride(0), x.stride(other), x.stride(axis), x.stride(3)
95
+
96
+ st_t = (t.stride(0), t.stride(other), t.stride(axis), t.stride(3))
97
+ for x in (q, k, v, out):
98
+ assert x.stride(4) == 1
99
+ grid = lambda meta: (triton.cdiv(L, meta["BLOCK_M"]), b * inner * heads) # noqa: E731
100
+ _axial_bias_attention_kernel[grid](q, k, v, t, scale, out, *st5(q), *st5(k), *st5(v), *st5(out), *st_t,
101
+ inner, heads, L, D=d)
102
+ return out
103
+
104
+
105
+ def cpu_attention_forward(self, x, defocus, strength):
106
+ """DefocusBiasAttention.forward for the CPU: the same computation, with the bias |T_D,i - T_D,j| from one
107
+ torch.cdist and softmax(QK^T / sqrt(d) + gamma_b alpha B) V from the fused scaled_dot_product_attention."""
108
+ b, h, w, c = x.shape
109
+ heads, d = self.num_heads, self.key_dim
110
+ q = self.q_proj(x).view(b, h, w, heads, d)
111
+ k = self.k_proj(x).view(b, h, w, heads, d)
112
+ v = self.v_proj(x)
113
+ lepe = self.lepe(v)
114
+ v = v.view(b, h, w, heads, d)
115
+ t_d = self.defocus_head_proj(self._log_features(defocus)) # T_D: b, h, w, heads
116
+ scale = (self._gamma_b(x, strength) * self.defocus_alpha.view(1, 1, heads, 1, 1)).view(b, 1, heads, 1, 1)
117
+ t = t_d.permute(0, 1, 3, 2).unsqueeze(-1) # rows: b, h, heads, w, 1
118
+ rows = F.scaled_dot_product_attention(q.permute(0, 1, 3, 2, 4), k.permute(0, 1, 3, 2, 4), v.permute(0, 1, 3, 2, 4),
119
+ attn_mask=torch.cdist(t, t, p=1).mul_(-scale), scale=self.scaling)
120
+ t = t_d.permute(0, 2, 3, 1).unsqueeze(-1) # columns: b, w, heads, h, 1
121
+ out = F.scaled_dot_product_attention(q.permute(0, 2, 3, 1, 4), k.permute(0, 2, 3, 1, 4), rows.permute(0, 3, 2, 1, 4),
122
+ attn_mask=torch.cdist(t, t, p=1).mul_(-scale), scale=self.scaling)
123
+ return self.out_proj(out.permute(0, 3, 1, 2, 4).reshape(b, h, w, c) + lepe)
124
+
125
+
126
+ def fused_attention_forward(self, x, defocus, strength):
127
+ """Drop-in forward of DefocusBiasAttention using the fused kernel (same parameters, same output)."""
128
+ if x.device.type == "cpu" and not self.training:
129
+ return cpu_attention_forward(self, x, defocus, strength)
130
+ if not (HAVE_TRITON and x.is_cuda) or self.training or self.key_dim not in (16, 32, 64, 128):
131
+ return type(self).forward(self, x, defocus, strength)
132
+ b, h, w, c = x.shape
133
+ q = self.q_proj(x)
134
+ k = self.k_proj(x) * self.scaling
135
+ v = self.v_proj(x)
136
+ lepe = self.lepe(v)
137
+ dt = q.dtype
138
+ q5 = q.view(b, h, w, self.num_heads, self.key_dim)
139
+ k5 = k.to(dt).view(b, h, w, self.num_heads, self.key_dim)
140
+ v5 = v.view(b, h, w, self.num_heads, self.key_dim)
141
+ t_d = self.defocus_head_proj(self._log_features(defocus)).float().contiguous() # T_D: b, h, w, heads
142
+ scale = (self._gamma_b(x, strength).view(b, self.num_heads).float()
143
+ * self.defocus_alpha.float().view(1, self.num_heads)).contiguous() # gamma_b * alpha: b, heads
144
+ rows = _axial_pass(q5, k5, v5, t_d, scale, axis=2)
145
+ out = _axial_pass(q5, k5, rows, t_d, scale, axis=1)
146
+ return self.out_proj(out.view(b, h, w, c) + lepe)
147
+
148
+
149
+ def enable_fused(renderer):
150
+ """Switch every DefocusBiasAttention in `renderer` to the fused kernel (CUDA) or the CPU path. Returns the
151
+ renderer."""
152
+ from .defocus_bias_attention import DefocusBiasAttention
153
+ for m in renderer.modules():
154
+ if isinstance(m, DefocusBiasAttention):
155
+ m.forward = fused_attention_forward.__get__(m)
156
+ 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 >= 5.0 (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 >= 5.0 (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,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch==2.8.0
2
+ torchvision==0.23.0
3
+ timm==1.0.30
4
+ einops==0.8.2
5
+ opencv-python-headless==5.0.0.93
6
+ safetensors==0.8.0
7
+ numpy==2.2.6
8
+ scipy
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