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.
This commit is contained in:
glide-the 2024-08-20 15:04:47 +08:00
parent 2825d9b707
commit e4e612db05
3 changed files with 338 additions and 101 deletions

View File

@ -1,3 +1,4 @@
import gc
import os import os
import tempfile import tempfile
import threading import threading
@ -8,17 +9,29 @@ import numpy as np
import torch import torch
from diffusers import CogVideoXPipeline from diffusers import CogVideoXPipeline
from datetime import datetime, timedelta from datetime import datetime, timedelta
from diffusers.image_processor import VaeImageProcessor
from openai import OpenAI from openai import OpenAI
import spaces
import imageio import imageio
import moviepy.editor as mp import moviepy.editor as mp
from typing import List, Union from typing import List, Union
import PIL import PIL
import utils
dtype = torch.bfloat16
device = "cuda" if torch.cuda.is_available() else "cpu" 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() 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. 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. 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( 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: ) -> str:
""" """
Export the video frames to a video file using imageio lib to Avoid "green screen" issue (for example CogVideoX) 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( response = client.chat.completions.create(
messages=[ messages=[
{"role": "system", "content": sys_prompt}, {"role": "system", "content": sys_prompt},
{ {"role": "user",
"role": "user", "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "a girl is on the beach"'},
"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",
"role": "assistant", "content": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : "A man jogging on a football field"'},
"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": "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",
"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"'},
"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 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",
"role": "assistant", "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: "{text}"'},
"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", model="glm-4-0520",
temperature=0.01, temperature=0.01,
top_p=0.7, top_p=0.7,
stream=False, stream=False,
max_tokens=250, max_tokens=200,
) )
if response.choices: if response.choices:
return response.choices[0].message.content return response.choices[0].message.content
return prompt 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() torch.cuda.empty_cache()
prompt_embeds, _ = pipe.encode_prompt( video_pt = pipe(
prompt=prompt, 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, num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale, guidance_scale=guidance_scale,
prompt_embeds=prompt_embeds, output_type="pt"
negative_prompt_embeds=torch.zeros_like(prompt_embeds), ).frames
).frames[0]
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") timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
video_path = f"./output/{timestamp}.mp4" video_path = f"./output/{timestamp}.mp4"
os.makedirs(os.path.dirname(video_path), exist_ok=True) 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 return video_path
@ -137,7 +191,7 @@ def convert_to_gif(video_path):
clip = mp.VideoFileClip(video_path) clip = mp.VideoFileClip(video_path)
clip = clip.set_fps(8) clip = clip.set_fps(8)
clip = clip.resize(height=240) 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) clip.write_gif(gif_path, fps=8)
return gif_path return gif_path
@ -146,7 +200,8 @@ def delete_old_files():
while True: while True:
now = datetime.now() now = datetime.now()
cutoff = now - timedelta(minutes=10) 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): for filename in os.listdir(output_dir):
file_path = os.path.join(output_dir, filename) file_path = os.path.join(output_dir, filename)
if os.path.isfile(file_path): if os.path.isfile(file_path):
@ -161,11 +216,13 @@ threading.Thread(target=delete_old_files, daemon=True).start()
with gr.Blocks() as demo: with gr.Blocks() as demo:
gr.Markdown(""" gr.Markdown("""
<div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;"> <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
CogVideoX-2B Huggingface Space🤗 CogVideoX-5B Huggingface Space🤗
</div> </div>
<div style="text-align: center;"> <div style="text-align: center;">
<a href="https://huggingface.co/THUDM/CogVideoX-2b">🤗 Model Hub</a> | <a href="https://huggingface.co/THUDM/CogVideoX-2B">🤗 2B Model Hub</a> |
<a href="https://github.com/THUDM/CogVideo">🌐 Github</a> <a href="https://huggingface.co/THUDM/CogVideoX-5B">🤗 5B Model Hub</a> |
<a href="https://github.com/THUDM/CogVideo">🌐 Github</a> |
<a href="https://arxiv.org/pdf/2408.06072">📜 arxiv </a>
</div> </div>
<div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;"> <div style="text-align: center; font-size: 15px; font-weight: bold; color: red; margin-bottom: 20px;">
@ -176,21 +233,22 @@ with gr.Blocks() as demo:
with gr.Row(): with gr.Row():
with gr.Column(): with gr.Column():
prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5) prompt = gr.Textbox(label="Prompt (Less than 200 Words)", placeholder="Enter your prompt here", lines=5)
with gr.Row(): with gr.Row():
gr.Markdown( gr.Markdown(
"✨Upon pressing the enhanced prompt button, we will use [GLM-4 Model](https://github.com/THUDM/GLM-4) to polish the prompt and overwrite the original one." "✨Upon pressing the enhanced prompt button, we will use [GLM-4 Model](https://github.com/THUDM/GLM-4) to polish the prompt and overwrite the original one.")
)
enhance_button = gr.Button("✨ Enhance Prompt(Optional)") enhance_button = gr.Button("✨ Enhance Prompt(Optional)")
with gr.Column(): with gr.Column():
gr.Markdown( gr.Markdown("**Optional Parameters** (default values are recommended)<br>"
"**Optional Parameters** (default values are recommended)<br>" "Increasing the number of inference steps will produce more detailed videos, but it will slow down the process.<br>"
"Turn Inference Steps larger if you want more detailed video, but it will be slower.<br>" "50 steps are recommended for most cases.<br>"
"50 steps are recommended for most cases. will cause 120 seconds for inference.<br>" "For the 5B model, 50 steps will take approximately 350 seconds.")
)
with gr.Row(): with gr.Row():
num_inference_steps = gr.Number(label="Inference Steps", value=50) num_inference_steps = gr.Number(label="Inference Steps", value=50)
guidance_scale = gr.Number(label="Guidance Scale", value=6.0) guidance_scale = gr.Number(label="Guidance Scale", value=6.0)
with gr.Row():
up_scale_model_ckpt = gr.Text(label="UP_SCALE_MODEL_CKPT", value="")
generate_button = gr.Button("🎬 Generate Video") generate_button = gr.Button("🎬 Generate Video")
with gr.Column(): with gr.Column():
@ -200,59 +258,88 @@ with gr.Blocks() as demo:
download_gif_button = gr.File(label="📥 Download GIF", visible=False) download_gif_button = gr.File(label="📥 Download GIF", visible=False)
gr.Markdown(""" gr.Markdown("""
<table border="1" style="width: 100%; text-align: left; margin-top: 20px;"> <table border="0" style="width: 100%; text-align: left; margin-top: 20px;">
<tr> <div style="text-align: center; font-size: 24px; font-weight: bold; margin-bottom: 20px;">
<th>Prompt</th> Demo Videos with 50 Inference Steps and 6.0 Guidance Scale.
<th>Video URL</th> </div>
<th>Inference Steps</th> <tr>
<th>Guidance Scale</th> <td style="width: 25%; vertical-align: top; font-size: 1.2em;">
</tr> <p>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.</p>
<tr> </td>
<td>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.</td> <td style="width: 25%; vertical-align: top;">
<td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/1.mp4">Video 1</a></td> <video src="https://github.com/user-attachments/assets/ea3af39a-3160-4999-90ec-2f7863c5b0e9" width="100%" controls autoplay></video>
<td>50</td> </td>
<td>6</td> <td style="width: 25%; vertical-align: top; font-size: 1.2em;">
</tr> <p>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.</p>
<tr> </td>
<td>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.</td> <td style="width: 25%; vertical-align: top;">
<td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/2.mp4">Video 2</a></td> <video src="https://github.com/user-attachments/assets/9de41efd-d4d1-4095-aeda-246dd834e91d" width="100%" controls autoplay></video>
<td>50</td> </td>
<td>6</td> </tr>
</tr> <tr>
<tr> <td style="width: 25%; vertical-align: top; font-size: 1.2em;">
<td>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.</td> <p>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.</p>
<td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/3.mp4">Video 3</a></td> </td>
<td>50</td> <td style="width: 25%; vertical-align: top;">
<td>6</td> <video src="https://github.com/user-attachments/assets/941d6661-6a8d-4a1b-b912-59606f0b2841" width="100%" controls autoplay></video>
</tr> </td>
<tr> <td style="width: 25%; vertical-align: top; font-size: 1.2em;">
<td>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.</td> <p>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.</p>
<td><a href="https://github.com/THUDM/CogVideo/raw/main/resources/videos/4.mp4">Video 4</a></td> </td>
<td>50</td> <td style="width: 25%; vertical-align: top;">
<td>6</td> <video src="https://github.com/user-attachments/assets/938529c4-91ae-4f60-b96b-3c3947fa63cb" width="100%" controls autoplay></video>
</tr> </td>
</table> </tr>
</table>
""") """)
def generate(prompt, num_inference_steps, guidance_scale, progress=gr.Progress(track_tqdm=True)):
tensor = infer(prompt, num_inference_steps, guidance_scale, progress=progress) def generate(prompt, num_inference_steps, guidance_scale, upscale_ckpt, progress=gr.Progress(track_tqdm=True)):
video_path = save_video(tensor) global UP_SCALE_MODEL
if not UP_SCALE_MODEL:
# Load the upscale model with progress tracking
UP_SCALE_MODEL = load_sd_upscale(upscale_ckpt)
latents = infer(prompt, num_inference_steps, guidance_scale, progress=progress)
if UP_SCALE_MODEL:
latents = upscale_batch_and_concatenate(UP_SCALE_MODEL, latents)
batch_size = latents.shape[0]
batch_video_frames = []
for batch_idx in range(batch_size):
pt_image = latents[batch_idx]
pt_image = torch.stack(
[pt_image[i] for i in range(pt_image.shape[0])]
)
image_np = VaeImageProcessor.pt_to_numpy(pt_image) # (形状为 [49, 512, 480, 3])
image_pil = VaeImageProcessor.numpy_to_pil(image_np)
batch_video_frames.append(image_pil)
video_path = save_video(batch_video_frames[0])
video_update = gr.update(visible=True, value=video_path) video_update = gr.update(visible=True, value=video_path)
gif_path = convert_to_gif(video_path) gif_path = convert_to_gif(video_path)
gif_update = gr.update(visible=True, value=gif_path) gif_update = gr.update(visible=True, value=gif_path)
return video_path, video_update, gif_update return video_path, video_update, gif_update
def enhance_prompt_func(prompt): def enhance_prompt_func(prompt):
return convert_prompt(prompt, retry_times=1) return convert_prompt(prompt, retry_times=1)
generate_button.click( generate_button.click(
generate, generate,
inputs=[prompt, num_inference_steps, guidance_scale], inputs=[prompt, num_inference_steps, guidance_scale, up_scale_model_ckpt],
outputs=[video_output, download_video_button, download_gif_button], outputs=[video_output, download_video_button, download_gif_button]
) )
enhance_button.click(enhance_prompt_func, inputs=[prompt], outputs=[prompt]) enhance_button.click(
enhance_prompt_func,
inputs=[prompt],
outputs=[prompt]
)
if __name__ == "__main__": if __name__ == "__main__":
demo.launch(server_name="127.0.0.1", server_port=7870, share=True) demo.launch(server_port=7870)

144
inference/utils.py Normal file
View File

@ -0,0 +1,144 @@
import math
import torch
import itertools
import safetensors.torch
import tqdm
import logging
logger = logging.getLogger(__file__)
def load_torch_file(ckpt, device=None, dtype=torch.float16):
if device is None:
device = torch.device("cpu")
if ckpt.lower().endswith(".safetensors") or ckpt.lower().endswith(".sft"):
sd = safetensors.torch.load_file(ckpt, device=device.type)
else:
if not 'weights_only' in torch.load.__code__.co_varnames:
logger.warning(
"Warning torch.load doesn't support weights_only on this pytorch version, loading unsafely.")
pl_sd = torch.load(ckpt, map_location=device, weights_only=True)
if "global_step" in pl_sd:
logger.debug(f"Global Step: {pl_sd['global_step']}")
if "state_dict" in pl_sd:
sd = pl_sd["state_dict"]
else:
sd = pl_sd
# Convert all tensors in the state_dict to the specified dtype
sd = {k: v.to(dtype) for k, v in sd.items()}
return sd
def state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=False):
if filter_keys:
out = {}
else:
out = state_dict
for rp in replace_prefix:
replace = list(map(lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp):])),
filter(lambda a: a.startswith(rp), state_dict.keys())))
for x in replace:
w = state_dict.pop(x[0])
out[x[1]] = w
return out
def module_size(module):
module_mem = 0
sd = module.state_dict()
for k in sd:
t = sd[k]
module_mem += t.nelement() * t.element_size()
return module_mem
def get_tiled_scale_steps(width, height, tile_x, tile_y, overlap):
return math.ceil((height / (tile_y - overlap))) * math.ceil((width / (tile_x - overlap)))
@torch.inference_mode()
def tiled_scale_multidim(samples, function, tile=(64, 64), overlap=8, upscale_amount=4, out_channels=3,
output_device="cpu", pbar=None):
dims = len(tile)
print(f"samples dtype:{samples.dtype}")
output = torch.empty(
[samples.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), samples.shape[2:])),
device=output_device)
for b in range(samples.shape[0]):
s = samples[b:b + 1]
out = torch.zeros([s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])),
device=output_device)
out_div = torch.zeros([s.shape[0], out_channels] + list(map(lambda a: round(a * upscale_amount), s.shape[2:])),
device=output_device)
for it in itertools.product(*map(lambda a: range(0, a[0], a[1] - overlap), zip(s.shape[2:], tile))):
s_in = s
upscaled = []
for d in range(dims):
pos = max(0, min(s.shape[d + 2] - overlap, it[d]))
l = min(tile[d], s.shape[d + 2] - pos)
s_in = s_in.narrow(d + 2, pos, l)
upscaled.append(round(pos * upscale_amount))
ps = function(s_in).to(output_device)
mask = torch.ones_like(ps)
feather = round(overlap * upscale_amount)
for t in range(feather):
for d in range(2, dims + 2):
m = mask.narrow(d, t, 1)
m *= ((1.0 / feather) * (t + 1))
m = mask.narrow(d, mask.shape[d] - 1 - t, 1)
m *= ((1.0 / feather) * (t + 1))
o = out
o_d = out_div
for d in range(dims):
o = o.narrow(d + 2, upscaled[d], mask.shape[d + 2])
o_d = o_d.narrow(d + 2, upscaled[d], mask.shape[d + 2])
o += ps * mask
o_d += mask
if pbar is not None:
pbar.update(1)
output[b:b + 1] = out / out_div
return output
def tiled_scale(samples, function, tile_x=64, tile_y=64, overlap=8, upscale_amount=4, out_channels=3,
output_device="cpu", pbar=None):
return tiled_scale_multidim(samples, function, (tile_y, tile_x), overlap, upscale_amount, out_channels,
output_device, pbar)
class ProgressBar:
def __init__(self, total):
self.total = total
self.current = 0
self.b_unit = tqdm.tqdm(
total=total, desc="ProgressBar context index: 0"
)
def update(self, value):
if value > self.total:
value = self.total
self.current = value
if self.b_unit is not None:
self.b_unit.set_description(
"ProgressBar context index: {}".format(self.current)
)
self.b_unit.refresh()
# 更新进度
self.b_unit.update(self.current)

View File

@ -11,4 +11,10 @@ streamlit==1.37.0 # For streamlit web demo
imageio==2.34.2 # For diffusers inference export video imageio==2.34.2 # For diffusers inference export video
imageio-ffmpeg==0.5.1 # For diffusers inference export video imageio-ffmpeg==0.5.1 # For diffusers inference export video
openai==1.40.6 # For prompt refiner openai==1.40.6 # For prompt refiner
moviepy==1.0.3 # For export video moviepy==1.0.3 # For export video
#
safetensors>=0.4.2
spandrel
spaces
tqdm