mirror of
https://github.com/THUDM/CogVideo.git
synced 2025-04-05 19:41:59 +08:00
commit
87ad61b531
@ -14,7 +14,7 @@ Experience the CogVideoX-5B model online at <a href="https://huggingface.co/spac
|
||||
📚 View the <a href="https://arxiv.org/abs/2408.06072" target="_blank">paper</a> and <a href="https://zhipu-ai.feishu.cn/wiki/DHCjw1TrJiTyeukfc9RceoSRnCh" target="_blank">user guide</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
👋 Join our <a href="resources/WECHAT.md" target="_blank">WeChat</a> and <a href="https://discord.gg/B94UfuhN" target="_blank">Discord</a>
|
||||
👋 Join our <a href="resources/WECHAT.md" target="_blank">WeChat</a> and <a href="https://discord.gg/Qqjtj69f" target="_blank">Discord</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
📍 Visit <a href="https://chatglm.cn/video?lang=en?fr=osm_cogvideo">QingYing</a> and <a href="https://open.bigmodel.cn/?utm_campaign=open&_channel_track_key=OWTVNma9">API Platform</a> to experience larger-scale commercial video generation models.
|
||||
@ -279,10 +279,11 @@ works have already been adapted for CogVideoX, and we invite everyone to use the
|
||||
+ [Xorbits Inference](https://github.com/xorbitsai/inference): A powerful and comprehensive distributed inference
|
||||
framework, allowing you to easily deploy your own models or the latest cutting-edge open-source models with just one
|
||||
click.
|
||||
+ [ComfyUI-CogVideoXWrapper](https://github.com/kijai/ComfyUI-CogVideoXWrapper) Use the ComfyUI framework to integrate CogVideoX into your workflow.
|
||||
+ [VideoSys](https://github.com/NUS-HPC-AI-Lab/VideoSys): VideoSys provides a user-friendly, high-performance
|
||||
infrastructure for video generation, with full pipeline support and continuous integration of the latest models and
|
||||
techniques.
|
||||
+ [AutoDL Image](https://www.codewithgpu.com/i/THUDM/CogVideo/CogVideoX-5b-demo): A one-click deployment Huggingface
|
||||
+ [AutoDL Space](https://www.codewithgpu.com/i/THUDM/CogVideo/CogVideoX-5b-demo): A one-click deployment Huggingface
|
||||
Space image provided by community members.
|
||||
+ [Colab Space](https://github.com/camenduru/CogVideoX-5B-jupyter) Run the CogVideoX-5B model using Jupyter Notebook on
|
||||
Colab.
|
||||
@ -336,9 +337,6 @@ This folder contains some tools for model conversion / caption generation, etc.
|
||||
|
||||
+ [convert_weight_sat2hf](tools/convert_weight_sat2hf.py): Convert SAT model weights to Huggingface model weights.
|
||||
+ [caption_demo](tools/caption): Caption tool, a model that understands videos and outputs them in text.
|
||||
+ [AutoDL Mirror](https://www.codewithgpu.com/i/THUDM/CogVideo/CogVideoX-5b-demo): A one-click deployment of Huggingface
|
||||
Space mirror provided by community members.
|
||||
|
||||
## CogVideo(ICLR'23)
|
||||
|
||||
The official repo for the
|
||||
|
@ -14,7 +14,7 @@
|
||||
📚 <a href="https://arxiv.org/abs/2408.06072" target="_blank">論文</a>と<a href="https://zhipu-ai.feishu.cn/wiki/DHCjw1TrJiTyeukfc9RceoSRnCh" target="_blank">使用ドキュメント</a>を表示します。
|
||||
</p>
|
||||
<p align="center">
|
||||
👋 <a href="resources/WECHAT.md" target="_blank">WeChat</a> と <a href="https://discord.gg/B94UfuhN" target="_blank">Discord</a> に参加
|
||||
👋 <a href="resources/WECHAT.md" target="_blank">WeChat</a> と <a href="https://discord.gg/Qqjtj69f" target="_blank">Discord</a> に参加
|
||||
</p>
|
||||
<p align="center">
|
||||
📍 <a href="https://chatglm.cn/video?lang=en?fr=osm_cogvideo">清影</a> と <a href="https://open.bigmodel.cn/?utm_campaign=open&_channel_track_key=OWTVNma9">APIプラットフォーム</a> を訪問して、より大規模な商用ビデオ生成モデルを体験
|
||||
@ -261,6 +261,7 @@ pipe.vae.enable_tiling()
|
||||
|
||||
+ [Xorbits Inference](https://github.com/xorbitsai/inference):
|
||||
強力で包括的な分散推論フレームワークであり、ワンクリックで独自のモデルや最新のオープンソースモデルを簡単にデプロイできます。
|
||||
+ + [ComfyUI-CogVideoXWrapper](https://github.com/kijai/ComfyUI-CogVideoXWrapper) ComfyUIフレームワークを使用して、CogVideoXをワークフローに統合します。
|
||||
+ [VideoSys](https://github.com/NUS-HPC-AI-Lab/VideoSys): VideoSysは、使いやすく高性能なビデオ生成インフラを提供し、最新のモデルや技術を継続的に統合しています。
|
||||
+ [AutoDLイメージ](https://www.codewithgpu.com/i/THUDM/CogVideo/CogVideoX-5b-demo): コミュニティメンバーが提供するHuggingface
|
||||
Spaceイメージのワンクリックデプロイメント。
|
||||
|
@ -15,7 +15,7 @@
|
||||
📚 查看 <a href="https://arxiv.org/abs/2408.06072" target="_blank">论文</a> 和 <a href="https://zhipu-ai.feishu.cn/wiki/DHCjw1TrJiTyeukfc9RceoSRnCh" target="_blank">使用文档</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
👋 加入我们的 <a href="resources/WECHAT.md" target="_blank">微信</a> 和 <a href="https://discord.gg/B94UfuhN" target="_blank">Discord</a>
|
||||
👋 加入我们的 <a href="resources/WECHAT.md" target="_blank">微信</a> 和 <a href="https://discord.gg/Qqjtj69f" target="_blank">Discord</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
📍 前往<a href="https://chatglm.cn/video?fr=osm_cogvideox"> 清影</a> 和 <a href="https://open.bigmodel.cn/?utm_campaign=open&_channel_track_key=OWTVNma9"> API平台</a> 体验更大规模的商业版视频生成模型。
|
||||
@ -249,6 +249,7 @@ pipe.vae.enable_tiling()
|
||||
我们非常欢迎来自社区的贡献,并积极的贡献开源社区。以下作品已经对CogVideoX进行了适配,欢迎大家使用:
|
||||
|
||||
+ [Xorbits Inference](https://github.com/xorbitsai/inference): 性能强大且功能全面的分布式推理框架,轻松一键部署你自己的模型或内置的前沿开源模型。
|
||||
+ [ComfyUI-CogVideoXWrapper](https://github.com/kijai/ComfyUI-CogVideoXWrapper) 使用ComfyUI框架,将CogVideoX加入到你的工作流中。
|
||||
+ [VideoSys](https://github.com/NUS-HPC-AI-Lab/VideoSys): VideoSys 提供了易用且高性能的视频生成基础设施,支持完整的管道,并持续集成最新的模型和技术。
|
||||
+ [AutoDL镜像](https://www.codewithgpu.com/i/THUDM/CogVideo/CogVideoX-5b-demo): 由社区成员提供的一键部署Huggingface
|
||||
Space镜像。
|
||||
|
@ -53,7 +53,6 @@ def generate_video(
|
||||
|
||||
# 3. Enable CPU offload for the model, enable tiling.
|
||||
# turn off if you have multiple GPUs or enough GPU memory(such as H100) and it will cost less time in inference
|
||||
pipe.enable_model_cpu_offload()
|
||||
pipe.enable_sequential_cpu_offload()
|
||||
pipe.vae.enable_slicing()
|
||||
pipe.vae.enable_tiling()
|
||||
|
@ -1,22 +1,27 @@
|
||||
"""
|
||||
The CogVideoX model is designed to generate high-quality videos based on detailed and highly descriptive prompts.
|
||||
The model performs best when provided with refined, granular prompts, which enhance the quality of video generation.
|
||||
This script is designed to assist with transforming simple user inputs into detailed prompts suitable for CogVideoX.
|
||||
It can handle both text-to-video (t2v) and image-to-video (i2v) conversions.
|
||||
|
||||
The CogVideoX model is pre-trained and fine-tuned using longer and more detailed prompts.Therefore, it requires highly granular and detailed prompts as input.This script aims to transform user inputs into executable inputs for CogVideoX, enabling superior video generation.
|
||||
- For text-to-video, simply provide the prompt.
|
||||
- For image-to-video, provide the path to the image file and an optional user input.
|
||||
The image will be encoded and sent as part of the request to Azure OpenAI.
|
||||
|
||||
This step is not mandatory; the model will still function correctly and without errors even if the prompts are not refined using this script. However, we strongly recommend using it to ensure the generation of high-quality videos.
|
||||
### How to run:
|
||||
Run the script for **text-to-video**:
|
||||
$ python convert_demo.py --prompt "A girl riding a bike." --type "t2v"
|
||||
|
||||
Note:
|
||||
Please set the OPENAI_API_KEY and OPENAI_BASE_URL(if needed) environment variable to your OpenAI API key before running this script.
|
||||
|
||||
Run the script:
|
||||
$ python convert_demo.py --prompt "A girl ridding a bike." # Using with OpenAI's API
|
||||
Run the script for **image-to-video**:
|
||||
$ python convert_demo.py --prompt "the cat is running" --type "i2v" --image_path "/path/to/your/image.jpg"
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from openai import OpenAI, AzureOpenAI
|
||||
import base64
|
||||
from mimetypes import guess_type
|
||||
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
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_t2v = """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.
|
||||
There are a few rules to follow:
|
||||
@ -29,54 +34,108 @@ Other times the user will not want modifications , but instead want a new image
|
||||
Video descriptions must have the same num of words as examples below. Extra words will be ignored.
|
||||
"""
|
||||
|
||||
sys_prompt_i2v = """
|
||||
**Objective**: **Give a highly descriptive video caption based on input image and user input. **. As an expert, delve deep into the image with a discerning eye, leveraging rich creativity, meticulous thought. When describing the details of an image, include appropriate dynamic information to ensure that the video caption contains reasonable actions and plots. If user input is not empty, then the caption should be expanded according to the user's input.
|
||||
|
||||
def convert_prompt(prompt: str, retry_times: int = 3):
|
||||
**Note**: The input image is the first frame of the video, and the output video caption should describe the motion starting from the current image. User input is optional and can be empty.
|
||||
|
||||
**Note**: Don't contain camera transitions!!! Don't contain screen switching!!! Don't contain perspective shifts !!!
|
||||
|
||||
**Answering Style**:
|
||||
Answers should be comprehensive, conversational, and use complete sentences. The answer should be in English no matter what the user's input is. Provide context where necessary and maintain a certain tone. Begin directly without introductory phrases like "The image/video showcases" "The photo captures" and more. For example, say "A woman is on a beach", instead of "A woman is depicted in the image".
|
||||
|
||||
**Output Format**: "[highly descriptive image caption here]"
|
||||
|
||||
user input:
|
||||
"""
|
||||
|
||||
|
||||
def image_to_url(image_path):
|
||||
mime_type, _ = guess_type(image_path)
|
||||
if mime_type is None:
|
||||
mime_type = "application/octet-stream"
|
||||
with open(image_path, "rb") as image_file:
|
||||
base64_encoded_data = base64.b64encode(image_file.read()).decode("utf-8")
|
||||
return f"data:{mime_type};base64,{base64_encoded_data}"
|
||||
|
||||
|
||||
def convert_prompt(prompt: str, retry_times: int = 3, type: str = "t2v", image_path: str = None):
|
||||
"""
|
||||
Convert a prompt to a format that can be used by the model for inference
|
||||
"""
|
||||
|
||||
client = OpenAI()
|
||||
text = prompt.strip()
|
||||
## If you using with Azure OpenAI, please uncomment the below line and comment the above line
|
||||
# client = AzureOpenAI(
|
||||
# api_key="",
|
||||
# api_version="",
|
||||
# azure_endpoint=""
|
||||
# )
|
||||
|
||||
text = prompt.strip()
|
||||
for i in range(retry_times):
|
||||
response = client.chat.completions.create(
|
||||
messages=[
|
||||
{"role": "system", "content": f"{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} "',
|
||||
},
|
||||
],
|
||||
model="glm-4-0520", # glm-4-0520 and gpt-4o have be tested
|
||||
temperature=0.01,
|
||||
top_p=0.7,
|
||||
stream=False,
|
||||
max_tokens=250,
|
||||
)
|
||||
if type == "t2v":
|
||||
response = client.chat.completions.create(
|
||||
messages=[
|
||||
{"role": "system", "content": f"{sys_prompt_t2v}"},
|
||||
{
|
||||
"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-plus", # glm-4-plus and gpt-4o have be tested
|
||||
temperature=0.01,
|
||||
top_p=0.7,
|
||||
stream=False,
|
||||
max_tokens=250,
|
||||
)
|
||||
else:
|
||||
response = client.chat.completions.create(
|
||||
model="gpt-4o",
|
||||
messages=[
|
||||
{"role": "system", "content": f"{sys_prompt_i2v}"},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": prompt},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": image_to_url(image_path),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
temperature=0.01,
|
||||
top_p=0.7,
|
||||
stream=False,
|
||||
max_tokens=250,
|
||||
)
|
||||
if response.choices:
|
||||
return response.choices[0].message.content
|
||||
return prompt
|
||||
@ -86,7 +145,9 @@ if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--prompt", type=str, required=True, help="Prompt to convert")
|
||||
parser.add_argument("--retry_times", type=int, default=3, help="Number of times to retry the conversion")
|
||||
parser.add_argument("--type", type=str, default="t2v", help="Type of conversion (t2v or i2v)")
|
||||
parser.add_argument("--image_path", type=str, default=None, help="Path to the image file")
|
||||
args = parser.parse_args()
|
||||
|
||||
converted_prompt = convert_prompt(args.prompt, args.retry_times)
|
||||
converted_prompt = convert_prompt(args.prompt, args.retry_times, args.type, args.image_path)
|
||||
print(converted_prompt)
|
||||
|
@ -162,7 +162,6 @@ class SATVideoDiffusionEngine(nn.Module):
|
||||
kwargs = {"timesteps": len(z[n * n_samples : (n + 1) * n_samples])}
|
||||
else:
|
||||
kwargs = {}
|
||||
use_cp = False
|
||||
out = self.first_stage_model.decode(z[n * n_samples : (n + 1) * n_samples], **kwargs)
|
||||
all_out.append(out)
|
||||
out = torch.cat(all_out, dim=0)
|
||||
@ -176,8 +175,6 @@ class SATVideoDiffusionEngine(nn.Module):
|
||||
x = x.permute(0, 2, 1, 3, 4).contiguous()
|
||||
return x * self.scale_factor # already encoded
|
||||
|
||||
use_cp = False
|
||||
|
||||
n_samples = default(self.en_and_decode_n_samples_a_time, x.shape[0])
|
||||
n_rounds = math.ceil(x.shape[0] / n_samples)
|
||||
all_out = []
|
||||
@ -305,11 +302,29 @@ class SATVideoDiffusionEngine(nn.Module):
|
||||
|
||||
samples = self.sample(c, shape=z.shape[1:], uc=uc, batch_size=N, **sampling_kwargs) # b t c h w
|
||||
samples = samples.permute(0, 2, 1, 3, 4).contiguous()
|
||||
if only_log_video_latents:
|
||||
latents = 1.0 / self.scale_factor * samples
|
||||
log["latents"] = latents
|
||||
else:
|
||||
samples = self.decode_first_stage(samples).to(torch.float32)
|
||||
if self.noised_image_input:
|
||||
image = x[:, :, 0:1]
|
||||
image = self.add_noise_to_first_frame(image)
|
||||
image = self.encode_first_stage(image, batch)
|
||||
image = image.permute(0, 2, 1, 3, 4).contiguous()
|
||||
image = torch.concat([image, torch.zeros_like(z[:, 1:])], dim=1)
|
||||
c["concat"] = image
|
||||
uc["concat"] = image
|
||||
samples = self.sample(c, shape=z.shape[1:], uc=uc, batch_size=N, **sampling_kwargs) # b t c h w
|
||||
samples = samples.permute(0, 2, 1, 3, 4).contiguous()
|
||||
log["samples"] = samples
|
||||
if only_log_video_latents:
|
||||
latents = 1.0 / self.scale_factor * samples
|
||||
log["latents"] = latents
|
||||
else:
|
||||
samples = self.decode_first_stage(samples).to(torch.float32)
|
||||
samples = samples.permute(0, 2, 1, 3, 4).contiguous()
|
||||
log["samples"] = samples
|
||||
else:
|
||||
if only_log_video_latents:
|
||||
latents = 1.0 / self.scale_factor * samples
|
||||
log["latents"] = latents
|
||||
else:
|
||||
samples = self.decode_first_stage(samples).to(torch.float32)
|
||||
samples = samples.permute(0, 2, 1, 3, 4).contiguous()
|
||||
log["samples"] = samples
|
||||
return log
|
||||
|
@ -155,6 +155,25 @@ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
|
||||
return emb
|
||||
|
||||
|
||||
class Basic2DPositionEmbeddingMixin(BaseMixin):
|
||||
def __init__(self, height, width, compressed_num_frames, hidden_size, text_length=0):
|
||||
super().__init__()
|
||||
self.height = height
|
||||
self.width = width
|
||||
self.spatial_length = height * width
|
||||
self.pos_embedding = nn.Parameter(
|
||||
torch.zeros(1, int(text_length + self.spatial_length), int(hidden_size)), requires_grad=False
|
||||
)
|
||||
|
||||
def position_embedding_forward(self, position_ids, **kwargs):
|
||||
return self.pos_embedding
|
||||
|
||||
def reinit(self, parent_model=None):
|
||||
del self.transformer.position_embeddings
|
||||
pos_embed = get_2d_sincos_pos_embed(self.pos_embedding.shape[-1], self.height, self.width)
|
||||
self.pos_embedding.data[:, -self.spatial_length :].copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
|
||||
|
||||
|
||||
class Basic3DPositionEmbeddingMixin(BaseMixin):
|
||||
def __init__(
|
||||
self,
|
||||
@ -240,10 +259,10 @@ class Rotary3DPositionEmbeddingMixin(BaseMixin):
|
||||
text_length,
|
||||
theta=10000,
|
||||
rot_v=False,
|
||||
learnable_pos_embed=False,
|
||||
):
|
||||
super().__init__()
|
||||
self.rot_v = rot_v
|
||||
self.text_length = text_length
|
||||
|
||||
dim_t = hidden_size_head // 4
|
||||
dim_h = hidden_size_head // 8 * 3
|
||||
@ -274,6 +293,13 @@ class Rotary3DPositionEmbeddingMixin(BaseMixin):
|
||||
self.register_buffer("freqs_sin", freqs_sin)
|
||||
self.register_buffer("freqs_cos", freqs_cos)
|
||||
|
||||
self.text_length = text_length
|
||||
if learnable_pos_embed:
|
||||
num_patches = height * width * compressed_num_frames + text_length
|
||||
self.pos_embedding = nn.Parameter(torch.zeros(1, num_patches, int(hidden_size)), requires_grad=True)
|
||||
else:
|
||||
self.pos_embedding = None
|
||||
|
||||
def rotary(self, t, **kwargs):
|
||||
seq_len = t.shape[2]
|
||||
freqs_cos = self.freqs_cos[:seq_len].unsqueeze(0).unsqueeze(0)
|
||||
@ -362,7 +388,6 @@ class FinalLayerMixin(BaseMixin):
|
||||
|
||||
def final_forward(self, logits, **kwargs):
|
||||
x, emb = logits[:, kwargs["text_length"] :, :], kwargs["emb"] # x:(b,(t n),d)
|
||||
|
||||
shift, scale = self.adaLN_modulation(emb).chunk(2, dim=1)
|
||||
x = modulate(self.norm_final(x), shift, scale)
|
||||
x = self.linear(x)
|
||||
@ -458,6 +483,7 @@ class AdaLNMixin(BaseMixin):
|
||||
# hidden_states (b,(n_t+t*n_i),d)
|
||||
text_hidden_states = hidden_states[:, :text_length] # (b,n,d)
|
||||
img_hidden_states = hidden_states[:, text_length:] # (b,(t n),d)
|
||||
|
||||
layer = self.transformer.layers[kwargs["layer_id"]]
|
||||
adaLN_modulation = self.adaLN_modulations[kwargs["layer_id"]]
|
||||
|
||||
@ -492,7 +518,6 @@ class AdaLNMixin(BaseMixin):
|
||||
attention_output = layer.attention(attention_input, mask, **kwargs)
|
||||
text_attention_output = attention_output[:, :text_length] # (b,n,d)
|
||||
img_attention_output = attention_output[:, text_length:] # (b,(t n),d)
|
||||
|
||||
if self.transformer.layernorm_order == "sandwich":
|
||||
text_attention_output = layer.third_layernorm(text_attention_output)
|
||||
img_attention_output = layer.third_layernorm(img_attention_output)
|
||||
@ -748,6 +773,15 @@ class DiffusionTransformer(BaseModel):
|
||||
b, t, d, h, w = x.shape
|
||||
if x.dtype != self.dtype:
|
||||
x = x.to(self.dtype)
|
||||
|
||||
# This is not use in inference
|
||||
if "concat_images" in kwargs and kwargs["concat_images"] is not None:
|
||||
if kwargs["concat_images"].shape[0] != x.shape[0]:
|
||||
concat_images = kwargs["concat_images"].repeat(2, 1, 1, 1, 1)
|
||||
else:
|
||||
concat_images = kwargs["concat_images"]
|
||||
x = torch.cat([x, concat_images], dim=2)
|
||||
|
||||
assert (y is not None) == (
|
||||
self.num_classes is not None
|
||||
), "must specify y if and only if the model is class-conditional"
|
||||
@ -768,5 +802,4 @@ class DiffusionTransformer(BaseModel):
|
||||
|
||||
kwargs["input_ids"] = kwargs["position_ids"] = kwargs["attention_mask"] = torch.ones((1, 1)).to(x.dtype)
|
||||
output = super().forward(**kwargs)[0]
|
||||
|
||||
return output
|
||||
|
@ -11,6 +11,7 @@ import numpy as np
|
||||
from einops import rearrange
|
||||
import torchvision.transforms as TT
|
||||
|
||||
|
||||
from sat.model.base_model import get_model
|
||||
from sat.training.model_io import load_checkpoint
|
||||
from sat import mpu
|
||||
@ -19,6 +20,7 @@ from diffusion_video import SATVideoDiffusionEngine
|
||||
from arguments import get_args
|
||||
from torchvision.transforms.functional import center_crop, resize
|
||||
from torchvision.transforms import InterpolationMode
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def read_from_cli():
|
||||
@ -132,6 +134,11 @@ def sampling_main(args, model_cls):
|
||||
|
||||
image_size = [480, 720]
|
||||
|
||||
if args.image2video:
|
||||
chained_trainsforms = []
|
||||
chained_trainsforms.append(TT.ToTensor())
|
||||
transform = TT.Compose(chained_trainsforms)
|
||||
|
||||
sample_func = model.sample
|
||||
T, H, W, C, F = args.sampling_num_frames, image_size[0], image_size[1], args.latent_channels, 8
|
||||
num_samples = [1]
|
||||
@ -139,10 +146,21 @@ def sampling_main(args, model_cls):
|
||||
device = model.device
|
||||
with torch.no_grad():
|
||||
for text, cnt in tqdm(data_iter):
|
||||
# reload model on GPU
|
||||
model.to(device)
|
||||
print("rank:", rank, "start to process", text, cnt)
|
||||
# TODO: broadcast image2video
|
||||
if args.image2video:
|
||||
text, image_path = text.split("@@")
|
||||
assert os.path.exists(image_path), image_path
|
||||
image = Image.open(image_path).convert("RGB")
|
||||
image = transform(image).unsqueeze(0).to("cuda")
|
||||
image = resize_for_rectangle_crop(image, image_size, reshape_mode="center").unsqueeze(0)
|
||||
image = image * 2.0 - 1.0
|
||||
image = image.unsqueeze(2).to(torch.bfloat16)
|
||||
image = model.encode_first_stage(image, None)
|
||||
image = image.permute(0, 2, 1, 3, 4).contiguous()
|
||||
pad_shape = (image.shape[0], T - 1, C, H // F, W // F)
|
||||
image = torch.concat([image, torch.zeros(pad_shape).to(image.device).to(image.dtype)], dim=1)
|
||||
else:
|
||||
image = None
|
||||
|
||||
value_dict = {
|
||||
"prompt": text,
|
||||
"negative_prompt": "",
|
||||
@ -168,6 +186,11 @@ def sampling_main(args, model_cls):
|
||||
for k in c:
|
||||
if not k == "crossattn":
|
||||
c[k], uc[k] = map(lambda y: y[k][: math.prod(num_samples)].to("cuda"), (c, uc))
|
||||
|
||||
if args.image2video and image is not None:
|
||||
c["concat"] = image
|
||||
uc["concat"] = image
|
||||
|
||||
for index in range(args.batch_size):
|
||||
# reload model on GPU
|
||||
model.to(device)
|
||||
|
@ -2,17 +2,9 @@ from typing import List, Optional, Union
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from omegaconf import ListConfig
|
||||
import math
|
||||
|
||||
from ...modules.diffusionmodules.sampling import VideoDDIMSampler, VPSDEDPMPP2MSampler
|
||||
from ...util import append_dims, instantiate_from_config
|
||||
from ...modules.autoencoding.lpips.loss.lpips import LPIPS
|
||||
|
||||
# import rearrange
|
||||
from einops import rearrange
|
||||
import random
|
||||
from sat import mpu
|
||||
|
||||
|
||||
@ -107,6 +99,9 @@ class VideoDiffusionLoss(StandardDiffusionLoss):
|
||||
(1 - alphas_cumprod_sqrt**2) ** 0.5, input.ndim
|
||||
)
|
||||
|
||||
if "concat_images" in batch.keys():
|
||||
additional_model_inputs["concat_images"] = batch["concat_images"]
|
||||
|
||||
model_output = denoiser(network, noised_input, alphas_cumprod_sqrt, cond, **additional_model_inputs)
|
||||
w = append_dims(1 / (1 - alphas_cumprod_sqrt**2), input.ndim) # v-pred
|
||||
|
||||
|
@ -807,7 +807,7 @@ class ContextParallelEncoder3D(nn.Module):
|
||||
kernel_size=3,
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
def forward(self, x, **kwargs):
|
||||
# timestep embedding
|
||||
temb = None
|
||||
|
||||
@ -948,7 +948,7 @@ class ContextParallelDecoder3D(nn.Module):
|
||||
kernel_size=3,
|
||||
)
|
||||
|
||||
def forward(self, z, clear_fake_cp_cache=True):
|
||||
def forward(self, z, clear_fake_cp_cache=True, **kwargs):
|
||||
self.last_z_shape = z.shape
|
||||
|
||||
# timestep embedding
|
||||
|
Loading…
x
Reference in New Issue
Block a user