jennyxue commited on
Commit
aa18c94
·
verified ·
1 Parent(s): e7b9c39

int8 build of DiffuEraser

Browse files
.gitattributes CHANGED
@@ -35,3 +35,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  fp16/brushnet.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  fp16/unet.onnx.data filter=lfs diff=lfs merge=lfs -text
 
 
 
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  fp16/brushnet.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  fp16/unet.onnx.data filter=lfs diff=lfs merge=lfs -text
38
+ int8/brushnet.onnx.data filter=lfs diff=lfs merge=lfs -text
39
+ int8/unet.onnx.data filter=lfs diff=lfs merge=lfs -text
int8/brushnet.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:199ed052adddb2bf02d6d1837cb790e3d7ff64ea13c9cdb7a8e469ff8425fcb7
3
+ size 805102
int8/brushnet.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:deef2c36bc2da8efd098ae3b1cd87a2b098f45f3bf5e8194cade3c1141b13fb9
3
+ size 1545010560
int8/pipeline.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DiffuEraser video inpainting with ONNX Runtime: the SD VAE (encoder, decoder), BrushNet and the motion UNet (with the
2
+ PCM 2-step LoRA merged) as ONNX graphs, numpy around them, following the repository's DiffuEraser.forward
3
+ (run_diffueraser.py settings: 2 TCD steps, guidance 0, clips of 22 frames, mask dilation 8, blended composite).
4
+
5
+ DiffuEraser refines a prior: the frames as a first-pass inpainter left them. The repository makes the prior with
6
+ ProPainter (non-commercial S-Lab License; ONNX builds: moonbox-dev/ProPainter-ONNX) and passes it in; so does this
7
+ runtime (`priors`). Needs numpy, scipy, onnxruntime (or onnxruntime-gpu) and Pillow; opencv-python (optional) for the
8
+ exact mask blur of the original (else a scipy Gaussian, within one grey level).
9
+
10
+ python fp16/pipeline.py frames_dir masks_dir priors_dir out_dir [--max-size 960] [--seed 42] [--cuda]
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+
19
+ NFRAMES = 22
20
+ SCALING = 0.18215
21
+ ALPHA0, SIGMA0 = 0.06826488673686981, 0.9976671934127808 # UniPC add_noise at "t = 0" (its sigma at index 999)
22
+ TIMESTEPS = (999, 499)
23
+
24
+
25
+ def alphas_cumprod():
26
+ b = np.linspace(0.00085 ** 0.5, 0.012 ** 0.5, 1000, dtype=np.float32) ** 2
27
+ return np.cumprod(1.0 - b.astype(np.float64)).astype(np.float32)
28
+
29
+
30
+ AC = alphas_cumprod()
31
+
32
+
33
+ def tcd_step(eps, t, x):
34
+ """TCDScheduler.step with eta 0 (epsilon prediction): x0 from the noise, re-noised to the next timestep (0 after
35
+ the last)."""
36
+ i = TIMESTEPS.index(t)
37
+ s = TIMESTEPS[i + 1] if i + 1 < len(TIMESTEPS) else 0
38
+ a_t, a_s = AC[t], AC[s]
39
+ x0 = (x - np.sqrt(1 - a_t) * eps) / np.sqrt(a_t)
40
+ return np.sqrt(a_s) * x0 + np.sqrt(1 - a_s) * eps
41
+
42
+
43
+ def contexts(total, overlap, n):
44
+ """get_frames_context_swap: windows of n frames stepping n - overlap (plus one at the end), and the same shifted by
45
+ n / 2 (used on odd steps)."""
46
+ if total < n:
47
+ n = total
48
+ cl, cs = [], []
49
+ idx = np.arange(total)
50
+ if total > n:
51
+ k = 0
52
+ for k in range(0, total - n, n - overlap):
53
+ cl.append(idx[k:k + n])
54
+ if k + n < total:
55
+ cl.append(idx[total - n:total])
56
+ cs.append(idx[0:n])
57
+ for k in range(n // 2, total - n, n - overlap):
58
+ cs.append(idx[k:k + n])
59
+ if k + n < total:
60
+ cs.append(idx[total - n:total])
61
+ if total == n:
62
+ cl.append(idx[total - n:total]); cs.append(idx[total - n:total])
63
+ return cl, cs
64
+
65
+
66
+ def to_l(img):
67
+ """PIL convert('L') on an RGB uint8 array (ITU-R 601-2: L = R 299/1000 + G 587/1000 + B 114/1000)."""
68
+ from PIL import Image
69
+ return np.asarray(Image.fromarray(img).convert("L"))
70
+
71
+
72
+ def process_mask(m_rgb, size, dilate):
73
+ """read_mask: luma, nearest resize, > 0, erode 3 x 3 once, dilate 3 x 3 `dilate` times (OpenCV's borders: the
74
+ outside never erodes, never dilates)."""
75
+ from PIL import Image
76
+ from scipy import ndimage
77
+ m = Image.fromarray(to_l(m_rgb))
78
+ if m.size != size:
79
+ m = m.resize(size, Image.NEAREST)
80
+ m = np.asarray(m) > 0
81
+ k = np.ones((3, 3), bool)
82
+ m = ndimage.binary_erosion(m, k, border_value=1)
83
+ m = ndimage.binary_dilation(m, k, iterations=dilate, border_value=0) if dilate > 0 else m
84
+ return m.astype(np.uint8) * 255
85
+
86
+
87
+ def blur21(m):
88
+ """cv2.GaussianBlur(m, (21, 21), 0) on uint8 (sigma 3.5, reflect-101 borders)."""
89
+ try:
90
+ import cv2
91
+ return cv2.GaussianBlur(m, (21, 21), 0)
92
+ except ImportError:
93
+ from scipy import ndimage
94
+ x = np.arange(21) - 10
95
+ k = np.exp(-x ** 2 / (2 * 3.5 ** 2)); k /= k.sum()
96
+ f = ndimage.convolve1d(ndimage.convolve1d(m.astype(np.float64), k, 0, mode="mirror"), k, 1, mode="mirror")
97
+ return np.clip(np.round(f), 0, 255).astype(np.uint8)
98
+
99
+
100
+ def target_size(w, h, max_size):
101
+ """read_video: downscale so the long side is at most max_size, both sides multiples of 8."""
102
+ m = max(w, h)
103
+ if m < 256 or m > 4096:
104
+ raise ValueError("the video's long side must be 256 - 4096 px")
105
+ if m > max_size:
106
+ r = m / max_size
107
+ w, h = int(w / r), int(h / r)
108
+ return (w - w % 8, h - h % 8), True
109
+ if w % 8 == 0 and h % 8 == 0:
110
+ return (w, h), False
111
+ return (w - w % 8, h - h % 8), True
112
+
113
+
114
+ def to_unit(img):
115
+ """VaeImageProcessor.preprocess: uint8 RGB -> [1, 3, H, W] in [-1, 1]."""
116
+ return (np.asarray(img, np.float32).transpose(2, 0, 1)[None] / 255.0) * 2 - 1
117
+
118
+
119
+ def to_uint8(x):
120
+ """VaeImageProcessor.postprocess (pil): [-1, 1] -> uint8, rounded."""
121
+ return np.round(np.clip(x / 2 + 0.5, 0, 1).transpose(0, 2, 3, 1) * 255).astype(np.uint8)
122
+
123
+
124
+ class DiffuEraser:
125
+ def __init__(self, folder, provider="cpu"):
126
+ import onnxruntime as ort
127
+ folder = Path(folder)
128
+ if provider != "cpu" and hasattr(ort, "preload_dlls"):
129
+ try:
130
+ ort.preload_dlls()
131
+ except Exception:
132
+ pass
133
+ so = ort.SessionOptions()
134
+ so.log_severity_level = 3
135
+ so.enable_mem_pattern = False # the UNet's activations: ~1 GB less peak memory without these
136
+ so.enable_cpu_mem_arena = False
137
+ # cuDNN: heuristic algorithm choice and no maximum workspace (the defaults hold GBs of workspace for the UNet)
138
+ pv = ["CPUExecutionProvider"] if provider == "cpu" else [
139
+ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested", "cudnn_conv_algo_search": "HEURISTIC",
140
+ "cudnn_conv_use_max_workspace": "0"}), "CPUExecutionProvider"]
141
+ self.s = {n: ort.InferenceSession(str(folder / f"{n}.onnx"), so, providers=pv)
142
+ for n in ("vae_encoder", "vae_decoder", "brushnet", "unet")}
143
+ self.ro = ort.RunOptions()
144
+ if provider != "cpu": # Windows: sizes vary, and the GPU arena would keep every size's buffers
145
+ self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0")
146
+ self.dt = {n: {i.name: (np.float16 if i.type == "tensor(float16)" else
147
+ np.int64 if i.type == "tensor(int64)" else np.float32) for i in s.get_inputs()}
148
+ for n, s in self.s.items()}
149
+ self.res = [o.name for o in self.s["brushnet"].get_outputs()]
150
+ self.text = np.load(folder / "text_embeds.npy").astype(np.float32) # CLIP("") [1, 77, 768]
151
+
152
+ def run(self, name, **feeds):
153
+ feeds = {k: np.ascontiguousarray(v, self.dt[name][k]) for k, v in feeds.items()}
154
+ out = [o.astype(np.float32) for o in self.s[name].run(None, feeds, self.ro)]
155
+ return out[0] if len(out) == 1 else out
156
+
157
+ # -- building blocks (the torch-checked driver swaps these) -----------------------------------------------------
158
+ def encode(self, imgs, noise):
159
+ """VAE encode + latent_dist.sample() in batches of 4 (one noise draw per batch, as the original)."""
160
+ out = []
161
+ for i in range(0, len(imgs), 4):
162
+ mom = self.run("vae_encoder", image=imgs[i:i + 4])
163
+ mean, logvar = mom[:, :4], np.clip(mom[:, 4:], -30.0, 20.0)
164
+ out.append(mean + np.exp(0.5 * logvar) * noise(mean.shape))
165
+ return np.concatenate(out) * SCALING
166
+
167
+ def decode(self, lat):
168
+ return np.concatenate([self.run("vae_decoder", latents=lat[t:t + 1] / SCALING) for t in range(len(lat))])
169
+
170
+ def denoise(self, lat_in, t, cond):
171
+ r = self.run("brushnet", sample=lat_in, timestep=np.array([t], np.int64),
172
+ text=np.repeat(self.text, len(lat_in), 0), cond=cond)
173
+ return self.run("unet", sample=lat_in, timestep=np.array([t], np.int64), text=self.text,
174
+ **dict(zip(self.res, r)))
175
+
176
+ # -- the pipeline call --------------------------------------------------------------------------------------------
177
+ def sample(self, images, masks, latents, noise):
178
+ """StableDiffusionDiffuEraserPipeline.__call__ (guidance 0): masked images and masks -> BrushNet condition;
179
+ 2 TCD steps over windows of 22 frames (the shifted windows on odd steps), overlaps blended as the original does;
180
+ decoded frames."""
181
+ x = np.concatenate([to_unit(im) for im in images])
182
+ mk = np.concatenate([to_unit(np.repeat(m[..., None], 3, 2)) for m in masks])
183
+ omask = (mk.sum(1, keepdims=True) < 0).astype(np.float32) # 1 where not masked
184
+ cond_lat = self.encode(x, noise)
185
+ h, w = latents.shape[-2:]
186
+ cond = np.concatenate([cond_lat, omask[:, :, ::omask.shape[2] // h, ::omask.shape[3] // w][:, :, :h, :w]], 1)
187
+ cl, cs = contexts(len(images), NFRAMES // 4, NFRAMES)
188
+ lat = latents.copy()
189
+ for i, t in enumerate(TIMESTEPS):
190
+ count = np.zeros(len(lat)); value = np.zeros_like(lat)
191
+ for j, ctx in enumerate(cs if i % 2 == 1 else cl):
192
+ lj = tcd_step(self.denoise(lat[ctx], t, cond[ctx]), t, lat[ctx])
193
+ count[ctx] += 1
194
+ if j == 0:
195
+ value[ctx] += lj
196
+ else: # the original's blend: weights indexed by position in the window (kept as is)
197
+ over = [k for k, c in enumerate(count[ctx]) if c > 1]
198
+ r_next = np.linspace(0, 1, len(over) + 2)[1:-1]
199
+ r_pre = 1 - r_next
200
+ io = None
201
+ for io in over:
202
+ value[ctx[io]] = value[ctx[io]] * r_pre[io] + lj[io] * r_next[io]
203
+ value[ctx[io:NFRAMES]] = lj[io:NFRAMES]
204
+ lat = value
205
+ return to_uint8(self.decode(lat)), lat
206
+
207
+ def __call__(self, frames, masks, priors, max_size=960, dilate=8, seed=None, noise=None):
208
+ """frames, masks, priors: lists of uint8 RGB arrays (masks: white = remove). `noise(shape)` supplies the
209
+ Gaussian draws in the original's order (noise_pre, then the VAE samples); default numpy's generator."""
210
+ from PIL import Image
211
+ if noise is None:
212
+ rng = np.random.default_rng(seed)
213
+ noise = lambda shape: rng.standard_normal(shape).astype(np.float32)
214
+ size, resize = target_size(frames[0].shape[1], frames[0].shape[0], max_size)
215
+ fr = [np.asarray(Image.fromarray(f).resize(size)) if resize else np.asarray(f) for f in frames]
216
+ n = min(len(fr), len(masks), len(priors))
217
+ if n < NFRAMES:
218
+ raise ValueError("needs at least 22 frames")
219
+ fr = fr[:n]
220
+ ms = [process_mask(m, size, dilate) for m in masks[:n]]
221
+ masked = [(f * (1 - (m[..., None].astype(np.float32) / 255))).astype(np.uint8) for f, m in zip(fr, ms)]
222
+ pr = [np.asarray(Image.fromarray(p).resize(size)) if (p.shape[1], p.shape[0]) != size else np.asarray(p)
223
+ for p in priors[:n]]
224
+ W, H = size
225
+ noise_pre = noise((NFRAMES, 4, H // 8, W // 8))
226
+ noise_all = np.tile(noise_pre, (int(np.ceil(n / NFRAMES)), 1, 1, 1))[:n]
227
+ lat = self.encode(np.concatenate([to_unit(p) for p in pr]), noise)
228
+ ms_ori, fr_ori = list(ms), list(fr)
229
+ if n > NFRAMES * 2: # pre-inference on 22 frames spread over the video
230
+ step = n / NFRAMES
231
+ sidx = [int(i * step) for i in range(NFRAMES)][:22]
232
+ out, lat_pre = self.sample([masked[i] for i in sidx], [ms[i] for i in sidx],
233
+ ALPHA0 * lat[sidx] + SIGMA0 * noise_pre, noise)
234
+ black = np.zeros_like(ms[0])
235
+ for k, i in enumerate(sidx):
236
+ lat[i] = lat_pre[k]; ms[i] = black; masked[i] = out[k]; fr[i] = out[k]
237
+ out, _ = self.sample(masked, ms, ALPHA0 * lat + SIGMA0 * noise_all, noise)
238
+ comp = []
239
+ for i in range(n):
240
+ m = ms_ori[i]
241
+ b = (1 - (1 - m / 255.0) * (1 - blur21(m) / 255.0)) * 255
242
+ b = np.repeat(b.astype(np.uint8)[..., None], 3, 2).astype(np.float32) / 255.0
243
+ comp.append((out[i].astype(np.uint8) * b + fr_ori[i].astype(np.uint8) * (1 - b)).astype(np.uint8))
244
+ return comp
245
+
246
+
247
+ if __name__ == "__main__":
248
+ import argparse
249
+ from PIL import Image
250
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
251
+ ap.add_argument("frames"); ap.add_argument("masks"); ap.add_argument("priors"); ap.add_argument("out")
252
+ ap.add_argument("--max-size", type=int, default=960); ap.add_argument("--seed", type=int, default=42)
253
+ ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)); ap.add_argument("--cuda", action="store_true")
254
+ a = ap.parse_args()
255
+ load = lambda d: [np.asarray(Image.open(p).convert("RGB")) for p in sorted(Path(d).iterdir())]
256
+ res = DiffuEraser(a.dir, "cuda" if a.cuda else "cpu")(load(a.frames), load(a.masks), load(a.priors), a.max_size,
257
+ seed=a.seed)
258
+ Path(a.out).mkdir(parents=True, exist_ok=True)
259
+ for i, c in enumerate(res):
260
+ Image.fromarray(c).save(Path(a.out) / f"{i:05d}.png")
int8/text_embeds.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5aef4d79fd6bd90ab0baab7e1ee34158f96e6e32fba16ff1aacf6efcb2ccca03
3
+ size 236672
int8/unet.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f71b146c146ea6142de726fcd8e7e4b5d90fa0c18ce3455ab929d81ce13af513
3
+ size 1920869
int8/unet.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9cbbd1007f8e125a9d2e77281b080a92f82f8ae3d6022fe4ce230751d35e527
3
+ size 1973925120
int8/vae_decoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c4e4582fc9c3d1589fdbdfb9d1e7b3a12de38bda8cb780696f9d23b3ef31959
3
+ size 99091326
int8/vae_encoder.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58d65b351143aebcb3f46b2aee731dc0efa792a602cbb731fb728f8c417cf15f
3
+ size 68423492