Spaces:
Runtime error
Runtime error
Update app.py
#2
by
chavinlo
- opened
- .gitattributes +0 -2
- README.md +3 -1
- app.py +148 -230
- example.gif → example.webp +2 -2
- examples/example_01_barbarian/input.png +0 -3
- examples/example_01_barbarian/output.gif +0 -3
- examples/example_01_barbarian/params.json +0 -14
- examples/example_02_zombies/output.gif +0 -3
- examples/example_02_zombies/params.json +0 -14
- examples/example_03_astronaut/output.gif +0 -3
- examples/example_03_astronaut/params.json +0 -14
- examples/example_04_furry_moster/output.gif +0 -3
- examples/example_04_furry_moster/params.json +0 -14
- examples/example_05_people/input.png +0 -3
- examples/example_05_people/output.gif +0 -3
- examples/example_05_people/params.json +0 -14
- examples/example_06_sophie/output.gif +0 -3
- examples/example_06_sophie/params.json +0 -14
- makeavid_sd/inference.py +58 -94
- requirements.txt +1 -1
.gitattributes
CHANGED
@@ -1,6 +1,4 @@
|
|
1 |
*.webp filter=lfs diff=lfs merge=lfs -text
|
2 |
-
*.gif filter=lfs diff=lfs merge=lfs -text
|
3 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
4 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
5 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
6 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
|
|
1 |
*.webp filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
2 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
3 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
4 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -12,10 +12,12 @@ library_name: diffusers
|
|
12 |
pipeline_tag: text-to-video
|
13 |
datasets:
|
14 |
- TempoFunk/tempofunk-sdance
|
15 |
-
- TempoFunk/
|
16 |
models:
|
17 |
- TempoFunk/makeavid-sd-jax
|
18 |
- runwayml/stable-diffusion-v1-5
|
19 |
tags:
|
20 |
- jax-diffusers-event
|
21 |
---
|
|
|
|
|
|
12 |
pipeline_tag: text-to-video
|
13 |
datasets:
|
14 |
- TempoFunk/tempofunk-sdance
|
15 |
+
- TempoFunk/tempofunk-m
|
16 |
models:
|
17 |
- TempoFunk/makeavid-sd-jax
|
18 |
- runwayml/stable-diffusion-v1-5
|
19 |
tags:
|
20 |
- jax-diffusers-event
|
21 |
---
|
22 |
+
|
23 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
|
2 |
import os
|
3 |
-
import json
|
4 |
from io import BytesIO
|
5 |
import base64
|
6 |
from functools import partial
|
@@ -8,88 +7,65 @@ from functools import partial
|
|
8 |
from PIL import Image, ImageOps
|
9 |
import gradio as gr
|
10 |
|
11 |
-
from makeavid_sd.inference import
|
12 |
-
InferenceUNetPseudo3D,
|
13 |
-
jnp,
|
14 |
-
SCHEDULERS
|
15 |
-
)
|
16 |
|
17 |
print(os.environ.get('XLA_PYTHON_CLIENT_PREALLOCATE', 'NotSet'))
|
18 |
print(os.environ.get('XLA_PYTHON_CLIENT_ALLOCATOR', 'NotSet'))
|
19 |
|
|
|
|
|
20 |
_seen_compilations = set()
|
21 |
|
22 |
_model = InferenceUNetPseudo3D(
|
23 |
model_path = 'TempoFunk/makeavid-sd-jax',
|
|
|
24 |
dtype = jnp.float16,
|
25 |
hf_auth_token = os.environ.get('HUGGING_FACE_HUB_TOKEN', None)
|
26 |
)
|
27 |
|
28 |
-
import datetime
|
29 |
-
print(datetime.datetime.now(datetime.timezone.utc).isoformat())
|
30 |
-
|
31 |
if _model.failed != False:
|
32 |
trace = f'```{_model.failed}```'
|
33 |
with gr.Blocks(title = 'Make-A-Video Stable Diffusion JAX', analytics_enabled = False) as demo:
|
34 |
exception = gr.Markdown(trace)
|
35 |
-
demo.launch()
|
36 |
-
|
37 |
-
_examples = []
|
38 |
-
_expath = 'examples'
|
39 |
-
for x in sorted(os.listdir(_expath)):
|
40 |
-
with open(os.path.join(_expath, x, 'params.json'), 'r') as f:
|
41 |
-
ex = json.load(f)
|
42 |
-
ex['image_input'] = None
|
43 |
-
if os.path.isfile(os.path.join(_expath, x, 'input.png')):
|
44 |
-
ex['image_input'] = os.path.join(_expath, x, 'input.png')
|
45 |
-
ex['image_output'] = os.path.join(_expath, x, 'output.gif')
|
46 |
-
_examples.append(ex)
|
47 |
|
48 |
-
|
49 |
-
_output_formats = (
|
50 |
-
'webp', 'gif'
|
51 |
-
)
|
52 |
|
53 |
# gradio is illiterate. type hints make it go poopoo in pantsu.
|
54 |
def generate(
|
55 |
prompt = 'An elderly man having a great time in the park.',
|
56 |
neg_prompt = '',
|
57 |
-
|
58 |
inference_steps = 20,
|
59 |
-
cfg =
|
60 |
-
cfg_image = 9.0,
|
61 |
seed = 0,
|
62 |
-
fps =
|
63 |
num_frames = 24,
|
64 |
height = 512,
|
65 |
-
width = 512
|
66 |
-
scheduler_type = 'dpm',
|
67 |
-
output_format = 'gif'
|
68 |
) -> str:
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
height = (height // 64) * 64
|
74 |
-
width = (width // 64) * 64
|
75 |
-
cfg = max(cfg, 1.0)
|
76 |
-
cfg_image = max(cfg_image, 1.0)
|
77 |
-
fps = min(1000, max(1, int(fps)))
|
78 |
-
seed = min(2**32-2, int(seed))
|
79 |
if seed < 0:
|
80 |
seed = -seed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
if hint_image is not None:
|
82 |
if hint_image.mode != 'RGB':
|
83 |
hint_image = hint_image.convert('RGB')
|
84 |
if hint_image.size != (width, height):
|
85 |
hint_image = ImageOps.fit(hint_image, (width, height), method = Image.Resampling.LANCZOS)
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
output_format = 'gif'
|
92 |
-
mask_image = None
|
93 |
images = _model.generate(
|
94 |
prompt = [prompt] * _model.device_count,
|
95 |
neg_prompt = neg_prompt,
|
@@ -97,44 +73,56 @@ def generate(
|
|
97 |
mask_image = mask_image,
|
98 |
inference_steps = inference_steps,
|
99 |
cfg = cfg,
|
100 |
-
cfg_image = cfg_image,
|
101 |
height = height,
|
102 |
width = width,
|
103 |
num_frames = num_frames,
|
104 |
-
seed = seed
|
105 |
-
scheduler_type = scheduler_type
|
106 |
)
|
107 |
_seen_compilations.add((hint_image is None, inference_steps, height, width, num_frames))
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
last_data = f'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode()
|
123 |
-
with BytesIO() as buffer:
|
124 |
-
images[0].save(buffer, format ='png', optimize = True)
|
125 |
-
first_data = f'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode()
|
126 |
-
return data, last_data, first_data
|
127 |
|
128 |
-
def check_if_compiled(
|
129 |
height = int(height)
|
130 |
width = int(width)
|
131 |
-
|
132 |
-
|
133 |
-
width = (width // 64) * 64
|
134 |
-
if (hint_image is None, inference_steps, height, width, num_frames, scheduler_type) in _seen_compilations:
|
135 |
return ''
|
136 |
else:
|
137 |
-
return message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
|
139 |
with gr.Blocks(title = 'Make-A-Video Stable Diffusion JAX', analytics_enabled = False) as demo:
|
140 |
variant = 'panel'
|
@@ -143,67 +131,60 @@ with gr.Blocks(title = 'Make-A-Video Stable Diffusion JAX', analytics_enabled =
|
|
143 |
intro1 = gr.Markdown("""
|
144 |
# Make-A-Video Stable Diffusion JAX
|
145 |
|
146 |
-
We have extended a pretrained
|
147 |
-
We
|
148 |
-
|
149 |
|
150 |
-
The temporal
|
151 |
-
|
152 |
-
Temporal attention is purely self attention and also separately attends to time.
|
153 |
|
154 |
Only the new temporal layers have been fine tuned on a dataset of videos themed around dance.
|
155 |
-
The model has been trained for
|
156 |
|
157 |
-
|
158 |
-
Datasets: [TempoFunk/tempofunk-sdance](https://huggingface.co/datasets/TempoFunk/tempofunk-sdance), [TempoFunk/small](https://huggingface.co/datasets/TempoFunk/small)
|
159 |
|
160 |
-
Model implementation and training code can be found at
|
161 |
""")
|
162 |
with gr.Column():
|
163 |
intro3 = gr.Markdown("""
|
164 |
**Please be patient. The model might have to compile with current parameters.**
|
165 |
|
166 |
This can take up to 5 minutes on the first run, and 2-3 minutes on later runs.
|
167 |
-
The compilation will be cached and
|
168 |
will be much faster.
|
169 |
|
170 |
Changes to the following parameters require the model to compile
|
171 |
- Number of frames
|
172 |
- Width & Height
|
173 |
-
-
|
174 |
- Input image vs. no input image
|
175 |
-
- Noise scheduler type
|
176 |
-
|
177 |
-
If you encounter any issues, please report them here: [Space discussions](https://huggingface.co/spaces/TempoFunk/makeavid-sd-jax/discussions) (or DM [@lopho](https://twitter.com/lopho))
|
178 |
-
|
179 |
-
<small>Leave a ❤️ like if you like. Consider it a dopamine donation at no cost.</small>
|
180 |
""")
|
181 |
|
182 |
with gr.Row(variant = variant):
|
183 |
-
with gr.Column():
|
184 |
with gr.Row():
|
185 |
#cancel_button = gr.Button(value = 'Cancel')
|
186 |
submit_button = gr.Button(value = 'Make A Video', variant = 'primary')
|
187 |
prompt_input = gr.Textbox(
|
188 |
label = 'Prompt',
|
189 |
-
value = 'They are dancing in the club
|
190 |
interactive = True
|
191 |
)
|
192 |
neg_prompt_input = gr.Textbox(
|
193 |
label = 'Negative prompt (optional)',
|
194 |
-
value = '
|
195 |
interactive = True
|
196 |
)
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
interactive = True
|
204 |
)
|
205 |
-
|
206 |
-
label = 'Guidance scale
|
207 |
minimum = 1.0,
|
208 |
maximum = 20.0,
|
209 |
step = 0.1,
|
@@ -217,152 +198,89 @@ with gr.Blocks(title = 'Make-A-Video Stable Diffusion JAX', analytics_enabled =
|
|
217 |
precision = 0
|
218 |
)
|
219 |
image_input = gr.Image(
|
220 |
-
label = '
|
221 |
interactive = True,
|
222 |
image_mode = 'RGB',
|
223 |
type = 'pil',
|
224 |
optional = True,
|
225 |
-
source = 'upload'
|
226 |
-
|
227 |
-
inference_steps_input = gr.Slider(
|
228 |
-
label = 'Steps',
|
229 |
-
minimum = 2,
|
230 |
-
maximum = 60,
|
231 |
-
value = 20,
|
232 |
-
step = 1,
|
233 |
-
interactive = True
|
234 |
)
|
235 |
num_frames_input = gr.Slider(
|
236 |
label = 'Number of frames to generate',
|
237 |
-
minimum =
|
238 |
maximum = 24,
|
239 |
step = 1,
|
240 |
-
value = 24
|
241 |
-
interactive = True
|
242 |
)
|
243 |
width_input = gr.Slider(
|
244 |
label = 'Width',
|
245 |
-
minimum =
|
246 |
-
maximum =
|
247 |
-
step =
|
248 |
-
value =
|
249 |
-
interactive = True
|
250 |
)
|
251 |
height_input = gr.Slider(
|
252 |
label = 'Height',
|
253 |
-
minimum =
|
254 |
-
maximum =
|
255 |
-
step =
|
256 |
-
value =
|
257 |
-
interactive = True
|
258 |
)
|
259 |
-
|
260 |
-
label = '
|
261 |
-
|
262 |
-
|
263 |
-
|
|
|
264 |
)
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
maximum = 1000,
|
270 |
-
step = 1,
|
271 |
-
value = 12,
|
272 |
-
interactive = True
|
273 |
-
)
|
274 |
-
output_format = gr.Dropdown(
|
275 |
-
label = 'Output format',
|
276 |
-
choices = _output_formats,
|
277 |
-
value = 'gif',
|
278 |
-
interactive = True
|
279 |
-
)
|
280 |
-
with gr.Column():
|
281 |
-
#will_trigger = gr.Markdown('')
|
282 |
-
patience = gr.Markdown('**Please be patient. The model might have to compile with current parameters.**')
|
283 |
image_output = gr.Image(
|
284 |
label = 'Output',
|
285 |
-
value = 'example.
|
286 |
interactive = False
|
287 |
)
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
cfg_input,
|
324 |
-
cfg_image_input,
|
325 |
-
seed_input,
|
326 |
-
fps_input,
|
327 |
-
inference_steps_input,
|
328 |
-
scheduler_input,
|
329 |
-
num_frames_input,
|
330 |
-
height_input,
|
331 |
-
width_input,
|
332 |
-
output_format
|
333 |
-
],
|
334 |
-
postprocess = False
|
335 |
-
)
|
336 |
-
#trigger_inputs = [ image_input, inference_steps_input, height_input, width_input, num_frames_input, scheduler_input ]
|
337 |
-
#trigger_check_fun = partial(check_if_compiled, message = 'Current parameters need compilation.')
|
338 |
-
#height_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
339 |
-
#width_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
340 |
-
#num_frames_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
341 |
-
#image_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
342 |
-
#inference_steps_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
343 |
-
#scheduler_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
344 |
-
submit_button.click(
|
345 |
-
fn = generate,
|
346 |
-
inputs = [
|
347 |
-
prompt_input,
|
348 |
-
neg_prompt_input,
|
349 |
-
image_input,
|
350 |
-
inference_steps_input,
|
351 |
-
cfg_input,
|
352 |
-
cfg_image_input,
|
353 |
-
seed_input,
|
354 |
-
fps_input,
|
355 |
-
num_frames_input,
|
356 |
-
height_input,
|
357 |
-
width_input,
|
358 |
-
scheduler_input,
|
359 |
-
output_format
|
360 |
-
],
|
361 |
-
outputs = [ image_output, last_frame_output, first_frame_output ],
|
362 |
-
postprocess = False
|
363 |
)
|
364 |
#cancel_button.click(fn = lambda: None, cancels = ev)
|
365 |
|
366 |
-
demo.queue(concurrency_count = 1, max_size =
|
367 |
-
demo.launch(
|
368 |
|
|
|
1 |
|
2 |
import os
|
|
|
3 |
from io import BytesIO
|
4 |
import base64
|
5 |
from functools import partial
|
|
|
7 |
from PIL import Image, ImageOps
|
8 |
import gradio as gr
|
9 |
|
10 |
+
from makeavid_sd.inference import InferenceUNetPseudo3D, FlaxDPMSolverMultistepScheduler, jnp
|
|
|
|
|
|
|
|
|
11 |
|
12 |
print(os.environ.get('XLA_PYTHON_CLIENT_PREALLOCATE', 'NotSet'))
|
13 |
print(os.environ.get('XLA_PYTHON_CLIENT_ALLOCATOR', 'NotSet'))
|
14 |
|
15 |
+
_preheat: bool = False
|
16 |
+
|
17 |
_seen_compilations = set()
|
18 |
|
19 |
_model = InferenceUNetPseudo3D(
|
20 |
model_path = 'TempoFunk/makeavid-sd-jax',
|
21 |
+
scheduler_cls = FlaxDPMSolverMultistepScheduler,
|
22 |
dtype = jnp.float16,
|
23 |
hf_auth_token = os.environ.get('HUGGING_FACE_HUB_TOKEN', None)
|
24 |
)
|
25 |
|
|
|
|
|
|
|
26 |
if _model.failed != False:
|
27 |
trace = f'```{_model.failed}```'
|
28 |
with gr.Blocks(title = 'Make-A-Video Stable Diffusion JAX', analytics_enabled = False) as demo:
|
29 |
exception = gr.Markdown(trace)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
+
demo.launch()
|
|
|
|
|
|
|
32 |
|
33 |
# gradio is illiterate. type hints make it go poopoo in pantsu.
|
34 |
def generate(
|
35 |
prompt = 'An elderly man having a great time in the park.',
|
36 |
neg_prompt = '',
|
37 |
+
image = { 'image': None, 'mask': None },
|
38 |
inference_steps = 20,
|
39 |
+
cfg = 12.0,
|
|
|
40 |
seed = 0,
|
41 |
+
fps = 24,
|
42 |
num_frames = 24,
|
43 |
height = 512,
|
44 |
+
width = 512
|
|
|
|
|
45 |
) -> str:
|
46 |
+
height = int((height//32)*32)
|
47 |
+
width = int((width//32)*32)
|
48 |
+
num_frames = int(num_frames)
|
49 |
+
seed = int(seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
if seed < 0:
|
51 |
seed = -seed
|
52 |
+
inference_steps = int(inference_steps)
|
53 |
+
if image is not None:
|
54 |
+
hint_image = image['image']
|
55 |
+
mask_image = image['mask']
|
56 |
+
else:
|
57 |
+
hint_image = None
|
58 |
+
mask_image = None
|
59 |
if hint_image is not None:
|
60 |
if hint_image.mode != 'RGB':
|
61 |
hint_image = hint_image.convert('RGB')
|
62 |
if hint_image.size != (width, height):
|
63 |
hint_image = ImageOps.fit(hint_image, (width, height), method = Image.Resampling.LANCZOS)
|
64 |
+
if mask_image is not None:
|
65 |
+
if mask_image.mode != 'L':
|
66 |
+
mask_image = mask_image.convert('L')
|
67 |
+
if mask_image.size != (width, height):
|
68 |
+
mask_image = ImageOps.fit(mask_image, (width, height), method = Image.Resampling.LANCZOS)
|
|
|
|
|
69 |
images = _model.generate(
|
70 |
prompt = [prompt] * _model.device_count,
|
71 |
neg_prompt = neg_prompt,
|
|
|
73 |
mask_image = mask_image,
|
74 |
inference_steps = inference_steps,
|
75 |
cfg = cfg,
|
|
|
76 |
height = height,
|
77 |
width = width,
|
78 |
num_frames = num_frames,
|
79 |
+
seed = seed
|
|
|
80 |
)
|
81 |
_seen_compilations.add((hint_image is None, inference_steps, height, width, num_frames))
|
82 |
+
buffer = BytesIO()
|
83 |
+
images[0].save(
|
84 |
+
buffer,
|
85 |
+
format = 'webp',
|
86 |
+
save_all = True,
|
87 |
+
append_images = images[1:],
|
88 |
+
loop = 0,
|
89 |
+
duration = round(1000 / fps),
|
90 |
+
allow_mixed = True
|
91 |
+
)
|
92 |
+
data = base64.b64encode(buffer.getvalue()).decode()
|
93 |
+
data = 'data:image/webp;base64,' + data
|
94 |
+
buffer.close()
|
95 |
+
return data
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
+
def check_if_compiled(image, inference_steps, height, width, num_frames, message):
|
98 |
height = int(height)
|
99 |
width = int(width)
|
100 |
+
hint_image = None if image is None else image['image']
|
101 |
+
if (hint_image is None, inference_steps, height, width, num_frames) in _seen_compilations:
|
|
|
|
|
102 |
return ''
|
103 |
else:
|
104 |
+
return f"""{message}"""
|
105 |
+
|
106 |
+
if _preheat:
|
107 |
+
print('\npreheating the oven')
|
108 |
+
generate(
|
109 |
+
prompt = 'preheating the oven',
|
110 |
+
neg_prompt = '',
|
111 |
+
image = { 'image': None, 'mask': None },
|
112 |
+
inference_steps = 20,
|
113 |
+
cfg = 12.0,
|
114 |
+
seed = 0
|
115 |
+
)
|
116 |
+
print('Entertaining the guests with sailor songs played on an old piano.')
|
117 |
+
dada = generate(
|
118 |
+
prompt = 'Entertaining the guests with sailor songs played on an old harmonium.',
|
119 |
+
neg_prompt = '',
|
120 |
+
image = { 'image': Image.new('RGB', size = (512, 512), color = (0, 0, 0)), 'mask': None },
|
121 |
+
inference_steps = 20,
|
122 |
+
cfg = 12.0,
|
123 |
+
seed = 0
|
124 |
+
)
|
125 |
+
print('dinner is ready\n')
|
126 |
|
127 |
with gr.Blocks(title = 'Make-A-Video Stable Diffusion JAX', analytics_enabled = False) as demo:
|
128 |
variant = 'panel'
|
|
|
131 |
intro1 = gr.Markdown("""
|
132 |
# Make-A-Video Stable Diffusion JAX
|
133 |
|
134 |
+
We have extended a pretrained LDM inpainting image generation model with temporal convolutions and attention.
|
135 |
+
We take advantage of the extra 5 input channels of the inpaint model to guide the video generation with a hint image and mask.
|
136 |
+
The hint image can be given by the user, otherwise it is generated by an generative image model.
|
137 |
|
138 |
+
The temporal convolution and attention is a port of [Make-A-Video Pytorch](https://github.com/lucidrains/make-a-video-pytorch/blob/main/make_a_video_pytorch) to FLAX.
|
139 |
+
It is a pseudo 3D convolution that seperately convolves accross the spatial dimension in 2D and over the temporal dimension in 1D.
|
140 |
+
Temporal attention is purely self attention and also separately attends to time and space.
|
141 |
|
142 |
Only the new temporal layers have been fine tuned on a dataset of videos themed around dance.
|
143 |
+
The model has been trained for 60 epochs on a dataset of 10,000 Videos with 120 frames each, randomly selecting a 24 frame range from each sample.
|
144 |
|
145 |
+
See model and dataset links in the metadata.
|
|
|
146 |
|
147 |
+
Model implementation and training code can be found at [https://github.com/lopho/makeavid-sd-tpu](https://github.com/lopho/makeavid-sd-tpu)
|
148 |
""")
|
149 |
with gr.Column():
|
150 |
intro3 = gr.Markdown("""
|
151 |
**Please be patient. The model might have to compile with current parameters.**
|
152 |
|
153 |
This can take up to 5 minutes on the first run, and 2-3 minutes on later runs.
|
154 |
+
The compilation will be cached and consecutive runs with the same parameters
|
155 |
will be much faster.
|
156 |
|
157 |
Changes to the following parameters require the model to compile
|
158 |
- Number of frames
|
159 |
- Width & Height
|
160 |
+
- Steps
|
161 |
- Input image vs. no input image
|
|
|
|
|
|
|
|
|
|
|
162 |
""")
|
163 |
|
164 |
with gr.Row(variant = variant):
|
165 |
+
with gr.Column(variant = variant):
|
166 |
with gr.Row():
|
167 |
#cancel_button = gr.Button(value = 'Cancel')
|
168 |
submit_button = gr.Button(value = 'Make A Video', variant = 'primary')
|
169 |
prompt_input = gr.Textbox(
|
170 |
label = 'Prompt',
|
171 |
+
value = 'They are dancing in the club while sweat drips from the ceiling.',
|
172 |
interactive = True
|
173 |
)
|
174 |
neg_prompt_input = gr.Textbox(
|
175 |
label = 'Negative prompt (optional)',
|
176 |
+
value = '',
|
177 |
interactive = True
|
178 |
)
|
179 |
+
inference_steps_input = gr.Slider(
|
180 |
+
label = 'Steps',
|
181 |
+
minimum = 2,
|
182 |
+
maximum = 100,
|
183 |
+
value = 20,
|
184 |
+
step = 1
|
|
|
185 |
)
|
186 |
+
cfg_input = gr.Slider(
|
187 |
+
label = 'Guidance scale',
|
188 |
minimum = 1.0,
|
189 |
maximum = 20.0,
|
190 |
step = 0.1,
|
|
|
198 |
precision = 0
|
199 |
)
|
200 |
image_input = gr.Image(
|
201 |
+
label = 'Input image (optional)',
|
202 |
interactive = True,
|
203 |
image_mode = 'RGB',
|
204 |
type = 'pil',
|
205 |
optional = True,
|
206 |
+
source = 'upload',
|
207 |
+
tool = 'sketch'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
)
|
209 |
num_frames_input = gr.Slider(
|
210 |
label = 'Number of frames to generate',
|
211 |
+
minimum = 1,
|
212 |
maximum = 24,
|
213 |
step = 1,
|
214 |
+
value = 24
|
|
|
215 |
)
|
216 |
width_input = gr.Slider(
|
217 |
label = 'Width',
|
218 |
+
minimum = 64,
|
219 |
+
maximum = 512,
|
220 |
+
step = 32,
|
221 |
+
value = 448
|
|
|
222 |
)
|
223 |
height_input = gr.Slider(
|
224 |
label = 'Height',
|
225 |
+
minimum = 64,
|
226 |
+
maximum = 512,
|
227 |
+
step = 32,
|
228 |
+
value = 448
|
|
|
229 |
)
|
230 |
+
fps_input = gr.Slider(
|
231 |
+
label = 'Output FPS',
|
232 |
+
minimum = 1,
|
233 |
+
maximum = 1000,
|
234 |
+
step = 1,
|
235 |
+
value = 12
|
236 |
)
|
237 |
+
with gr.Column(variant = variant):
|
238 |
+
#no_gpu = gr.Markdown('**Until a GPU is assigned expect extremely long runtimes up to 1h+**')
|
239 |
+
will_trigger = gr.Markdown('')
|
240 |
+
patience = gr.Markdown('')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
241 |
image_output = gr.Image(
|
242 |
label = 'Output',
|
243 |
+
value = 'example.webp',
|
244 |
interactive = False
|
245 |
)
|
246 |
+
trigger_inputs = [ image_input, inference_steps_input, height_input, width_input, num_frames_input ]
|
247 |
+
trigger_check_fun = partial(check_if_compiled, message = 'Current parameters will trigger compilation.')
|
248 |
+
height_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
249 |
+
width_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
250 |
+
num_frames_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
251 |
+
image_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
252 |
+
inference_steps_input.change(fn = trigger_check_fun, inputs = trigger_inputs, outputs = will_trigger)
|
253 |
+
will_trigger.value = trigger_check_fun(image_input.value, inference_steps_input.value, height_input.value, width_input.value, num_frames_input.value)
|
254 |
+
ev = submit_button.click(
|
255 |
+
fn = partial(
|
256 |
+
check_if_compiled,
|
257 |
+
message = 'Please be patient. The model has to be compiled with current parameters.'
|
258 |
+
),
|
259 |
+
inputs = trigger_inputs,
|
260 |
+
outputs = patience
|
261 |
+
).then(
|
262 |
+
fn = generate,
|
263 |
+
inputs = [
|
264 |
+
prompt_input,
|
265 |
+
neg_prompt_input,
|
266 |
+
image_input,
|
267 |
+
inference_steps_input,
|
268 |
+
cfg_input,
|
269 |
+
seed_input,
|
270 |
+
fps_input,
|
271 |
+
num_frames_input,
|
272 |
+
height_input,
|
273 |
+
width_input
|
274 |
+
],
|
275 |
+
outputs = image_output,
|
276 |
+
postprocess = False
|
277 |
+
).then(
|
278 |
+
fn = trigger_check_fun,
|
279 |
+
inputs = trigger_inputs,
|
280 |
+
outputs = will_trigger
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
281 |
)
|
282 |
#cancel_button.click(fn = lambda: None, cancels = ev)
|
283 |
|
284 |
+
demo.queue(concurrency_count = 1, max_size = 32)
|
285 |
+
demo.launch()
|
286 |
|
example.gif → example.webp
RENAMED
File without changes
|
examples/example_01_barbarian/input.png
DELETED
Git LFS Details
|
examples/example_01_barbarian/output.gif
DELETED
Git LFS Details
|
examples/example_01_barbarian/params.json
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"prompt": "he is dancing as minotaur dancer wearing a fur armor water in a dark cave, john cena, fantasy, barbarian",
|
3 |
-
"neg_prompt": "",
|
4 |
-
"cfg": 15,
|
5 |
-
"cfg_image": 9,
|
6 |
-
"seed": 1,
|
7 |
-
"steps": 20,
|
8 |
-
"width": 512,
|
9 |
-
"height": 512,
|
10 |
-
"scheduler": "dpm",
|
11 |
-
"fps": 20,
|
12 |
-
"format": "gif",
|
13 |
-
"num_frames": 24
|
14 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
examples/example_02_zombies/output.gif
DELETED
Git LFS Details
|
examples/example_02_zombies/params.json
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"prompt": "Group of scary zombies dancing. Halloween concept.",
|
3 |
-
"neg_prompt": "monochrome",
|
4 |
-
"cfg": 15,
|
5 |
-
"cfg_image": 15,
|
6 |
-
"seed": 0,
|
7 |
-
"steps": 20,
|
8 |
-
"width": 512,
|
9 |
-
"height": 512,
|
10 |
-
"scheduler": "dpm",
|
11 |
-
"fps": 20,
|
12 |
-
"format": "gif",
|
13 |
-
"num_frames": 24
|
14 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
examples/example_03_astronaut/output.gif
DELETED
Git LFS Details
|
examples/example_03_astronaut/params.json
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"prompt": "Astronaut performing shuffle dance moves on a Moon surface. Stanley Kubrick.",
|
3 |
-
"neg_prompt": "",
|
4 |
-
"cfg": 15,
|
5 |
-
"cfg_image": 15,
|
6 |
-
"seed": 0,
|
7 |
-
"steps": 20,
|
8 |
-
"width": 512,
|
9 |
-
"height": 512,
|
10 |
-
"scheduler": "dpm",
|
11 |
-
"fps": 20,
|
12 |
-
"format": "gif",
|
13 |
-
"num_frames": 24
|
14 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
examples/example_04_furry_moster/output.gif
DELETED
Git LFS Details
|
examples/example_04_furry_moster/params.json
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"prompt": "They are dancing in the club but everybody is a 3d cg hairy monster wearing a hairy costume.",
|
3 |
-
"neg_prompt": "monochrome, saturated",
|
4 |
-
"cfg": 15,
|
5 |
-
"cfg_image": 15,
|
6 |
-
"seed": 0,
|
7 |
-
"steps": 20,
|
8 |
-
"width": 512,
|
9 |
-
"height": 512,
|
10 |
-
"scheduler": "dpm",
|
11 |
-
"fps": 12,
|
12 |
-
"format": "gif",
|
13 |
-
"num_frames": 24
|
14 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
examples/example_05_people/input.png
DELETED
Git LFS Details
|
examples/example_05_people/output.gif
DELETED
Git LFS Details
|
examples/example_05_people/params.json
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"prompt": "Front view close up of group of people dancing at a concert in nightclub.",
|
3 |
-
"neg_prompt": "",
|
4 |
-
"cfg": 15,
|
5 |
-
"cfg_image": 9,
|
6 |
-
"seed": 3,
|
7 |
-
"steps": 20,
|
8 |
-
"width": 512,
|
9 |
-
"height": 512,
|
10 |
-
"scheduler": "dpm",
|
11 |
-
"fps": 20,
|
12 |
-
"format": "gif",
|
13 |
-
"num_frames": 24
|
14 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
examples/example_06_sophie/output.gif
DELETED
Git LFS Details
|
examples/example_06_sophie/params.json
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
{
|
2 |
-
"prompt": "A girl is dancing by a beautiful lake by sophie anderson and greg rutkowski and alphonse mucha.",
|
3 |
-
"neg_prompt": "",
|
4 |
-
"cfg": 15,
|
5 |
-
"cfg_image": 15,
|
6 |
-
"seed": 1,
|
7 |
-
"steps": 20,
|
8 |
-
"width": 512,
|
9 |
-
"height": 512,
|
10 |
-
"scheduler": "dpm",
|
11 |
-
"fps": 20,
|
12 |
-
"format": "gif",
|
13 |
-
"num_frames": 24
|
14 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
makeavid_sd/inference.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
|
2 |
-
from typing import Any, Union,
|
3 |
import os
|
4 |
import gc
|
5 |
from functools import partial
|
@@ -17,14 +17,13 @@ import einops
|
|
17 |
from diffusers import FlaxAutoencoderKL, FlaxUNet2DConditionModel
|
18 |
from diffusers import (
|
19 |
FlaxDDIMScheduler,
|
|
|
20 |
FlaxPNDMScheduler,
|
21 |
FlaxLMSDiscreteScheduler,
|
22 |
FlaxDPMSolverMultistepScheduler,
|
|
|
|
|
23 |
)
|
24 |
-
from diffusers.schedulers.scheduling_ddim_flax import DDIMSchedulerState
|
25 |
-
from diffusers.schedulers.scheduling_pndm_flax import PNDMSchedulerState
|
26 |
-
from diffusers.schedulers.scheduling_lms_discrete_flax import LMSDiscreteSchedulerState
|
27 |
-
from diffusers.schedulers.scheduling_dpmsolver_multistep_flax import DPMSolverMultistepSchedulerState
|
28 |
|
29 |
from transformers import FlaxCLIPTextModel, CLIPTokenizer
|
30 |
|
@@ -32,31 +31,14 @@ from .flax_impl.flax_unet_pseudo3d_condition import UNetPseudo3DConditionModel
|
|
32 |
|
33 |
SchedulerType = Union[
|
34 |
FlaxDDIMScheduler,
|
|
|
35 |
FlaxPNDMScheduler,
|
36 |
FlaxLMSDiscreteScheduler,
|
37 |
FlaxDPMSolverMultistepScheduler,
|
|
|
|
|
38 |
]
|
39 |
|
40 |
-
SchedulerStateType = Union[
|
41 |
-
DDIMSchedulerState,
|
42 |
-
PNDMSchedulerState,
|
43 |
-
LMSDiscreteSchedulerState,
|
44 |
-
DPMSolverMultistepSchedulerState,
|
45 |
-
]
|
46 |
-
|
47 |
-
SCHEDULERS: Dict[str, SchedulerType] = {
|
48 |
-
'dpm': FlaxDPMSolverMultistepScheduler, # husbando
|
49 |
-
'ddim': FlaxDDIMScheduler,
|
50 |
-
#'PLMS': FlaxPNDMScheduler, # its not correctly implemented in diffusers, output is bad, but at least it "works"
|
51 |
-
#'LMS': FlaxLMSDiscreteScheduler, # borked
|
52 |
-
# image_latents, image_scheduler_state = scheduler.step(
|
53 |
-
# File "/mnt/work1/make_a_vid/makeavid-space/.venv/lib/python3.10/site-packages/diffusers/schedulers/scheduling_lms_discrete_flax.py", line 255, in step
|
54 |
-
# order = min(timestep + 1, order)
|
55 |
-
# jax._src.errors.ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected: Traced<ShapedArray(bool[])>with<DynamicJaxprTrace(level=1/1)>
|
56 |
-
# The problem arose with the `bool` function.
|
57 |
-
# The error occurred while tracing the function scanned_fun at /mnt/work1/make_a_vid/makeavid-space/.venv/lib/python3.10/site-packages/jax/_src/lax/control_flow/loops.py:1668 for scan. This concrete value was not available in Python because it depends on the values of the arguments loop_carry[0] and loop_carry[1][1].timesteps
|
58 |
-
}
|
59 |
-
|
60 |
def dtypestr(x: jnp.dtype):
|
61 |
if x == jnp.float32: return 'float32'
|
62 |
elif x == jnp.float16: return 'float16'
|
@@ -71,6 +53,7 @@ def castto(dtype, m, x):
|
|
71 |
class InferenceUNetPseudo3D:
|
72 |
def __init__(self,
|
73 |
model_path: str,
|
|
|
74 |
dtype: jnp.dtype = jnp.float16,
|
75 |
hf_auth_token: Union[str, None] = None
|
76 |
) -> None:
|
@@ -146,27 +129,28 @@ class InferenceUNetPseudo3D:
|
|
146 |
subfolder = 'tokenizer',
|
147 |
use_auth_token = self.hf_auth_token
|
148 |
)
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
)
|
158 |
-
else:
|
159 |
-
scheduler, scheduler_state = SCHEDULERS[scheduler_name].from_pretrained(
|
160 |
-
self.model_path,
|
161 |
-
subfolder = 'scheduler',
|
162 |
-
use_auth_token = self.hf_auth_token
|
163 |
-
)
|
164 |
-
self.schedulers[scheduler_name] = scheduler
|
165 |
-
self.params[scheduler_name] = scheduler_state
|
166 |
self.vae_scale_factor: int = int(2 ** (len(self.vae.config.block_out_channels) - 1))
|
167 |
self.device_count = jax.device_count()
|
168 |
gc.collect()
|
169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
def prepare_inputs(self,
|
171 |
prompt: List[str],
|
172 |
neg_prompt: List[str],
|
@@ -224,18 +208,16 @@ class InferenceUNetPseudo3D:
|
|
224 |
return tokens, neg_tokens, hint, mask
|
225 |
|
226 |
def generate(self,
|
227 |
-
prompt: Union[str, List[str]]
|
228 |
-
inference_steps: int
|
229 |
hint_image: Union[Image.Image, List[Image.Image], None] = None,
|
230 |
mask_image: Union[Image.Image, List[Image.Image], None] = None,
|
231 |
neg_prompt: Union[str, List[str]] = '',
|
232 |
-
cfg: float =
|
233 |
-
cfg_image: Optional[float] = None,
|
234 |
num_frames: int = 24,
|
235 |
width: int = 512,
|
236 |
height: int = 512,
|
237 |
-
seed: int = 0
|
238 |
-
scheduler_type: str = 'dpm'
|
239 |
) -> List[List[Image.Image]]:
|
240 |
assert inference_steps > 0, f'number of inference steps must be > 0 but is {inference_steps}'
|
241 |
assert num_frames > 0, f'number of frames must be > 0 but is {num_frames}'
|
@@ -261,7 +243,6 @@ class InferenceUNetPseudo3D:
|
|
261 |
if isinstance(neg_prompt, str):
|
262 |
neg_prompt = [ neg_prompt ] * batch_size
|
263 |
assert len(neg_prompt) == batch_size, f'number of negative prompts must be equal to batch size {batch_size} but is {len(neg_prompt)}'
|
264 |
-
assert scheduler_type in SCHEDULERS, f'unknown type of noise scheduler: {scheduler_type}, must be one of {list(SCHEDULERS.keys())}'
|
265 |
tokens, neg_tokens, hint, mask = self.prepare_inputs(
|
266 |
prompt = prompt,
|
267 |
neg_prompt = neg_prompt,
|
@@ -270,14 +251,11 @@ class InferenceUNetPseudo3D:
|
|
270 |
width = width,
|
271 |
height = height
|
272 |
)
|
273 |
-
if cfg_image is None:
|
274 |
-
cfg_image = cfg
|
275 |
-
#params['scheduler'] = scheduler_state
|
276 |
# NOTE splitting rngs is not deterministic,
|
277 |
# running on different device counts gives different seeds
|
278 |
#rng = jax.random.PRNGKey(seed)
|
279 |
#rngs = jax.random.split(rng, self.device_count)
|
280 |
-
# manually assign seeded RNGs to devices for reproducability
|
281 |
rngs = jnp.array([ jax.random.PRNGKey(seed + i) for i in range(self.device_count) ])
|
282 |
params = jax_utils.replicate(self.params)
|
283 |
tokens = shard(tokens)
|
@@ -294,11 +272,9 @@ class InferenceUNetPseudo3D:
|
|
294 |
height,
|
295 |
width,
|
296 |
cfg,
|
297 |
-
cfg_image,
|
298 |
rngs,
|
299 |
params,
|
300 |
-
use_imagegen
|
301 |
-
scheduler_type,
|
302 |
)
|
303 |
if images.ndim == 5:
|
304 |
images = einops.rearrange(images, 'd f c h w -> (d f) h w c')
|
@@ -319,11 +295,9 @@ class InferenceUNetPseudo3D:
|
|
319 |
height,
|
320 |
width,
|
321 |
cfg: float,
|
322 |
-
cfg_image: float,
|
323 |
rng: jax.random.KeyArray,
|
324 |
params: Union[Dict[str, Any], FrozenDict[str, Any]],
|
325 |
-
use_imagegen: bool
|
326 |
-
scheduler_type: str
|
327 |
) -> List[Image.Image]:
|
328 |
batch_size = tokens.shape[0]
|
329 |
latent_h = height // self.vae_scale_factor
|
@@ -338,18 +312,15 @@ class InferenceUNetPseudo3D:
|
|
338 |
encoded_prompt = self.text_encoder(tokens, params = params['text_encoder'])[0]
|
339 |
encoded_neg_prompt = self.text_encoder(neg_tokens, params = params['text_encoder'])[0]
|
340 |
|
341 |
-
scheduler = self.schedulers[scheduler_type]
|
342 |
-
scheduler_state = params[scheduler_type]
|
343 |
-
|
344 |
if use_imagegen:
|
345 |
image_latent_shape = (batch_size, self.vae.config.latent_channels, latent_h, latent_w)
|
346 |
image_latents = jax.random.normal(
|
347 |
rng,
|
348 |
shape = image_latent_shape,
|
349 |
dtype = jnp.float32
|
350 |
-
) *
|
351 |
-
image_scheduler_state = scheduler.set_timesteps(
|
352 |
-
|
353 |
num_inference_steps = inference_steps,
|
354 |
shape = image_latents.shape
|
355 |
)
|
@@ -357,21 +328,21 @@ class InferenceUNetPseudo3D:
|
|
357 |
image_latents, image_scheduler_state = args
|
358 |
t = image_scheduler_state.timesteps[step]
|
359 |
tt = jnp.broadcast_to(t, image_latents.shape[0])
|
360 |
-
latents_input = scheduler.scale_model_input(image_scheduler_state, image_latents, t)
|
361 |
noise_pred = self.imunet.apply(
|
362 |
-
{
|
363 |
latents_input,
|
364 |
tt,
|
365 |
encoder_hidden_states = encoded_prompt
|
366 |
).sample
|
367 |
noise_pred_uncond = self.imunet.apply(
|
368 |
-
{
|
369 |
latents_input,
|
370 |
tt,
|
371 |
encoder_hidden_states = encoded_neg_prompt
|
372 |
).sample
|
373 |
-
noise_pred = noise_pred_uncond +
|
374 |
-
image_latents, image_scheduler_state = scheduler.step(
|
375 |
image_scheduler_state,
|
376 |
noise_pred.astype(jnp.float32),
|
377 |
t,
|
@@ -386,7 +357,7 @@ class InferenceUNetPseudo3D:
|
|
386 |
hint = image_latents
|
387 |
else:
|
388 |
hint = self.vae.apply(
|
389 |
-
{
|
390 |
hint,
|
391 |
method = self.vae.encode
|
392 |
).latent_dist.mean * self.vae.config.scaling_factor
|
@@ -404,9 +375,9 @@ class InferenceUNetPseudo3D:
|
|
404 |
rng,
|
405 |
shape = latent_shape,
|
406 |
dtype = jnp.float32
|
407 |
-
) *
|
408 |
-
scheduler_state = scheduler.set_timesteps(
|
409 |
-
|
410 |
num_inference_steps = inference_steps,
|
411 |
shape = latents.shape
|
412 |
)
|
@@ -415,7 +386,7 @@ class InferenceUNetPseudo3D:
|
|
415 |
latents, scheduler_state = args
|
416 |
t = scheduler_state.timesteps[step]#jnp.array(scheduler_state.timesteps, dtype = jnp.int32)[step]
|
417 |
tt = jnp.broadcast_to(t, latents.shape[0])
|
418 |
-
latents_input = scheduler.scale_model_input(scheduler_state, latents, t)
|
419 |
latents_input = jnp.concatenate([latents_input, mask, hint], axis = 1)
|
420 |
noise_pred = self.unet.apply(
|
421 |
{ 'params': params['unet'] },
|
@@ -430,7 +401,7 @@ class InferenceUNetPseudo3D:
|
|
430 |
encoded_neg_prompt
|
431 |
).sample
|
432 |
noise_pred = noise_pred_uncond + cfg * (noise_pred - noise_pred_uncond)
|
433 |
-
latents, scheduler_state = scheduler.step(
|
434 |
scheduler_state,
|
435 |
noise_pred.astype(jnp.float32),
|
436 |
t,
|
@@ -482,11 +453,9 @@ class InferenceUNetPseudo3D:
|
|
482 |
None, # 7 height
|
483 |
None, # 8 width
|
484 |
None, # 9 cfg
|
485 |
-
|
486 |
-
0, # 11
|
487 |
-
|
488 |
-
None, # 13 use_imagegen
|
489 |
-
None, # 14 scheduler_type
|
490 |
),
|
491 |
static_broadcasted_argnums = ( # trigger recompilation on change
|
492 |
0, # inference_class
|
@@ -494,8 +463,7 @@ class InferenceUNetPseudo3D:
|
|
494 |
6, # num_frames
|
495 |
7, # height
|
496 |
8, # width
|
497 |
-
|
498 |
-
14, # scheduler_type
|
499 |
)
|
500 |
)
|
501 |
def _p_generate(
|
@@ -504,16 +472,14 @@ def _p_generate(
|
|
504 |
neg_tokens,
|
505 |
hint,
|
506 |
mask,
|
507 |
-
inference_steps
|
508 |
-
num_frames
|
509 |
-
height
|
510 |
-
width
|
511 |
-
cfg
|
512 |
-
cfg_image: float,
|
513 |
rng,
|
514 |
params,
|
515 |
-
use_imagegen
|
516 |
-
scheduler_type: str
|
517 |
):
|
518 |
return inference_class._generate(
|
519 |
tokens,
|
@@ -525,10 +491,8 @@ def _p_generate(
|
|
525 |
height,
|
526 |
width,
|
527 |
cfg,
|
528 |
-
cfg_image,
|
529 |
rng,
|
530 |
params,
|
531 |
-
use_imagegen
|
532 |
-
scheduler_type
|
533 |
)
|
534 |
|
|
|
1 |
|
2 |
+
from typing import Any, Union, Tuple, List, Dict
|
3 |
import os
|
4 |
import gc
|
5 |
from functools import partial
|
|
|
17 |
from diffusers import FlaxAutoencoderKL, FlaxUNet2DConditionModel
|
18 |
from diffusers import (
|
19 |
FlaxDDIMScheduler,
|
20 |
+
FlaxDDPMScheduler,
|
21 |
FlaxPNDMScheduler,
|
22 |
FlaxLMSDiscreteScheduler,
|
23 |
FlaxDPMSolverMultistepScheduler,
|
24 |
+
FlaxKarrasVeScheduler,
|
25 |
+
FlaxScoreSdeVeScheduler
|
26 |
)
|
|
|
|
|
|
|
|
|
27 |
|
28 |
from transformers import FlaxCLIPTextModel, CLIPTokenizer
|
29 |
|
|
|
31 |
|
32 |
SchedulerType = Union[
|
33 |
FlaxDDIMScheduler,
|
34 |
+
FlaxDDPMScheduler,
|
35 |
FlaxPNDMScheduler,
|
36 |
FlaxLMSDiscreteScheduler,
|
37 |
FlaxDPMSolverMultistepScheduler,
|
38 |
+
FlaxKarrasVeScheduler,
|
39 |
+
FlaxScoreSdeVeScheduler
|
40 |
]
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
def dtypestr(x: jnp.dtype):
|
43 |
if x == jnp.float32: return 'float32'
|
44 |
elif x == jnp.float16: return 'float16'
|
|
|
53 |
class InferenceUNetPseudo3D:
|
54 |
def __init__(self,
|
55 |
model_path: str,
|
56 |
+
scheduler_cls: SchedulerType = FlaxDDIMScheduler,
|
57 |
dtype: jnp.dtype = jnp.float16,
|
58 |
hf_auth_token: Union[str, None] = None
|
59 |
) -> None:
|
|
|
129 |
subfolder = 'tokenizer',
|
130 |
use_auth_token = self.hf_auth_token
|
131 |
)
|
132 |
+
scheduler, scheduler_state = scheduler_cls.from_pretrained(
|
133 |
+
self.model_path,
|
134 |
+
subfolder = 'scheduler',
|
135 |
+
dtype = jnp.float32,
|
136 |
+
use_auth_token = self.hf_auth_token
|
137 |
+
)
|
138 |
+
self.scheduler: scheduler_cls = scheduler
|
139 |
+
self.params['scheduler'] = scheduler_state
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
self.vae_scale_factor: int = int(2 ** (len(self.vae.config.block_out_channels) - 1))
|
141 |
self.device_count = jax.device_count()
|
142 |
gc.collect()
|
143 |
|
144 |
+
def set_scheduler(self, scheduler_cls: SchedulerType) -> None:
|
145 |
+
scheduler, scheduler_state = scheduler_cls.from_pretrained(
|
146 |
+
self.model_path,
|
147 |
+
subfolder = 'scheduler',
|
148 |
+
dtype = jnp.float32,
|
149 |
+
use_auth_token = self.hf_auth_token
|
150 |
+
)
|
151 |
+
self.scheduler: scheduler_cls = scheduler
|
152 |
+
self.params['scheduler'] = scheduler_state
|
153 |
+
|
154 |
def prepare_inputs(self,
|
155 |
prompt: List[str],
|
156 |
neg_prompt: List[str],
|
|
|
208 |
return tokens, neg_tokens, hint, mask
|
209 |
|
210 |
def generate(self,
|
211 |
+
prompt: Union[str, List[str]],
|
212 |
+
inference_steps: int,
|
213 |
hint_image: Union[Image.Image, List[Image.Image], None] = None,
|
214 |
mask_image: Union[Image.Image, List[Image.Image], None] = None,
|
215 |
neg_prompt: Union[str, List[str]] = '',
|
216 |
+
cfg: float = 10.0,
|
|
|
217 |
num_frames: int = 24,
|
218 |
width: int = 512,
|
219 |
height: int = 512,
|
220 |
+
seed: int = 0
|
|
|
221 |
) -> List[List[Image.Image]]:
|
222 |
assert inference_steps > 0, f'number of inference steps must be > 0 but is {inference_steps}'
|
223 |
assert num_frames > 0, f'number of frames must be > 0 but is {num_frames}'
|
|
|
243 |
if isinstance(neg_prompt, str):
|
244 |
neg_prompt = [ neg_prompt ] * batch_size
|
245 |
assert len(neg_prompt) == batch_size, f'number of negative prompts must be equal to batch size {batch_size} but is {len(neg_prompt)}'
|
|
|
246 |
tokens, neg_tokens, hint, mask = self.prepare_inputs(
|
247 |
prompt = prompt,
|
248 |
neg_prompt = neg_prompt,
|
|
|
251 |
width = width,
|
252 |
height = height
|
253 |
)
|
|
|
|
|
|
|
254 |
# NOTE splitting rngs is not deterministic,
|
255 |
# running on different device counts gives different seeds
|
256 |
#rng = jax.random.PRNGKey(seed)
|
257 |
#rngs = jax.random.split(rng, self.device_count)
|
258 |
+
# manually assign seeded RNGs to devices for reproducability
|
259 |
rngs = jnp.array([ jax.random.PRNGKey(seed + i) for i in range(self.device_count) ])
|
260 |
params = jax_utils.replicate(self.params)
|
261 |
tokens = shard(tokens)
|
|
|
272 |
height,
|
273 |
width,
|
274 |
cfg,
|
|
|
275 |
rngs,
|
276 |
params,
|
277 |
+
use_imagegen
|
|
|
278 |
)
|
279 |
if images.ndim == 5:
|
280 |
images = einops.rearrange(images, 'd f c h w -> (d f) h w c')
|
|
|
295 |
height,
|
296 |
width,
|
297 |
cfg: float,
|
|
|
298 |
rng: jax.random.KeyArray,
|
299 |
params: Union[Dict[str, Any], FrozenDict[str, Any]],
|
300 |
+
use_imagegen: bool
|
|
|
301 |
) -> List[Image.Image]:
|
302 |
batch_size = tokens.shape[0]
|
303 |
latent_h = height // self.vae_scale_factor
|
|
|
312 |
encoded_prompt = self.text_encoder(tokens, params = params['text_encoder'])[0]
|
313 |
encoded_neg_prompt = self.text_encoder(neg_tokens, params = params['text_encoder'])[0]
|
314 |
|
|
|
|
|
|
|
315 |
if use_imagegen:
|
316 |
image_latent_shape = (batch_size, self.vae.config.latent_channels, latent_h, latent_w)
|
317 |
image_latents = jax.random.normal(
|
318 |
rng,
|
319 |
shape = image_latent_shape,
|
320 |
dtype = jnp.float32
|
321 |
+
) * params['scheduler'].init_noise_sigma
|
322 |
+
image_scheduler_state = self.scheduler.set_timesteps(
|
323 |
+
params['scheduler'],
|
324 |
num_inference_steps = inference_steps,
|
325 |
shape = image_latents.shape
|
326 |
)
|
|
|
328 |
image_latents, image_scheduler_state = args
|
329 |
t = image_scheduler_state.timesteps[step]
|
330 |
tt = jnp.broadcast_to(t, image_latents.shape[0])
|
331 |
+
latents_input = self.scheduler.scale_model_input(image_scheduler_state, image_latents, t)
|
332 |
noise_pred = self.imunet.apply(
|
333 |
+
{'params': params['imunet']},
|
334 |
latents_input,
|
335 |
tt,
|
336 |
encoder_hidden_states = encoded_prompt
|
337 |
).sample
|
338 |
noise_pred_uncond = self.imunet.apply(
|
339 |
+
{'params': params['imunet']},
|
340 |
latents_input,
|
341 |
tt,
|
342 |
encoder_hidden_states = encoded_neg_prompt
|
343 |
).sample
|
344 |
+
noise_pred = noise_pred_uncond + cfg * (noise_pred - noise_pred_uncond)
|
345 |
+
image_latents, image_scheduler_state = self.scheduler.step(
|
346 |
image_scheduler_state,
|
347 |
noise_pred.astype(jnp.float32),
|
348 |
t,
|
|
|
357 |
hint = image_latents
|
358 |
else:
|
359 |
hint = self.vae.apply(
|
360 |
+
{'params': params['vae']},
|
361 |
hint,
|
362 |
method = self.vae.encode
|
363 |
).latent_dist.mean * self.vae.config.scaling_factor
|
|
|
375 |
rng,
|
376 |
shape = latent_shape,
|
377 |
dtype = jnp.float32
|
378 |
+
) * params['scheduler'].init_noise_sigma
|
379 |
+
scheduler_state = self.scheduler.set_timesteps(
|
380 |
+
params['scheduler'],
|
381 |
num_inference_steps = inference_steps,
|
382 |
shape = latents.shape
|
383 |
)
|
|
|
386 |
latents, scheduler_state = args
|
387 |
t = scheduler_state.timesteps[step]#jnp.array(scheduler_state.timesteps, dtype = jnp.int32)[step]
|
388 |
tt = jnp.broadcast_to(t, latents.shape[0])
|
389 |
+
latents_input = self.scheduler.scale_model_input(scheduler_state, latents, t)
|
390 |
latents_input = jnp.concatenate([latents_input, mask, hint], axis = 1)
|
391 |
noise_pred = self.unet.apply(
|
392 |
{ 'params': params['unet'] },
|
|
|
401 |
encoded_neg_prompt
|
402 |
).sample
|
403 |
noise_pred = noise_pred_uncond + cfg * (noise_pred - noise_pred_uncond)
|
404 |
+
latents, scheduler_state = self.scheduler.step(
|
405 |
scheduler_state,
|
406 |
noise_pred.astype(jnp.float32),
|
407 |
t,
|
|
|
453 |
None, # 7 height
|
454 |
None, # 8 width
|
455 |
None, # 9 cfg
|
456 |
+
0, # 10 rng
|
457 |
+
0, # 11 params
|
458 |
+
None, # 12 use_imagegen
|
|
|
|
|
459 |
),
|
460 |
static_broadcasted_argnums = ( # trigger recompilation on change
|
461 |
0, # inference_class
|
|
|
463 |
6, # num_frames
|
464 |
7, # height
|
465 |
8, # width
|
466 |
+
12, # use_imagegen
|
|
|
467 |
)
|
468 |
)
|
469 |
def _p_generate(
|
|
|
472 |
neg_tokens,
|
473 |
hint,
|
474 |
mask,
|
475 |
+
inference_steps,
|
476 |
+
num_frames,
|
477 |
+
height,
|
478 |
+
width,
|
479 |
+
cfg,
|
|
|
480 |
rng,
|
481 |
params,
|
482 |
+
use_imagegen
|
|
|
483 |
):
|
484 |
return inference_class._generate(
|
485 |
tokens,
|
|
|
491 |
height,
|
492 |
width,
|
493 |
cfg,
|
|
|
494 |
rng,
|
495 |
params,
|
496 |
+
use_imagegen
|
|
|
497 |
)
|
498 |
|
requirements.txt
CHANGED
@@ -6,5 +6,5 @@ einops
|
|
6 |
-f https://download.pytorch.org/whl/cpu/torch
|
7 |
torch[cpu]
|
8 |
-f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html
|
9 |
-
jax[
|
10 |
flax
|
|
|
6 |
-f https://download.pytorch.org/whl/cpu/torch
|
7 |
torch[cpu]
|
8 |
-f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html
|
9 |
+
jax[cuda11_cudnn82] #jax[cuda11_cudnn86] #jax[cuda11_cudnn805]
|
10 |
flax
|