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