Spaces:
Build error
Build error
File size: 15,770 Bytes
2c924d3 |
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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 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 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
import torch
from enum import Enum
import gc
import numpy as np
import jax.numpy as jnp
import tomesd
import jax
from flax.training.common_utils import shard
from flax.jax_utils import replicate
from flax import jax_utils
import einops
from transformers import CLIPTokenizer, CLIPFeatureExtractor, FlaxCLIPTextModel
from diffusers import (
FlaxDDIMScheduler,
FlaxAutoencoderKL,
FlaxStableDiffusionControlNetPipeline,
StableDiffusionPipeline,
)
from text_to_animation.models.unet_2d_condition_flax import FlaxUNet2DConditionModel
from text_to_animation.models.controlnet_flax import FlaxControlNetModel
from text_to_animation.pipelines.text_to_video_pipeline_flax import (
FlaxTextToVideoPipeline,
)
import utils.utils as utils
import utils.gradio_utils as gradio_utils
import os
on_huggingspace = os.environ.get("SPACE_AUTHOR_NAME") == "PAIR"
unshard = lambda x: einops.rearrange(x, "d b ... -> (d b) ...")
class ModelType(Enum):
Text2Video = 1
ControlNetPose = 2
StableDiffusion = 3
def replicate_devices(array):
return jnp.expand_dims(array, 0).repeat(jax.device_count(), 0)
class ControlAnimationModel:
def __init__(self, device, dtype, **kwargs):
self.device = device
self.dtype = dtype
self.rng = jax.random.PRNGKey(0)
self.pipe_dict = {
ModelType.Text2Video: FlaxTextToVideoPipeline, # TODO: Replace with our TextToVideo JAX Pipeline
ModelType.ControlNetPose: FlaxStableDiffusionControlNetPipeline,
}
self.pipe = None
self.model_type = None
self.states = {}
self.model_name = ""
self.from_local = True # if the attn model is available in local (after adaptation by adapt_attn.py)
def set_model(
self,
model_type: ModelType,
model_id: str,
controlnet,
controlnet_params,
tokenizer,
scheduler,
scheduler_state,
**kwargs,
):
if hasattr(self, "pipe") and self.pipe is not None:
del self.pipe
self.pipe = None
gc.collect()
scheduler, scheduler_state = FlaxDDIMScheduler.from_pretrained(
model_id, subfolder="scheduler", from_pt=True
)
tokenizer = CLIPTokenizer.from_pretrained(model_id, subfolder="tokenizer")
feature_extractor = CLIPFeatureExtractor.from_pretrained(
model_id, subfolder="feature_extractor"
)
if self.from_local:
unet, unet_params = FlaxUNet2DConditionModel.from_pretrained(
f'./{model_id.split("/")[-1]}',
subfolder="unet",
from_pt=True,
dtype=self.dtype,
)
else:
unet, unet_params = FlaxUNet2DConditionModel.from_pretrained(
model_id, subfolder="unet", from_pt=True, dtype=self.dtype
)
vae, vae_params = FlaxAutoencoderKL.from_pretrained(
model_id, subfolder="vae", from_pt=True, dtype=self.dtype
)
text_encoder = FlaxCLIPTextModel.from_pretrained(
model_id, subfolder="text_encoder", from_pt=True, dtype=self.dtype
)
self.pipe = FlaxTextToVideoPipeline(
vae=vae,
text_encoder=text_encoder,
tokenizer=tokenizer,
unet=unet,
controlnet=controlnet,
scheduler=scheduler,
safety_checker=None,
feature_extractor=feature_extractor,
)
self.params = {
"unet": unet_params,
"vae": vae_params,
"scheduler": scheduler_state,
"controlnet": controlnet_params,
"text_encoder": text_encoder.params,
}
self.p_params = jax_utils.replicate(self.params)
self.model_type = model_type
self.model_name = model_id
# def inference_chunk(self, image, frame_ids, prompt, negative_prompt, **kwargs):
# prompt_ids = self.pipe.prepare_text_inputs(prompt)
# n_prompt_ids = self.pipe.prepare_text_inputs(negative_prompt)
# latents = kwargs.pop('latents')
# # rng = jax.random.split(self.rng, jax.device_count())
# prng, self.rng = jax.random.split(self.rng)
# #prng = jax.numpy.stack([prng] * jax.device_count())#same prng seed on every device
# prng_seed = jax.random.split(prng, jax.device_count())
# image = replicate_devices(image[frame_ids])
# latents = replicate_devices(latents)
# prompt_ids = replicate_devices(prompt_ids)
# n_prompt_ids = replicate_devices(n_prompt_ids)
# return (self.pipe(image=image,
# latents=latents,
# prompt_ids=prompt_ids,
# neg_prompt_ids=n_prompt_ids,
# params=self.p_params,
# prng_seed=prng_seed, jit = True,
# ).images)[0]
def inference(self, image, split_to_chunks=False, chunk_size=8, **kwargs):
if not hasattr(self, "pipe") or self.pipe is None:
return
if "merging_ratio" in kwargs:
merging_ratio = kwargs.pop("merging_ratio")
# if merging_ratio > 0:
tomesd.apply_patch(self.pipe, ratio=merging_ratio)
# f = image.shape[0]
assert "prompt" in kwargs
prompt = [kwargs.pop("prompt")]
negative_prompt = [kwargs.pop("negative_prompt", "")]
frames_counter = 0
# Processing chunk-by-chunk
if split_to_chunks:
pass
# # not tested
# f = image.shape[0]
# chunk_ids = np.arange(0, f, chunk_size - 1)
# result = []
# for i in range(len(chunk_ids)):
# ch_start = chunk_ids[i]
# ch_end = f if i == len(chunk_ids) - 1 else chunk_ids[i + 1]
# frame_ids = [0] + list(range(ch_start, ch_end))
# print(f'Processing chunk {i + 1} / {len(chunk_ids)}')
# result.append(self.inference_chunk(image=image,
# frame_ids=frame_ids,
# prompt=prompt,
# negative_prompt=negative_prompt,
# **kwargs).images[1:])
# frames_counter += len(chunk_ids)-1
# if on_huggingspace and frames_counter >= 80:
# break
# result = np.concatenate(result)
# return result
else:
if "jit" in kwargs and kwargs.pop("jit"):
prompt_ids = self.pipe.prepare_text_inputs(prompt)
n_prompt_ids = self.pipe.prepare_text_inputs(negative_prompt)
latents = kwargs.pop("latents")
prng, self.rng = jax.random.split(self.rng)
prng_seed = jax.random.split(prng, jax.device_count())
image = replicate_devices(image)
latents = replicate_devices(latents)
prompt_ids = replicate_devices(prompt_ids)
n_prompt_ids = replicate_devices(n_prompt_ids)
return (
self.pipe(
image=image,
latents=latents,
prompt_ids=prompt_ids,
neg_prompt_ids=n_prompt_ids,
params=self.p_params,
prng_seed=prng_seed,
jit=True,
).images
)[0]
else:
prompt_ids = self.pipe.prepare_text_inputs(prompt)
n_prompt_ids = self.pipe.prepare_text_inputs(negative_prompt)
latents = kwargs.pop("latents")
prng_seed, self.rng = jax.random.split(self.rng)
return self.pipe(
image=image,
latents=latents,
prompt_ids=prompt_ids,
neg_prompt_ids=n_prompt_ids,
params=self.params,
prng_seed=prng_seed,
jit=False,
).images
def process_controlnet_pose(
self,
video_path,
prompt,
chunk_size=8,
watermark="Picsart AI Research",
merging_ratio=0.0,
num_inference_steps=20,
controlnet_conditioning_scale=1.0,
guidance_scale=9.0,
seed=42,
eta=0.0,
resolution=512,
use_cf_attn=True,
save_path=None,
):
print("Module Pose")
video_path = gradio_utils.motion_to_video_path(video_path)
if self.model_type != ModelType.ControlNetPose:
controlnet = FlaxControlNetModel.from_pretrained(
"fusing/stable-diffusion-v1-5-controlnet-openpose"
)
self.set_model(
ModelType.ControlNetPose,
model_id="runwayml/stable-diffusion-v1-5",
controlnet=controlnet,
)
self.pipe.scheduler = FlaxDDIMScheduler.from_config(
self.pipe.scheduler.config
)
if use_cf_attn:
self.pipe.unet.set_attn_processor(processor=self.controlnet_attn_proc)
self.pipe.controlnet.set_attn_processor(
processor=self.controlnet_attn_proc
)
video_path = (
gradio_utils.motion_to_video_path(video_path)
if "Motion" in video_path
else video_path
)
added_prompt = "best quality, extremely detailed, HD, ultra-realistic, 8K, HQ, masterpiece, trending on artstation, art, smooth"
negative_prompts = "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer difits, cropped, worst quality, low quality, deformed body, bloated, ugly, unrealistic"
video, fps = utils.prepare_video(
video_path, resolution, self.device, self.dtype, False, output_fps=4
)
control = (
utils.pre_process_pose(video, apply_pose_detect=False)
.to(self.device)
.to(self.dtype)
)
f, _, h, w = video.shape
self.generator.manual_seed(seed)
latents = torch.randn(
(1, 4, h // 8, w // 8),
dtype=self.dtype,
device=self.device,
generator=self.generator,
)
latents = latents.repeat(f, 1, 1, 1)
result = self.inference(
image=control,
prompt=prompt + ", " + added_prompt,
height=h,
width=w,
negative_prompt=negative_prompts,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
controlnet_conditioning_scale=controlnet_conditioning_scale,
eta=eta,
latents=latents,
seed=seed,
output_type="numpy",
split_to_chunks=True,
chunk_size=chunk_size,
merging_ratio=merging_ratio,
)
return utils.create_gif(
result,
fps,
path=save_path,
watermark=gradio_utils.logo_name_to_path(watermark),
)
def process_text2video(
self,
prompt,
model_name="dreamlike-art/dreamlike-photoreal-2.0",
motion_field_strength_x=12,
motion_field_strength_y=12,
t0=44,
t1=47,
n_prompt="",
chunk_size=8,
video_length=8,
watermark="Picsart AI Research",
merging_ratio=0.0,
seed=0,
resolution=512,
fps=2,
use_cf_attn=True,
use_motion_field=True,
smooth_bg=False,
smooth_bg_strength=0.4,
path=None,
):
print("Module Text2Video")
if self.model_type != ModelType.Text2Video or model_name != self.model_name:
print("Model update")
unet = FlaxUNet2DConditionModel.from_pretrained(
model_name, subfolder="unet"
)
self.set_model(ModelType.Text2Video, model_id=model_name, unet=unet)
self.pipe.scheduler = FlaxDDIMScheduler.from_config(
self.pipe.scheduler.config
)
if use_cf_attn:
self.pipe.unet.set_attn_processor(processor=self.text2video_attn_proc)
self.generator.manual_seed(seed)
added_prompt = "high quality, HD, 8K, trending on artstation, high focus, dramatic lighting"
negative_prompts = "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer difits, cropped, worst quality, low quality, deformed body, bloated, ugly, unrealistic"
prompt = prompt.rstrip()
if len(prompt) > 0 and (prompt[-1] == "," or prompt[-1] == "."):
prompt = prompt.rstrip()[:-1]
prompt = prompt.rstrip()
prompt = prompt + ", " + added_prompt
if len(n_prompt) > 0:
negative_prompt = n_prompt
else:
negative_prompt = None
result = self.inference(
prompt=prompt,
video_length=video_length,
height=resolution,
width=resolution,
num_inference_steps=50,
guidance_scale=7.5,
guidance_stop_step=1.0,
t0=t0,
t1=t1,
motion_field_strength_x=motion_field_strength_x,
motion_field_strength_y=motion_field_strength_y,
use_motion_field=use_motion_field,
smooth_bg=smooth_bg,
smooth_bg_strength=smooth_bg_strength,
seed=seed,
output_type="numpy",
negative_prompt=negative_prompt,
merging_ratio=merging_ratio,
split_to_chunks=True,
chunk_size=chunk_size,
)
return utils.create_video(
result, fps, path=path, watermark=gradio_utils.logo_name_to_path(watermark)
)
def generate_animation(
self,
prompt: str,
model_link: str = "dreamlike-art/dreamlike-photoreal-2.0",
is_safetensor: bool = False,
motion_field_strength_x: int = 12,
motion_field_strength_y: int = 12,
t0: int = 44,
t1: int = 47,
n_prompt: str = "",
chunk_size: int = 8,
video_length: int = 8,
merging_ratio: float = 0.0,
seed: int = 0,
resolution: int = 512,
fps: int = 2,
use_cf_attn: bool = True,
use_motion_field: bool = True,
smooth_bg: bool = False,
smooth_bg_strength: float = 0.4,
path: str = None,
):
if is_safetensor and model_link[-len(".safetensors") :] == ".safetensors":
pipe = utils.load_safetensors_model(model_link)
return
def generate_initial_frames(
self,
prompt: str,
model_link: str = "dreamlike-art/dreamlike-photoreal-2.0",
is_safetensor: bool = False,
n_prompt: str = "",
width: int = 512,
height: int = 512,
# batch_count: int = 4,
# batch_size: int = 1,
cfg_scale: float = 7.0,
seed: int = 0,
):
print(f">>> prompt: {prompt}, model_link: {model_link}")
pipe = StableDiffusionPipeline.from_pretrained(model_link)
batch_size = 4
prompt = [prompt] * batch_size
negative_prompt = [n_prompt] * batch_size
images = pipe(
prompt,
negative_prompt=negative_prompt,
width=width,
height=height,
guidance_scale=cfg_scale,
).images
return images
|