jennyxue commited on
Commit
5faacc6
·
verified ·
1 Parent(s): c3df9f3

int8 build of SeedVR2

Browse files
.gitattributes CHANGED
@@ -36,3 +36,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
36
  fp16/dit.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  assets/seedvr_logo.png filter=lfs diff=lfs merge=lfs -text
38
  assets/teaser.png filter=lfs diff=lfs merge=lfs -text
 
 
36
  fp16/dit.onnx.data filter=lfs diff=lfs merge=lfs -text
37
  assets/seedvr_logo.png filter=lfs diff=lfs merge=lfs -text
38
  assets/teaser.png filter=lfs diff=lfs merge=lfs -text
39
+ int8/dit.onnx.data filter=lfs diff=lfs merge=lfs -text
int8/LICENSE.txt 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 2025 seed
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.
int8/dit.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e73874804e6062a81ea3a047ed74e671f27d54fee158408b04d803b0f6c95d21
3
+ size 1630270
int8/dit.onnx.data ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c36caaa979408e6b3ad6c956ba55e92d9120ae0c84ac62bc8537543d6e79790f
3
+ size 3555440304
int8/pipeline.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SeedVR2-3B (one-step diffusion video restoration / super-resolution) on ONNX Runtime: a numpy port of the
2
+ repository's projects/inference_seedvr2_3b.py (one step, cfg 1, the repository's positive text embedding; no colour
3
+ fix), around five graphs:
4
+
5
+ vae_enc_first.onnx / vae_enc_next.onnx one causal slice of the VAE encoder (5 frames, then 4 per slice):
6
+ x [1, 3, n, H, W] in [-1, 1] (+ the causal convs' memories) -> moments
7
+ [1, 32, t, H/8, W/8] (mean | log-variance) + the new memories
8
+ dit.onnx the NaDiT at t = 1000: vid [T, h, w, 33] (noise | latent | 1), and per
9
+ window method (0: 720pwin, 1: 720pswin) the windows' token indices,
10
+ key mask, inverse indices and RoPE tables -> v [T, h, w, 16]
11
+ vae_dec_first.onnx / vae_dec_next.onnx one causal slice of the VAE decoder (2 latents, then 1 per slice)
12
+ -> frames [1, 3, n, H, W]
13
+
14
+ python pipeline.py frames_dir out_dir [--cuda] [--seed 666] (frames all one size, sides multiples of 16)
15
+ """
16
+ import json
17
+ import math
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ from PIL import Image
23
+
24
+ SCALE = 0.9152 # VAE scaling factor (shift 0)
25
+ WINDOW = (4, 3, 3)
26
+ TXT_LEN = 58 # the length of the baked text embedding (pos_emb.pt)
27
+
28
+
29
+ def windows(size, num, shifted):
30
+ """make_720Pwindows_bysize / make_shifted_720Pwindows_bysize: [(t0, t1, h0, h1, w0, w1)] in the repository's
31
+ order."""
32
+ t, h, w = size
33
+ rt, rh, rw = num
34
+ scale = math.sqrt((45 * 80) / (h * w))
35
+ sh_, sw_ = round(h * scale), round(w * scale)
36
+ wh, ww = math.ceil(sh_ / rh), math.ceil(sw_ / rw)
37
+ wt = math.ceil(min(t, 30) / rt)
38
+ out = []
39
+ if not shifted:
40
+ nt, nh, nw = math.ceil(t / wt), math.ceil(h / wh), math.ceil(w / ww)
41
+ for iw in range(nw):
42
+ if min((iw + 1) * ww, w) <= iw * ww:
43
+ continue
44
+ for ih in range(nh):
45
+ if min((ih + 1) * wh, h) <= ih * wh:
46
+ continue
47
+ for it in range(nt):
48
+ if min((it + 1) * wt, t) <= it * wt:
49
+ continue
50
+ out.append((it * wt, min((it + 1) * wt, t), ih * wh, min((ih + 1) * wh, h),
51
+ iw * ww, min((iw + 1) * ww, w)))
52
+ return out
53
+ st, sh, sw = (0.5 if wt < t else 0, 0.5 if wh < h else 0, 0.5 if ww < w else 0)
54
+ nt, nh, nw = math.ceil((t - st) / wt), math.ceil((h - sh) / wh), math.ceil((w - sw) / ww)
55
+ nt, nh, nw = (nt + 1 if st > 0 else 1, nh + 1 if sh > 0 else 1, nw + 1 if sw > 0 else 1)
56
+ rng = lambda i, s_, n, size_: (max(int((i - s_) * n), 0), min(int((i - s_ + 1) * n), size_))
57
+ for iw in range(nw):
58
+ w0, w1 = rng(iw, sw, ww, w)
59
+ if w1 <= w0:
60
+ continue
61
+ for ih in range(nh):
62
+ h0, h1 = rng(ih, sh, wh, h)
63
+ if h1 <= h0:
64
+ continue
65
+ for it in range(nt):
66
+ t0, t1 = rng(it, st, wt, t)
67
+ if t1 <= t0:
68
+ continue
69
+ out.append((t0, t1, h0, h1, w0, w1))
70
+ return out
71
+
72
+
73
+ def window_inputs(T, h, w, shifted, txt_len=TXT_LEN):
74
+ """The DiT's inputs for one window method on a T x h x w token grid: idx [nw, S], mask [nw, S + l], inv [L],
75
+ cos / sin [nw, S, 63] (window-local positions, time offset by the text length, as NaMMRotaryEmbedding3d)."""
76
+ wins = windows((T, h, w), WINDOW, shifted)
77
+ S = max((t1 - t0) * (h1 - h0) * (w1 - w0) for t0, t1, h0, h1, w0, w1 in wins)
78
+ nw = len(wins)
79
+ idx = np.zeros((nw, S), np.int64)
80
+ mask = np.zeros((nw, S + txt_len), np.int32)
81
+ mask[:, S:] = 1
82
+ inv = np.zeros(T * h * w, np.int64)
83
+ pos = np.zeros((nw, S, 3), np.float32)
84
+ for k, (t0, t1, h0, h1, w0, w1) in enumerate(wins):
85
+ tt, hh, ww = np.meshgrid(np.arange(t0, t1), np.arange(h0, h1), np.arange(w0, w1), indexing="ij")
86
+ tok = (tt * h * w + hh * w + ww).reshape(-1)
87
+ n = len(tok)
88
+ idx[k, :n] = tok
89
+ mask[k, :n] = 1
90
+ inv[tok] = k * S + np.arange(n)
91
+ pos[k, :n, 0] = (tt - t0).reshape(-1) + txt_len
92
+ pos[k, :n, 1] = (hh - h0).reshape(-1)
93
+ pos[k, :n, 2] = (ww - w0).reshape(-1)
94
+ f = (1.0 / (np.float32(10000.0) ** (np.arange(0, 42, 2)[:21].astype(np.float32) / np.float32(42)))).astype(np.float32)
95
+ ang = np.concatenate([pos[..., a:a + 1] * f for a in range(3)], -1).astype(np.float32) # [nw, S, 63]
96
+ return idx, mask, inv, np.cos(ang).astype(np.float32), np.sin(ang).astype(np.float32)
97
+
98
+
99
+ def _phase(folder, provider, name, args):
100
+ """One phase in a fresh process (see SeedVR2(separate_processes=True))."""
101
+ p = SeedVR2(folder, provider, separate_processes=False)
102
+ return getattr(p, name)(*args)
103
+
104
+
105
+ class SeedVR2:
106
+ def __init__(self, folder, provider="cuda", keep_loaded=False, separate_processes=True):
107
+ """separate_processes: run the VAE encode, the DiT and the VAE decode each in a child process. On Windows,
108
+ where GPU memory counts toward the commit limit, several GB stay held in a process after a phase (CUDA /
109
+ cuDNN state), and the DiT session alone needs ~12 GB at 512 x 512 x 17 frames. The VAE decoder's sessions
110
+ search cuDNN's algorithms exhaustively: its heuristic picks for some sizes (384 x 384) need over 10 GB more."""
111
+ import onnxruntime as ort
112
+ self.provider = provider
113
+ self.separate = separate_processes
114
+ self.folder = Path(folder)
115
+ self.ort = ort
116
+ if provider != "cpu" and hasattr(ort, "preload_dlls"):
117
+ try:
118
+ ort.preload_dlls()
119
+ except Exception:
120
+ pass
121
+ so = ort.SessionOptions()
122
+ so.log_severity_level = 3
123
+ so.enable_mem_pattern = False
124
+ so.enable_cpu_mem_arena = False
125
+ self.so = so
126
+ self.cuda = provider != "cpu"
127
+ self.pv = ["CPUExecutionProvider"] if not self.cuda else [
128
+ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested", "cudnn_conv_algo_search": "HEURISTIC",
129
+ "cudnn_conv_use_max_workspace": "0"}), "CPUExecutionProvider"]
130
+ self.keep = keep_loaded
131
+ self.s, self.dt = {}, {}
132
+ self.ro = ort.RunOptions()
133
+ if self.cuda:
134
+ self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0")
135
+
136
+ def session(self, name):
137
+ if name not in self.s:
138
+ pv = self.pv
139
+ if self.cuda and name.startswith("vae_dec"): # cuDNN's heuristic / default picks for the decoder's 3-D
140
+ pv = [("CUDAExecutionProvider", {**pv[0][1], "cudnn_conv_algo_search": "EXHAUSTIVE"}), pv[1]]
141
+ s = self.ort.InferenceSession(str(self.folder / f"{name}.onnx"), self.so, providers=pv)
142
+ if self.cuda and "CUDAExecutionProvider" not in s.get_providers():
143
+ raise RuntimeError("the CUDA execution provider failed to load (CUDA 12 / cuDNN 9 needed)")
144
+ self.s[name] = s
145
+ self.dt[name] = {i.name: (np.float16 if i.type == "tensor(float16)" else np.int64 if i.type == "tensor(int64)"
146
+ else np.int32 if i.type == "tensor(int32)" else np.float32) for i in s.get_inputs()}
147
+ return self.s[name]
148
+
149
+ def release(self, *names):
150
+ if not self.keep:
151
+ for n in names:
152
+ self.s.pop(n, None)
153
+
154
+ def run(self, name, **feeds):
155
+ s = self.session(name)
156
+ feeds = {k: np.ascontiguousarray(v, self.dt[name][k]) for k, v in feeds.items()}
157
+ return s.run(None, feeds, self.ro)
158
+
159
+ # --- building blocks (a torch driver overrides these) ---
160
+ def vae_slice(self, part, first, x, mems):
161
+ out = self.run(f"vae_{part}_{'first' if first else 'next'}", x=x, **{f"mem{i}": m for i, m in enumerate(mems)})
162
+ return out[0], out[1:]
163
+
164
+ def dit(self, vid, win):
165
+ feeds = {"vid": vid}
166
+ for m, (idx, mask, inv, cos, sin) in enumerate(win):
167
+ feeds.update({f"idx{m}": idx, f"mask{m}": mask, f"inv{m}": inv, f"cos{m}": cos, f"sin{m}": sin})
168
+ return self.run("dit", **feeds)[0]
169
+
170
+ def phase(self, name, *args):
171
+ if not self.separate:
172
+ return getattr(self, name)(*args)
173
+ import multiprocessing as mp
174
+ with mp.get_context("spawn").Pool(1) as pool:
175
+ return pool.apply(_phase, (str(self.folder), self.provider, name, args))
176
+
177
+ def encode(self, x):
178
+ mom, mems = [], []
179
+ sl = [x[:, :, :5]] + [x[:, :, i:i + 4] for i in range(5, x.shape[2], 4)]
180
+ for k, xs in enumerate(sl):
181
+ m_, mems = self.vae_slice("enc", k == 0, xs, mems)
182
+ mom.append(np.asarray(m_, np.float32))
183
+ self.release("vae_enc_first", "vae_enc_next")
184
+ return np.concatenate(mom, 2)
185
+
186
+ def dit_phase(self, vid):
187
+ t, h, w, _ = vid.shape
188
+ win = [window_inputs(t, h // 2, w // 2, False), window_inputs(t, h // 2, w // 2, True)]
189
+ v = np.asarray(self.dit(vid, win), np.float32)
190
+ self.release("dit")
191
+ return v
192
+
193
+ def decode(self, z):
194
+ out, mems = [], []
195
+ sl = [z[:, :, :2]] + [z[:, :, i:i + 1] for i in range(2, z.shape[2])]
196
+ for k, zs in enumerate(sl):
197
+ y, mems = self.vae_slice("dec", k == 0, zs, mems)
198
+ out.append(np.asarray(y, np.float32))
199
+ self.release("vae_dec_first", "vae_dec_next")
200
+ return np.concatenate(out, 2)
201
+
202
+ def __call__(self, frames, seed=666, draws=None):
203
+ """frames: list of uint8 RGB arrays, all the same size (sides multiples of 16: crop or resize them first; the
204
+ repository resizes to an area and centre-crops to multiples of 16). draws: the random draws in order (the
205
+ VAE posterior noise [1, 16, t, h, w], the initial noise [t, h, w, 16], the condition-augmentation noise, unused
206
+ at noise scale 0); default numpy draws from seed. Returns len(frames) uint8 frames."""
207
+ x = np.stack([np.asarray(f, np.float32) for f in frames]) / 255.0 # T H W C
208
+ n0 = len(x)
209
+ x = (x * 2 - 1).transpose(3, 0, 1, 2)[None] # 1 C T H W in [-1, 1]
210
+ T = x.shape[2]
211
+ if T > 1 and (T - 1) % 4: # cut_videos: pad to 4n + 1
212
+ x = np.concatenate([x, np.repeat(x[:, :, -1:], 4 - (T - 1) % 4, 2)], 2)
213
+ rng = np.random.default_rng(seed)
214
+ it = iter(draws) if draws is not None else None
215
+ draw = (lambda shape: np.asarray(next(it), np.float32).reshape(shape)) if it else \
216
+ (lambda shape: rng.standard_normal(shape).astype(np.float32))
217
+ # 1. VAE encode, causal slices of 4 frames (the first with frame 0 in front)
218
+ mom = self.phase("encode", x)
219
+ mean, logvar = mom[:, :16], np.clip(mom[:, 16:], -30.0, 20.0)
220
+ lat = mean + np.exp(0.5 * logvar) * draw(mean.shape)
221
+ lat = lat[0].transpose(1, 2, 3, 0) * SCALE # t h w c
222
+ # 2. one DiT step from noise, conditioned on the latent
223
+ t, h, w, _ = lat.shape
224
+ noise = draw(lat.shape)
225
+ draw(lat.shape) # the augmentation noise (scale 0: no effect)
226
+ vid = np.concatenate([noise, lat, np.ones((t, h, w, 1), np.float32)], -1)
227
+ v = self.phase("dit_phase", vid)
228
+ x0 = noise - np.asarray(v, np.float32)
229
+ # 3. VAE decode, causal slices of 1 latent (the first with latent 0 in front)
230
+ y = self.phase("decode", (x0 / SCALE).transpose(3, 0, 1, 2)[None])[0][:, :n0] # C T H W
231
+ y = np.clip(y, -1, 1) * 0.5 + 0.5
232
+ return list(np.round(y.transpose(1, 2, 3, 0) * 255).astype(np.uint8))
233
+
234
+
235
+ if __name__ == "__main__":
236
+ import argparse
237
+ ap = argparse.ArgumentParser()
238
+ ap.add_argument("frames")
239
+ ap.add_argument("out")
240
+ ap.add_argument("--cuda", action="store_true")
241
+ ap.add_argument("--seed", type=int, default=666)
242
+ a = ap.parse_args()
243
+ files = sorted(p for p in Path(a.frames).iterdir() if p.suffix.lower() in (".png", ".jpg", ".jpeg"))
244
+ p = SeedVR2(Path(__file__).resolve().parent, "cuda" if a.cuda else "cpu")
245
+ out = p([np.asarray(Image.open(f).convert("RGB")) for f in files], seed=a.seed)
246
+ Path(a.out).mkdir(parents=True, exist_ok=True)
247
+ for i, fr in enumerate(out):
248
+ Image.fromarray(fr).save(Path(a.out) / f"{i:05d}.png")
249
+ print(len(out), "frames ->", a.out)
int8/vae_dec_first.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8250314ef04dcae8adf28b5209baa254ba478537257206cce5f6670cd7eb05a7
3
+ size 301715063
int8/vae_dec_next.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e300dd92f6f72a1bd2857fd3bbe04c5e31b71a93b88edd0ed390028baf46ff73
3
+ size 301538837
int8/vae_enc_first.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6a9041ed8a4eacf403229894704327dab9275218ac933dcd54cd44cb0db6dbe
3
+ size 200468788
int8/vae_enc_next.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcffa79fd16db2acc4953c043722f26defaa84723865a64a0a9cfe3af64f45d2
3
+ size 200339836