From e4e612db05f17c45a72ffc7cb78d3daff64ac42a Mon Sep 17 00:00:00 2001 From: glide-the <2533736852@qq.com> Date: Tue, 20 Aug 2024 15:04:47 +0800 Subject: [PATCH] feat: Add upscale model integration and batch processing for video frames - Integrated progress tracking with upscale model loading. - Implemented conditional latent upscaling using the upscale model. - Processed batch video frames using PyTorch and converted them to PIL images. --- inference/gradio_web_demo.py | 287 +++++++++++++++++++++++------------ inference/utils.py | 144 ++++++++++++++++++ requirements.txt | 8 +- 3 files changed, 338 insertions(+), 101 deletions(-) create mode 100644 inference/utils.py diff --git a/inference/gradio_web_demo.py b/inference/gradio_web_demo.py index b81c0ba..ae1e6d7 100644 --- a/inference/gradio_web_demo.py +++ b/inference/gradio_web_demo.py @@ -1,3 +1,4 @@ +import gc import os import tempfile import threading @@ -8,17 +9,29 @@ import numpy as np import torch from diffusers import CogVideoXPipeline from datetime import datetime, timedelta + +from diffusers.image_processor import VaeImageProcessor from openai import OpenAI +import spaces import imageio import moviepy.editor as mp from typing import List, Union import PIL +import utils -dtype = torch.bfloat16 device = "cuda" if torch.cuda.is_available() else "cpu" -pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=dtype) + +pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16).to( + device) pipe.enable_model_cpu_offload() +gc.collect() +torch.cuda.empty_cache() +torch.cuda.reset_accumulated_memory_stats() +torch.cuda.reset_peak_memory_stats() + +# pipe.vae.enable_tiling() +UP_SCALE_MODEL = None sys_prompt = """You are part of a team of bots that creates videos. You work with an assistant bot that will draw anything you say in square brackets. For example , outputting " a beautiful morning in the woods with the sun peaking through the trees " will trigger your partner bot to output an video of a forest morning , as described. You will be prompted by people looking to create detailed , amazing videos. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive. @@ -33,8 +46,67 @@ Video descriptions must have the same num of words as examples below. Extra word """ +def load_sd_upscale(ckpt): + from spandrel import ModelLoader, ImageModelDescriptor # Simulate a step in loading + + pbar = utils.ProgressBar(1) + sd = utils.load_torch_file(ckpt, device=device) + if "module.layers.0.residual_group.blocks.0.norm1.weight" in sd: + sd = utils.state_dict_prefix_replace(sd, {"module.": ""}) + out = ModelLoader().load_from_state_dict(sd).half() + + pbar.update(1) # Update progress by 1 + return out + + +def upscale(upscale_model, tensor: torch.Tensor) -> torch.Tensor: + memory_required = utils.module_size(upscale_model.model) + memory_required += ((512 * 512 * 3) * + tensor.element_size() * + max(upscale_model.scale, 1.0) * + 384.0 + ) #The 384.0 is an estimate of how much some of these models take, TODO: make it more accurate + memory_required += tensor.nelement() * tensor.element_size() + print(f"Memory required: {memory_required / 1024 / 1024 / 1024} GB") + + upscale_model.to(device) + # in_img = tensor.movedim(-1, -3).to(device) + + tile = 512 + overlap = 32 + + steps = tensor.shape[0] * utils.get_tiled_scale_steps(tensor.shape[3], tensor.shape[2], tile_x=tile, + tile_y=tile, overlap=overlap) + + pbar = utils.ProgressBar(steps) + + s = utils.tiled_scale(tensor, lambda a: upscale_model(a), tile_x=tile, tile_y=tile, overlap=overlap, + upscale_amount=upscale_model.scale, pbar=pbar) + + upscale_model.to("cpu") + return s + + +def upscale_batch_and_concatenate(upscale_model, latents): + # 初始化一个空列表来存储每个批次的放大结果 + upscaled_latents = [] + + # 遍历第一个维度 (批次) + for i in range(latents.size(0)): + # 取出第 i 个批次数据 (形状为 [49, 3, 512, 480]) + latent = latents[i] + + # 调用放大模型对该批次数据进行放大 + upscaled_latent = upscale(upscale_model, latent) + + # 将放大的结果存储到列表中 + upscaled_latents.append(upscaled_latent) + + return torch.stack(upscaled_latents) + + def export_to_video_imageio( - video_frames: Union[List[np.ndarray], List[PIL.Image.Image]], output_video_path: str = None, fps: int = 8 + video_frames: Union[List[np.ndarray], List[PIL.Image.Image]], output_video_path: str = None, fps: int = 8 ) -> str: """ Export the video frames to a video file using imageio lib to Avoid "green screen" issue (for example CogVideoX) @@ -62,74 +134,56 @@ def convert_prompt(prompt: str, retry_times: int = 3) -> str: response = client.chat.completions.create( messages=[ {"role": "system", "content": sys_prompt}, - { - "role": "user", - "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"', - }, - { - "role": "assistant", - "content": "A radiant woman stands on a deserted beach, arms outstretched, wearing a beige trench coat, white blouse, light blue jeans, and chic boots, against a backdrop of soft sky and sea. Moments later, she is seen mid-twirl, arms exuberant, with the lighting suggesting dawn or dusk. Then, she runs along the beach, her attire complemented by an off-white scarf and black ankle boots, the tranquil sea behind her. Finally, she holds a paper airplane, her pose reflecting joy and freedom, with the ocean's gentle waves and the sky's soft pastel hues enhancing the serene ambiance.", - }, - { - "role": "user", - "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"', - }, - { - "role": "assistant", - "content": "A determined man in athletic attire, including a blue long-sleeve shirt, black shorts, and blue socks, jogs around a snow-covered soccer field, showcasing his solitary exercise in a quiet, overcast setting. His long dreadlocks, focused expression, and the serene winter backdrop highlight his dedication to fitness. As he moves, his attire, consisting of a blue sports sweatshirt, black athletic pants, gloves, and sneakers, grips the snowy ground. He is seen running past a chain-link fence enclosing the playground area, with a basketball hoop and children's slide, suggesting a moment of solitary exercise amidst the empty field.", - }, - { - "role": "user", - "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"', - }, - { - "role": "assistant", - "content": "A young woman with her hair in an updo and wearing a teal hoodie stands against a light backdrop, initially looking over her shoulder with a contemplative expression. She then confidently makes a subtle dance move, suggesting rhythm and movement. Next, she appears poised and focused, looking directly at the camera. Her expression shifts to one of introspection as she gazes downward slightly. Finally, she dances with confidence, her left hand over her heart, symbolizing a poignant moment, all while dressed in the same teal hoodie against a plain, light-colored background.", - }, - { - "role": "user", - "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"', - }, + {"role": "user", + "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"'}, + {"role": "assistant", + "content": "A radiant woman stands on a deserted beach, arms outstretched, wearing a beige trench coat, white blouse, light blue jeans, and chic boots, against a backdrop of soft sky and sea. Moments later, she is seen mid-twirl, arms exuberant, with the lighting suggesting dawn or dusk. Then, she runs along the beach, her attire complemented by an off-white scarf and black ankle boots, the tranquil sea behind her. Finally, she holds a paper airplane, her pose reflecting joy and freedom, with the ocean's gentle waves and the sky's soft pastel hues enhancing the serene ambiance."}, + {"role": "user", + "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"'}, + {"role": "assistant", + "content": "A determined man in athletic attire, including a blue long-sleeve shirt, black shorts, and blue socks, jogs around a snow-covered soccer field, showcasing his solitary exercise in a quiet, overcast setting. His long dreadlocks, focused expression, and the serene winter backdrop highlight his dedication to fitness. As he moves, his attire, consisting of a blue sports sweatshirt, black athletic pants, gloves, and sneakers, grips the snowy ground. He is seen running past a chain-link fence enclosing the playground area, with a basketball hoop and children's slide, suggesting a moment of solitary exercise amidst the empty field."}, + {"role": "user", + "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : " A woman is dancing, HD footage, close-up"'}, + {"role": "assistant", + "content": "A young woman with her hair in an updo and wearing a teal hoodie stands against a light backdrop, initially looking over her shoulder with a contemplative expression. She then confidently makes a subtle dance move, suggesting rhythm and movement. Next, she appears poised and focused, looking directly at the camera. Her expression shifts to one of introspection as she gazes downward slightly. Finally, she dances with confidence, her left hand over her heart, symbolizing a poignant moment, all while dressed in the same teal hoodie against a plain, light-colored background."}, + {"role": "user", + "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"'}, ], model="glm-4-0520", temperature=0.01, top_p=0.7, stream=False, - max_tokens=250, + max_tokens=200, ) if response.choices: return response.choices[0].message.content return prompt -def infer(prompt: str, num_inference_steps: int, guidance_scale: float, progress=gr.Progress(track_tqdm=True)): +@spaces.GPU(duration=300) +def infer( + prompt: str, + num_inference_steps: int, + guidance_scale: float, + progress=gr.Progress(track_tqdm=True), +): torch.cuda.empty_cache() - prompt_embeds, _ = pipe.encode_prompt( + video_pt = pipe( prompt=prompt, - negative_prompt=None, - do_classifier_free_guidance=True, - num_videos_per_prompt=1, - max_sequence_length=226, - device=device, - dtype=dtype, - ) - - video = pipe( num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, - prompt_embeds=prompt_embeds, - negative_prompt_embeds=torch.zeros_like(prompt_embeds), - ).frames[0] + output_type="pt" + ).frames - return video + return video_pt -def save_video(tensor): +def save_video(tensor: Union[List[np.ndarray], List[PIL.Image.Image]]): timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") video_path = f"./output/{timestamp}.mp4" os.makedirs(os.path.dirname(video_path), exist_ok=True) - export_to_video_imageio(tensor[1:], video_path) + export_to_video_imageio(tensor, video_path) return video_path @@ -137,7 +191,7 @@ def convert_to_gif(video_path): clip = mp.VideoFileClip(video_path) clip = clip.set_fps(8) clip = clip.resize(height=240) - gif_path = video_path.replace(".mp4", ".gif") + gif_path = video_path.replace('.mp4', '.gif') clip.write_gif(gif_path, fps=8) return gif_path @@ -146,7 +200,8 @@ def delete_old_files(): while True: now = datetime.now() cutoff = now - timedelta(minutes=10) - output_dir = "./output" + output_dir = './output' + os.makedirs(output_dir, exist_ok=True) for filename in os.listdir(output_dir): file_path = os.path.join(output_dir, filename) if os.path.isfile(file_path): @@ -161,11 +216,13 @@ threading.Thread(target=delete_old_files, daemon=True).start() with gr.Blocks() as demo: gr.Markdown("""
| Prompt | -Video URL | -Inference Steps | -Guidance Scale | -
|---|---|---|---|
| A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting. | -Video 1 | -50 | -6 | -
| The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from it’s tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds. | -Video 2 | -50 | -6 | -
| A street artist, clad in a worn-out denim jacket and a colorful bandana, stands before a vast concrete wall in the heart, holding a can of spray paint, spray-painting a colorful bird on a mottled wall. | -Video 3 | -50 | -6 | -
| In the haunting backdrop of a war-torn city, where ruins and crumbled walls tell a story of devastation, a poignant close-up frames a young girl. Her face is smudged with ash, a silent testament to the chaos around her. Her eyes glistening with a mix of sorrow and resilience, capturing the raw emotion of a world that has lost its innocence to the ravages of conflict. | -Video 4 | -50 | -6 | -
|
+ A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting. + |
+ + + | +
+ The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from its tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds. + |
+ + + | +
|
+ A street artist, clad in a worn-out denim jacket and a colorful bandana, stands before a vast concrete wall in the heart, holding a can of spray paint, spray-painting a colorful bird on a mottled wall. + |
+ + + | +
+ In the haunting backdrop of a war-torn city, where ruins and crumbled walls tell a story of devastation, a poignant close-up frames a young girl. Her face is smudged with ash, a silent testament to the chaos around her. Her eyes glistening with a mix of sorrow and resilience, capturing the raw emotion of a world that has lost its innocence to the ravages of conflict. + |
+ + + | +