Spaces:
Paused
Paused
Commit
·
3ecd0c7
0
Parent(s):
Duplicate from YueMafighting/FollowYourPose
Browse filesCo-authored-by: Jack Ma <[email protected]>
- .gitattributes +34 -0
- .gitignore +5 -0
- .gitmodules +0 -0
- .pre-commit-config.yaml +37 -0
- .style.yapf +5 -0
- Dockerfile +63 -0
- FollowYourPose/__pycache__/test_followyourpose.cpython-38.pyc +0 -0
- FollowYourPose/configs/pose_sample.yaml +28 -0
- FollowYourPose/followyourpose/__pycache__/util.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/data/__pycache__/dataset.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/data/__pycache__/hdvila.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/data/hdvila.py +245 -0
- FollowYourPose/followyourpose/models/__pycache__/attention.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/models/__pycache__/resnet.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/models/__pycache__/unet.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/models/__pycache__/unet_blocks.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/models/attention.py +375 -0
- FollowYourPose/followyourpose/models/resnet.py +209 -0
- FollowYourPose/followyourpose/models/unet.py +571 -0
- FollowYourPose/followyourpose/models/unet_blocks.py +631 -0
- FollowYourPose/followyourpose/pipelines/__pycache__/pipeline_followyourpose.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/pipelines/__pycache__/pipeline_tuneavideo.cpython-38.pyc +0 -0
- FollowYourPose/followyourpose/pipelines/pipeline_followyourpose.py +442 -0
- FollowYourPose/followyourpose/util.py +84 -0
- FollowYourPose/test_followyourpose.py +186 -0
- LICENSE +21 -0
- README.md +13 -0
- __pycache__/example.cpython-38.pyc +0 -0
- __pycache__/inference_followyourpose.cpython-38.pyc +0 -0
- app.py +174 -0
- docs/OpenSans-Regular.ttf +0 -0
- example.py +85 -0
- inference_followyourpose.py +81 -0
- packages.txt +1 -0
- requirements.txt +112 -0
- style.css +3 -0
.gitattributes
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
trash/*
|
| 2 |
+
tmp
|
| 3 |
+
gradio_cached_examples
|
| 4 |
+
|
| 5 |
+
./FollowYourPose/checkpoints
|
.gitmodules
ADDED
|
File without changes
|
.pre-commit-config.yaml
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
exclude: patch
|
| 2 |
+
repos:
|
| 3 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 4 |
+
rev: v4.2.0
|
| 5 |
+
hooks:
|
| 6 |
+
- id: check-executables-have-shebangs
|
| 7 |
+
- id: check-json
|
| 8 |
+
- id: check-merge-conflict
|
| 9 |
+
- id: check-shebang-scripts-are-executable
|
| 10 |
+
- id: check-toml
|
| 11 |
+
- id: check-yaml
|
| 12 |
+
- id: double-quote-string-fixer
|
| 13 |
+
- id: end-of-file-fixer
|
| 14 |
+
- id: mixed-line-ending
|
| 15 |
+
args: ['--fix=lf']
|
| 16 |
+
- id: requirements-txt-fixer
|
| 17 |
+
- id: trailing-whitespace
|
| 18 |
+
- repo: https://github.com/myint/docformatter
|
| 19 |
+
rev: v1.4
|
| 20 |
+
hooks:
|
| 21 |
+
- id: docformatter
|
| 22 |
+
args: ['--in-place']
|
| 23 |
+
- repo: https://github.com/pycqa/isort
|
| 24 |
+
rev: 5.12.0
|
| 25 |
+
hooks:
|
| 26 |
+
- id: isort
|
| 27 |
+
- repo: https://github.com/pre-commit/mirrors-mypy
|
| 28 |
+
rev: v0.991
|
| 29 |
+
hooks:
|
| 30 |
+
- id: mypy
|
| 31 |
+
args: ['--ignore-missing-imports']
|
| 32 |
+
additional_dependencies: ['types-python-slugify']
|
| 33 |
+
- repo: https://github.com/google/yapf
|
| 34 |
+
rev: v0.32.0
|
| 35 |
+
hooks:
|
| 36 |
+
- id: yapf
|
| 37 |
+
args: ['--parallel', '--in-place']
|
.style.yapf
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[style]
|
| 2 |
+
based_on_style = pep8
|
| 3 |
+
blank_line_before_nested_class_or_def = false
|
| 4 |
+
spaces_before_comment = 2
|
| 5 |
+
split_before_logical_operator = true
|
Dockerfile
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM nvidia/cuda:11.7.1-cudnn8-devel-ubuntu22.04
|
| 2 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 3 |
+
RUN apt-get update && \
|
| 4 |
+
apt-get upgrade -y && \
|
| 5 |
+
apt-get install -y --no-install-recommends \
|
| 6 |
+
git \
|
| 7 |
+
zip \
|
| 8 |
+
unzip \
|
| 9 |
+
git-lfs \
|
| 10 |
+
wget \
|
| 11 |
+
curl \
|
| 12 |
+
# ffmpeg \
|
| 13 |
+
ffmpeg \
|
| 14 |
+
x264 \
|
| 15 |
+
# python build dependencies \
|
| 16 |
+
build-essential \
|
| 17 |
+
libssl-dev \
|
| 18 |
+
zlib1g-dev \
|
| 19 |
+
libbz2-dev \
|
| 20 |
+
libreadline-dev \
|
| 21 |
+
libsqlite3-dev \
|
| 22 |
+
libncursesw5-dev \
|
| 23 |
+
xz-utils \
|
| 24 |
+
tk-dev \
|
| 25 |
+
libxml2-dev \
|
| 26 |
+
libxmlsec1-dev \
|
| 27 |
+
libffi-dev \
|
| 28 |
+
liblzma-dev && \
|
| 29 |
+
apt-get clean && \
|
| 30 |
+
rm -rf /var/lib/apt/lists/*
|
| 31 |
+
# RUN apt-get update && \
|
| 32 |
+
# apt-get install zip
|
| 33 |
+
# RUN wget https://github.com/ChenyangQiQi/FateZero/releases/download/v0.0.1/style.zip && unzip style.zip
|
| 34 |
+
RUN useradd -m -u 1000 user
|
| 35 |
+
USER user
|
| 36 |
+
ENV HOME=/home/user \
|
| 37 |
+
PATH=/home/user/.local/bin:${PATH}
|
| 38 |
+
WORKDIR ${HOME}/app
|
| 39 |
+
|
| 40 |
+
RUN curl https://pyenv.run | bash
|
| 41 |
+
ENV PATH=${HOME}/.pyenv/shims:${HOME}/.pyenv/bin:${PATH}
|
| 42 |
+
ENV PYTHON_VERSION=3.10.9
|
| 43 |
+
RUN pyenv install ${PYTHON_VERSION} && \
|
| 44 |
+
pyenv global ${PYTHON_VERSION} && \
|
| 45 |
+
pyenv rehash && \
|
| 46 |
+
pip install --no-cache-dir -U pip setuptools wheel
|
| 47 |
+
|
| 48 |
+
RUN pip install --no-cache-dir -U torch==1.13.1 torchvision==0.14.1
|
| 49 |
+
COPY --chown=1000 requirements.txt /tmp/requirements.txt
|
| 50 |
+
RUN pip install --no-cache-dir -U -r /tmp/requirements.txt
|
| 51 |
+
|
| 52 |
+
COPY --chown=1000 . ${HOME}/app
|
| 53 |
+
RUN ls -a
|
| 54 |
+
RUN cd ./FateZero/ckpt && bash download.sh
|
| 55 |
+
RUN cd ./FateZero/data && bash download.sh
|
| 56 |
+
ENV PYTHONPATH=${HOME}/app \
|
| 57 |
+
PYTHONUNBUFFERED=1 \
|
| 58 |
+
GRADIO_ALLOW_FLAGGING=never \
|
| 59 |
+
GRADIO_NUM_PORTS=1 \
|
| 60 |
+
GRADIO_SERVER_NAME=0.0.0.0 \
|
| 61 |
+
GRADIO_THEME=huggingface \
|
| 62 |
+
SYSTEM=spaces
|
| 63 |
+
CMD ["python", "app_fatezero.py"]
|
FollowYourPose/__pycache__/test_followyourpose.cpython-38.pyc
ADDED
|
Binary file (4.99 kB). View file
|
|
|
FollowYourPose/configs/pose_sample.yaml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pretrained_model_path: "./FollowYourPose/checkpoints/stable-diffusion-v1-4"
|
| 2 |
+
output_dir: "output"
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
validation_data:
|
| 6 |
+
prompts:
|
| 7 |
+
- "Stormtrooper on the sea"
|
| 8 |
+
- "Astronaut on the beach"
|
| 9 |
+
video_length: 8
|
| 10 |
+
width: 512
|
| 11 |
+
height: 512
|
| 12 |
+
num_inference_steps: 50
|
| 13 |
+
guidance_scale: 12.5
|
| 14 |
+
use_inv_latent: False
|
| 15 |
+
num_inv_steps: 50
|
| 16 |
+
dataset_set: "val"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
train_batch_size: 1
|
| 21 |
+
validation_steps: 100
|
| 22 |
+
skeleton_path: ' '
|
| 23 |
+
resume_from_checkpoint: './FollowYourPose/checkpoints/followyourpose_checkpoint-1000'
|
| 24 |
+
|
| 25 |
+
seed: 33
|
| 26 |
+
mixed_precision: 'no'
|
| 27 |
+
gradient_checkpointing: False
|
| 28 |
+
enable_xformers_memory_efficient_attention: True
|
FollowYourPose/followyourpose/__pycache__/util.cpython-38.pyc
ADDED
|
Binary file (2.92 kB). View file
|
|
|
FollowYourPose/followyourpose/data/__pycache__/dataset.cpython-38.pyc
ADDED
|
Binary file (1.5 kB). View file
|
|
|
FollowYourPose/followyourpose/data/__pycache__/hdvila.cpython-38.pyc
ADDED
|
Binary file (177 Bytes). View file
|
|
|
FollowYourPose/followyourpose/data/hdvila.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# import os
|
| 2 |
+
# import random
|
| 3 |
+
# from abc import abstractmethod
|
| 4 |
+
# import math
|
| 5 |
+
# import pandas as pd
|
| 6 |
+
# import av
|
| 7 |
+
# import cv2
|
| 8 |
+
# import decord
|
| 9 |
+
# import numpy as np
|
| 10 |
+
# import torch
|
| 11 |
+
# from PIL import Image
|
| 12 |
+
# from torch.utils.data import Dataset
|
| 13 |
+
# from torchvision import transforms
|
| 14 |
+
# from decord import VideoReader, cpu
|
| 15 |
+
# import torchvision.transforms._transforms_video as transforms_video
|
| 16 |
+
# from torchvision.transforms.functional import to_tensor
|
| 17 |
+
# from collections import OrderedDict
|
| 18 |
+
# import time
|
| 19 |
+
# import csv
|
| 20 |
+
|
| 21 |
+
# class HDVilaDataset(Dataset):
|
| 22 |
+
# """
|
| 23 |
+
# HDVila Dataset.
|
| 24 |
+
# Assumes webvid data is structured as follows.
|
| 25 |
+
# HDVila/
|
| 26 |
+
# part_N/ # 0-10
|
| 27 |
+
# video_clips/ ($page_dir)
|
| 28 |
+
# 1.mp4 (videoid.mp4)
|
| 29 |
+
# ...
|
| 30 |
+
# 5000.mp4
|
| 31 |
+
# ...
|
| 32 |
+
# """
|
| 33 |
+
# def __init__(self,
|
| 34 |
+
# video_path,
|
| 35 |
+
# width=512,
|
| 36 |
+
# height=512,
|
| 37 |
+
# n_sample_frames=8,
|
| 38 |
+
# dataset_set="train",
|
| 39 |
+
# prompt=None,
|
| 40 |
+
# sample_frame_rate=2,
|
| 41 |
+
# sample_start_idx=0,
|
| 42 |
+
# accelerator=None,
|
| 43 |
+
# ):
|
| 44 |
+
|
| 45 |
+
# try:
|
| 46 |
+
# host_gpu_num = accelerator.num_processes
|
| 47 |
+
# host_num = 1
|
| 48 |
+
# all_rank = host_gpu_num * host_num
|
| 49 |
+
# global_rank = accelerator.local_process_index
|
| 50 |
+
# except:
|
| 51 |
+
# pass
|
| 52 |
+
# print('dataset rank:', global_rank, ' / ',all_rank, ' ')
|
| 53 |
+
|
| 54 |
+
# self.data_dir = '/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m'
|
| 55 |
+
# if dataset_set=='train':
|
| 56 |
+
# self.text_name = 'caption_rm2048_train.csv'
|
| 57 |
+
# else:
|
| 58 |
+
# self.text_name = 'caption_2048_val_new.csv'
|
| 59 |
+
# self.meta_path = os.path.join(self.data_dir, self.text_name)
|
| 60 |
+
# # text_name = 'caption_2048_val_new.csv'
|
| 61 |
+
|
| 62 |
+
# spatial_transform = 'resize_center_crop'
|
| 63 |
+
# resolution=width
|
| 64 |
+
# load_raw_resolution=True
|
| 65 |
+
# # frame_stride=2
|
| 66 |
+
# video_length= n_sample_frames
|
| 67 |
+
# fps_max=None
|
| 68 |
+
# load_resize_keep_ratio=False
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# self.global_rank = global_rank
|
| 73 |
+
# self.all_rank = all_rank
|
| 74 |
+
# # self.subsample = subsample
|
| 75 |
+
# self.video_length = video_length
|
| 76 |
+
# self.resolution = [resolution, resolution] if isinstance(resolution, int) else resolution
|
| 77 |
+
# self.frame_stride = sample_frame_rate
|
| 78 |
+
# self.load_raw_resolution = load_raw_resolution
|
| 79 |
+
# self.fps_max = fps_max
|
| 80 |
+
# self.load_resize_keep_ratio = load_resize_keep_ratio
|
| 81 |
+
# print('start load meta data')
|
| 82 |
+
# self._load_metadata()
|
| 83 |
+
# print('load meta data done!!!')
|
| 84 |
+
# if spatial_transform is not None:
|
| 85 |
+
# if spatial_transform == "random_crop":
|
| 86 |
+
# self.spatial_transform = transforms_video.RandomCropVideo(crop_resolution)
|
| 87 |
+
# elif spatial_transform == "resize_center_crop":
|
| 88 |
+
# assert(self.resolution[0] == self.resolution[1])
|
| 89 |
+
# self.spatial_transform = transforms.Compose([
|
| 90 |
+
# transforms.Resize(resolution),
|
| 91 |
+
# transforms_video.CenterCropVideo(resolution),
|
| 92 |
+
# ])
|
| 93 |
+
# elif spatial_transform == "center_crop":
|
| 94 |
+
# self.spatial_transform = transforms_video.CenterCropVideo(resolution)
|
| 95 |
+
# else:
|
| 96 |
+
# raise NotImplementedError
|
| 97 |
+
# else:
|
| 98 |
+
# self.spatial_transform = None
|
| 99 |
+
|
| 100 |
+
# def _load_metadata(self):
|
| 101 |
+
# # clip_id frame_id caption
|
| 102 |
+
# last_clip_id = ''
|
| 103 |
+
# self.metadata = []
|
| 104 |
+
# start_time = time.time()
|
| 105 |
+
# caption_path = self.meta_path
|
| 106 |
+
# count=-1
|
| 107 |
+
# total_count = 8854264 #8856312 - 2048
|
| 108 |
+
|
| 109 |
+
# with open(caption_path, 'r',encoding="utf-8") as csvfile: #41s
|
| 110 |
+
# reader = csv.DictReader(csvfile)
|
| 111 |
+
# for row in reader:
|
| 112 |
+
# if row['clip_id'] != last_clip_id:
|
| 113 |
+
# count+=1
|
| 114 |
+
# if count >= (total_count // self.all_rank)*self.all_rank: # drop last
|
| 115 |
+
# break
|
| 116 |
+
# last_clip_id = row['clip_id']
|
| 117 |
+
# if count % self.all_rank == self.global_rank:
|
| 118 |
+
# self.metadata.append([('%02d'%int(row['part_id']))+row['clip_id']])
|
| 119 |
+
# self.metadata[-1].append([row['caption']])
|
| 120 |
+
# else:
|
| 121 |
+
# if count % self.all_rank == self.global_rank:
|
| 122 |
+
# self.metadata[-1][-1].append(row['caption'])
|
| 123 |
+
# # caption_data = pd.read_csv(caption_path) # use time 26+264s
|
| 124 |
+
|
| 125 |
+
# # for index,row in caption_data.iterrows():
|
| 126 |
+
# # if row['clip_id'] != last_clip_id:
|
| 127 |
+
# # last_clip_id = row['clip_id']
|
| 128 |
+
# # meta_data[('%02d'%part_id)+row['clip_id']] = [row['caption']]
|
| 129 |
+
# # else:
|
| 130 |
+
# # meta_data[('%02d'%part_id)+row['clip_id']].append(row['caption'])
|
| 131 |
+
# end_time = time.time()
|
| 132 |
+
# print('load %d - %d items use time: %.1f;' % (len(self.metadata), count, end_time-start_time))
|
| 133 |
+
# # self.metadata=meta_data
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# def _get_video_path(self, sample):
|
| 137 |
+
# part_id = int(sample[0][:2])
|
| 138 |
+
# clip_id = sample[0][2:]
|
| 139 |
+
# video_path = os.path.join(self.data_dir,'part_%d' % part_id, 'video_clips', clip_id)
|
| 140 |
+
# return video_path
|
| 141 |
+
|
| 142 |
+
# def __getitem__(self, index):
|
| 143 |
+
# while True:
|
| 144 |
+
|
| 145 |
+
# index = index % len(self.metadata)
|
| 146 |
+
# sample = self.metadata[index]
|
| 147 |
+
# video_path = self._get_video_path(sample)
|
| 148 |
+
|
| 149 |
+
# try:
|
| 150 |
+
# if self.load_raw_resolution:
|
| 151 |
+
# video_reader = VideoReader(video_path, ctx=cpu(0))
|
| 152 |
+
# elif self.load_resize_keep_ratio:
|
| 153 |
+
# # resize scale is according to the short side
|
| 154 |
+
# h, w, c = VideoReader(video_path, ctx=cpu(0))[0].shape
|
| 155 |
+
# if h < w:
|
| 156 |
+
# scale = h / self.resolution[0]
|
| 157 |
+
# else:
|
| 158 |
+
# scale = w / self.resolution[1]
|
| 159 |
+
|
| 160 |
+
# h = math.ceil(h / scale)
|
| 161 |
+
# w = math.ceil(w / scale)
|
| 162 |
+
# video_reader = VideoReader(video_path, ctx=cpu(0), width=w, height=h)
|
| 163 |
+
# else:
|
| 164 |
+
# video_reader = VideoReader(video_path, ctx=cpu(0), width=self.resolution[1], height=self.resolution[0])
|
| 165 |
+
# if len(video_reader) < self.video_length:
|
| 166 |
+
# print(f"video length ({len(video_reader)}) is smaller than target length({self.video_length})")
|
| 167 |
+
# index += 1
|
| 168 |
+
# continue
|
| 169 |
+
# else:
|
| 170 |
+
# pass
|
| 171 |
+
# except:
|
| 172 |
+
# index += 1
|
| 173 |
+
# print(f"Load video failed! path = {video_path}")
|
| 174 |
+
# continue
|
| 175 |
+
# fps_ori = video_reader.get_avg_fps()
|
| 176 |
+
|
| 177 |
+
# fs = self.frame_stride
|
| 178 |
+
# allf = len(video_reader)
|
| 179 |
+
# if self.frame_stride != 1:
|
| 180 |
+
# all_frames = list(range(0, len(video_reader), self.frame_stride))
|
| 181 |
+
# if len(all_frames) < self.video_length:
|
| 182 |
+
# fs = len(video_reader) // self.video_length
|
| 183 |
+
# assert(fs != 0)
|
| 184 |
+
# all_frames = list(range(0, len(video_reader), fs))
|
| 185 |
+
# else:
|
| 186 |
+
# all_frames = list(range(len(video_reader)))
|
| 187 |
+
|
| 188 |
+
# # select a random clip
|
| 189 |
+
# rand_idx = random.randint(0, len(all_frames) - self.video_length)
|
| 190 |
+
# frame_indices = all_frames[rand_idx:rand_idx+self.video_length]
|
| 191 |
+
# try:
|
| 192 |
+
# frames = video_reader.get_batch(frame_indices)
|
| 193 |
+
# break
|
| 194 |
+
# except:
|
| 195 |
+
# print(f"Get frames failed! path = {video_path}")
|
| 196 |
+
# index += 1
|
| 197 |
+
# continue
|
| 198 |
+
|
| 199 |
+
# assert(frames.shape[0] == self.video_length),f'{len(frames)}, self.video_length={self.video_length}'
|
| 200 |
+
# frames = torch.tensor(frames.asnumpy()).permute(3, 0, 1, 2).float() # [t,h,w,c] -> [c,t,h,w]
|
| 201 |
+
|
| 202 |
+
# if self.spatial_transform is not None:
|
| 203 |
+
# frames = self.spatial_transform(frames)
|
| 204 |
+
# assert(frames.shape[2] == self.resolution[0] and frames.shape[3] == self.resolution[1]), f'frames={frames.shape}, self.resolution={self.resolution}'
|
| 205 |
+
# frames = frames.byte()
|
| 206 |
+
# # fps
|
| 207 |
+
# fps_clip = fps_ori // self.frame_stride
|
| 208 |
+
# if self.fps_max is not None and fps_clip > self.fps_max:
|
| 209 |
+
# fps_clip = self.fps_max
|
| 210 |
+
|
| 211 |
+
# # caption index
|
| 212 |
+
# middle_idx = (rand_idx + self.video_length /2 )*fs
|
| 213 |
+
# big_cap_idx = (middle_idx // 64 +1) *64
|
| 214 |
+
# small_cap_idx = (middle_idx // 64) *64
|
| 215 |
+
# if big_cap_idx >= allf or ((big_cap_idx-middle_idx) >= (small_cap_idx-middle_idx)):
|
| 216 |
+
# cap_idx = small_cap_idx
|
| 217 |
+
# else:
|
| 218 |
+
# cap_idx = big_cap_idx
|
| 219 |
+
# # print(middle_idx, small_cap_idx, big_cap_idx,cap_idx)
|
| 220 |
+
# caption = sample[1][int(cap_idx//64)]
|
| 221 |
+
|
| 222 |
+
# frames = frames.permute(1,0,2,3)
|
| 223 |
+
# skeleton_final = torch.zeros_like(frames).byte()
|
| 224 |
+
# frames = (frames / 127.5 - 1.0)
|
| 225 |
+
# skeleton_final = (skeleton_final / 127.5 - 1.0)
|
| 226 |
+
# example = {'pixel_values': frames, 'sentence': caption, 'pose': skeleton_final}
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# return example
|
| 231 |
+
|
| 232 |
+
# def __len__(self):
|
| 233 |
+
# return len(self.metadata)
|
| 234 |
+
# # return 1
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# if __name__ == '__main__':
|
| 238 |
+
# if True: # val
|
| 239 |
+
# hd_data = HDVila('/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m','/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m/caption_2048_val.csv')
|
| 240 |
+
# else:
|
| 241 |
+
# hd_data = HDVila('/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m','/apdcephfs_cq3/share_1290939/0_public_datasets/hd-vila-100m/caption_rm2048_train.csv')
|
| 242 |
+
# print(len(hd_data))
|
| 243 |
+
# for i in range(len(hd_data)):
|
| 244 |
+
# # print(i)
|
| 245 |
+
# hd_data[i]
|
FollowYourPose/followyourpose/models/__pycache__/attention.cpython-38.pyc
ADDED
|
Binary file (8.93 kB). View file
|
|
|
FollowYourPose/followyourpose/models/__pycache__/resnet.cpython-38.pyc
ADDED
|
Binary file (5.12 kB). View file
|
|
|
FollowYourPose/followyourpose/models/__pycache__/unet.cpython-38.pyc
ADDED
|
Binary file (14.9 kB). View file
|
|
|
FollowYourPose/followyourpose/models/__pycache__/unet_blocks.cpython-38.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
FollowYourPose/followyourpose/models/attention.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch import nn
|
| 9 |
+
|
| 10 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 11 |
+
from diffusers.modeling_utils import ModelMixin
|
| 12 |
+
from diffusers.utils import BaseOutput
|
| 13 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 14 |
+
from diffusers.models.attention import CrossAttention, FeedForward, AdaLayerNorm
|
| 15 |
+
|
| 16 |
+
from einops import rearrange, repeat
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class Transformer3DModelOutput(BaseOutput):
|
| 21 |
+
sample: torch.FloatTensor
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if is_xformers_available():
|
| 25 |
+
import xformers
|
| 26 |
+
import xformers.ops
|
| 27 |
+
else:
|
| 28 |
+
xformers = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Transformer3DModel(ModelMixin, ConfigMixin):
|
| 32 |
+
@register_to_config
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
num_attention_heads: int = 16,
|
| 36 |
+
attention_head_dim: int = 88,
|
| 37 |
+
in_channels: Optional[int] = None,
|
| 38 |
+
num_layers: int = 1,
|
| 39 |
+
dropout: float = 0.0,
|
| 40 |
+
norm_num_groups: int = 32,
|
| 41 |
+
cross_attention_dim: Optional[int] = None,
|
| 42 |
+
attention_bias: bool = False,
|
| 43 |
+
activation_fn: str = "geglu",
|
| 44 |
+
num_embeds_ada_norm: Optional[int] = None,
|
| 45 |
+
use_linear_projection: bool = False,
|
| 46 |
+
only_cross_attention: bool = False,
|
| 47 |
+
upcast_attention: bool = False,
|
| 48 |
+
):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.use_linear_projection = use_linear_projection
|
| 51 |
+
self.num_attention_heads = num_attention_heads
|
| 52 |
+
self.attention_head_dim = attention_head_dim
|
| 53 |
+
inner_dim = num_attention_heads * attention_head_dim
|
| 54 |
+
|
| 55 |
+
# Define input layers
|
| 56 |
+
self.in_channels = in_channels
|
| 57 |
+
|
| 58 |
+
self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
| 59 |
+
if use_linear_projection:
|
| 60 |
+
self.proj_in = nn.Linear(in_channels, inner_dim)
|
| 61 |
+
else:
|
| 62 |
+
self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
|
| 63 |
+
|
| 64 |
+
# Define transformers blocks
|
| 65 |
+
self.transformer_blocks = nn.ModuleList(
|
| 66 |
+
[
|
| 67 |
+
BasicTransformerBlock(
|
| 68 |
+
inner_dim,
|
| 69 |
+
num_attention_heads,
|
| 70 |
+
attention_head_dim,
|
| 71 |
+
dropout=dropout,
|
| 72 |
+
cross_attention_dim=cross_attention_dim,
|
| 73 |
+
activation_fn=activation_fn,
|
| 74 |
+
num_embeds_ada_norm=num_embeds_ada_norm,
|
| 75 |
+
attention_bias=attention_bias,
|
| 76 |
+
only_cross_attention=only_cross_attention,
|
| 77 |
+
upcast_attention=upcast_attention,
|
| 78 |
+
)
|
| 79 |
+
for d in range(num_layers)
|
| 80 |
+
]
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# 4. Define output layers
|
| 84 |
+
if use_linear_projection:
|
| 85 |
+
self.proj_out = nn.Linear(in_channels, inner_dim)
|
| 86 |
+
else:
|
| 87 |
+
self.proj_out = nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
|
| 88 |
+
|
| 89 |
+
def forward(self, hidden_states, encoder_hidden_states=None, timestep=None, return_dict: bool = True):
|
| 90 |
+
# Input
|
| 91 |
+
assert hidden_states.dim() == 5, f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
|
| 92 |
+
video_length = hidden_states.shape[2]
|
| 93 |
+
hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
|
| 94 |
+
encoder_hidden_states = repeat(encoder_hidden_states, 'b n c -> (b f) n c', f=video_length)
|
| 95 |
+
|
| 96 |
+
batch, channel, height, weight = hidden_states.shape
|
| 97 |
+
residual = hidden_states
|
| 98 |
+
|
| 99 |
+
hidden_states = self.norm(hidden_states)
|
| 100 |
+
if not self.use_linear_projection:
|
| 101 |
+
hidden_states = self.proj_in(hidden_states)
|
| 102 |
+
inner_dim = hidden_states.shape[1]
|
| 103 |
+
hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
|
| 104 |
+
else:
|
| 105 |
+
inner_dim = hidden_states.shape[1]
|
| 106 |
+
hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
|
| 107 |
+
hidden_states = self.proj_in(hidden_states)
|
| 108 |
+
|
| 109 |
+
# Blocks
|
| 110 |
+
for block in self.transformer_blocks:
|
| 111 |
+
hidden_states = block(
|
| 112 |
+
hidden_states,
|
| 113 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 114 |
+
timestep=timestep,
|
| 115 |
+
video_length=video_length
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# Output
|
| 119 |
+
if not self.use_linear_projection:
|
| 120 |
+
hidden_states = (
|
| 121 |
+
hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
|
| 122 |
+
)
|
| 123 |
+
hidden_states = self.proj_out(hidden_states)
|
| 124 |
+
else:
|
| 125 |
+
hidden_states = self.proj_out(hidden_states)
|
| 126 |
+
hidden_states = (
|
| 127 |
+
hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
output = hidden_states + residual
|
| 131 |
+
|
| 132 |
+
output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
|
| 133 |
+
if not return_dict:
|
| 134 |
+
return (output,)
|
| 135 |
+
|
| 136 |
+
return Transformer3DModelOutput(sample=output)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class BasicTransformerBlock(nn.Module):
|
| 140 |
+
def __init__(
|
| 141 |
+
self,
|
| 142 |
+
dim: int,
|
| 143 |
+
num_attention_heads: int,
|
| 144 |
+
attention_head_dim: int,
|
| 145 |
+
dropout=0.0,
|
| 146 |
+
cross_attention_dim: Optional[int] = None,
|
| 147 |
+
activation_fn: str = "geglu",
|
| 148 |
+
num_embeds_ada_norm: Optional[int] = None,
|
| 149 |
+
attention_bias: bool = False,
|
| 150 |
+
only_cross_attention: bool = False,
|
| 151 |
+
upcast_attention: bool = False,
|
| 152 |
+
):
|
| 153 |
+
super().__init__()
|
| 154 |
+
self.only_cross_attention = only_cross_attention
|
| 155 |
+
self.use_ada_layer_norm = num_embeds_ada_norm is not None
|
| 156 |
+
|
| 157 |
+
# SC-Attn
|
| 158 |
+
self.attn1 = SparseCausalAttention(
|
| 159 |
+
query_dim=dim,
|
| 160 |
+
heads=num_attention_heads,
|
| 161 |
+
dim_head=attention_head_dim,
|
| 162 |
+
dropout=dropout,
|
| 163 |
+
bias=attention_bias,
|
| 164 |
+
cross_attention_dim=cross_attention_dim if only_cross_attention else None,
|
| 165 |
+
upcast_attention=upcast_attention,
|
| 166 |
+
)
|
| 167 |
+
self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
|
| 168 |
+
|
| 169 |
+
# Cross-Attn
|
| 170 |
+
if cross_attention_dim is not None:
|
| 171 |
+
self.attn2 = CrossAttention(
|
| 172 |
+
query_dim=dim,
|
| 173 |
+
cross_attention_dim=cross_attention_dim,
|
| 174 |
+
heads=num_attention_heads,
|
| 175 |
+
dim_head=attention_head_dim,
|
| 176 |
+
dropout=dropout,
|
| 177 |
+
bias=attention_bias,
|
| 178 |
+
upcast_attention=upcast_attention,
|
| 179 |
+
)
|
| 180 |
+
else:
|
| 181 |
+
self.attn2 = None
|
| 182 |
+
|
| 183 |
+
if cross_attention_dim is not None:
|
| 184 |
+
self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
|
| 185 |
+
else:
|
| 186 |
+
self.norm2 = None
|
| 187 |
+
|
| 188 |
+
# Feed-forward
|
| 189 |
+
self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
|
| 190 |
+
self.norm3 = nn.LayerNorm(dim)
|
| 191 |
+
|
| 192 |
+
# Temp-Attn
|
| 193 |
+
self.attn_temp = CrossAttention(
|
| 194 |
+
query_dim=dim,
|
| 195 |
+
heads=num_attention_heads,
|
| 196 |
+
dim_head=attention_head_dim,
|
| 197 |
+
dropout=dropout,
|
| 198 |
+
bias=attention_bias,
|
| 199 |
+
upcast_attention=upcast_attention,
|
| 200 |
+
)
|
| 201 |
+
# nn.init.zeros_(self.attn_temp.to_out[0].weight.data)
|
| 202 |
+
self.norm_temp = AdaLayerNorm(dim, num_embeds_ada_norm) if self.use_ada_layer_norm else nn.LayerNorm(dim)
|
| 203 |
+
|
| 204 |
+
self.conv_temporal = LoRALinearLayer(dim, dim, rank=160, stride=1)
|
| 205 |
+
|
| 206 |
+
def set_use_memory_efficient_attention_xformers(self, use_memory_efficient_attention_xformers: bool):
|
| 207 |
+
if not is_xformers_available():
|
| 208 |
+
print("Here is how to install it")
|
| 209 |
+
raise ModuleNotFoundError(
|
| 210 |
+
"Refer to https://github.com/facebookresearch/xformers for more information on how to install"
|
| 211 |
+
" xformers",
|
| 212 |
+
name="xformers",
|
| 213 |
+
)
|
| 214 |
+
elif not torch.cuda.is_available():
|
| 215 |
+
raise ValueError(
|
| 216 |
+
"torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is only"
|
| 217 |
+
" available for GPU "
|
| 218 |
+
)
|
| 219 |
+
else:
|
| 220 |
+
try:
|
| 221 |
+
# Make sure we can run the memory efficient attention
|
| 222 |
+
_ = xformers.ops.memory_efficient_attention(
|
| 223 |
+
torch.randn((1, 2, 40), device="cuda"),
|
| 224 |
+
torch.randn((1, 2, 40), device="cuda"),
|
| 225 |
+
torch.randn((1, 2, 40), device="cuda"),
|
| 226 |
+
)
|
| 227 |
+
except Exception as e:
|
| 228 |
+
raise e
|
| 229 |
+
self.attn1._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
|
| 230 |
+
if self.attn2 is not None:
|
| 231 |
+
self.attn2._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
|
| 232 |
+
# self.attn_temp._use_memory_efficient_attention_xformers = use_memory_efficient_attention_xformers
|
| 233 |
+
|
| 234 |
+
def forward(self, hidden_states, encoder_hidden_states=None, timestep=None, attention_mask=None, video_length=None):
|
| 235 |
+
# SparseCausal-Attention
|
| 236 |
+
norm_hidden_states = (
|
| 237 |
+
self.norm1(hidden_states, timestep) if self.use_ada_layer_norm else self.norm1(hidden_states)
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
if self.only_cross_attention:
|
| 241 |
+
hidden_states = (
|
| 242 |
+
self.attn1(norm_hidden_states, encoder_hidden_states, attention_mask=attention_mask) + hidden_states
|
| 243 |
+
)
|
| 244 |
+
else:
|
| 245 |
+
hidden_states = self.attn1(norm_hidden_states, attention_mask=attention_mask, video_length=video_length) + hidden_states
|
| 246 |
+
|
| 247 |
+
if self.attn2 is not None:
|
| 248 |
+
# Cross-Attention
|
| 249 |
+
norm_hidden_states = (
|
| 250 |
+
self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
|
| 251 |
+
)
|
| 252 |
+
hidden_states = (
|
| 253 |
+
self.attn2(
|
| 254 |
+
norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
|
| 255 |
+
)
|
| 256 |
+
+ hidden_states
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# Feed-forward
|
| 260 |
+
hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
|
| 261 |
+
|
| 262 |
+
# Temporal-Attention
|
| 263 |
+
d = hidden_states.shape[1]
|
| 264 |
+
hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=video_length)
|
| 265 |
+
norm_hidden_states = (
|
| 266 |
+
self.norm_temp(hidden_states, timestep) if self.use_ada_layer_norm else self.norm_temp(hidden_states)
|
| 267 |
+
)
|
| 268 |
+
hidden_states = self.attn_temp(norm_hidden_states) + hidden_states
|
| 269 |
+
hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) c f", d=d, f=video_length)
|
| 273 |
+
hidden_states = self.conv_temporal(hidden_states)
|
| 274 |
+
hidden_states = rearrange(hidden_states, "(b d) c f -> (b f) d c", d=d, f=video_length)
|
| 275 |
+
|
| 276 |
+
return hidden_states
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class LoRALinearLayer(nn.Module):
|
| 282 |
+
def __init__(self, in_features, out_features, rank=4, stride=1):
|
| 283 |
+
super().__init__()
|
| 284 |
+
|
| 285 |
+
if rank > min(in_features, out_features):
|
| 286 |
+
Warning(f"LoRA rank {rank} must be less or equal than {min(in_features, out_features)}, reset to {min(in_features, out_features)//2}")
|
| 287 |
+
rank = min(in_features, out_features)//2
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
self.down = nn.Conv1d(in_features, rank, bias=False,
|
| 291 |
+
kernel_size=3,
|
| 292 |
+
stride = stride,
|
| 293 |
+
padding=1,)
|
| 294 |
+
self.up = nn.Conv1d(rank, out_features, bias=False,
|
| 295 |
+
kernel_size=3,
|
| 296 |
+
padding=1,)
|
| 297 |
+
|
| 298 |
+
nn.init.normal_(self.down.weight, std=1 / rank)
|
| 299 |
+
# nn.init.zeros_(self.down.bias.data)
|
| 300 |
+
|
| 301 |
+
nn.init.zeros_(self.up.weight)
|
| 302 |
+
# nn.init.zeros_(self.up.bias.data)
|
| 303 |
+
if stride > 1:
|
| 304 |
+
self.skip = nn.AvgPool1d(kernel_size=3, stride=2, padding=1)
|
| 305 |
+
|
| 306 |
+
def forward(self, hidden_states):
|
| 307 |
+
orig_dtype = hidden_states.dtype
|
| 308 |
+
dtype = self.down.weight.dtype
|
| 309 |
+
|
| 310 |
+
down_hidden_states = self.down(hidden_states.to(dtype))
|
| 311 |
+
up_hidden_states = self.up(down_hidden_states)
|
| 312 |
+
if hasattr(self, 'skip'):
|
| 313 |
+
hidden_states=self.skip(hidden_states)
|
| 314 |
+
return up_hidden_states.to(orig_dtype)+hidden_states
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class SparseCausalAttention(CrossAttention):
|
| 320 |
+
def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None, video_length=None):
|
| 321 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 322 |
+
|
| 323 |
+
encoder_hidden_states = encoder_hidden_states
|
| 324 |
+
|
| 325 |
+
if self.group_norm is not None:
|
| 326 |
+
hidden_states = self.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 327 |
+
|
| 328 |
+
query = self.to_q(hidden_states)
|
| 329 |
+
dim = query.shape[-1]
|
| 330 |
+
query = self.reshape_heads_to_batch_dim(query)
|
| 331 |
+
|
| 332 |
+
if self.added_kv_proj_dim is not None:
|
| 333 |
+
raise NotImplementedError
|
| 334 |
+
|
| 335 |
+
encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
|
| 336 |
+
key = self.to_k(encoder_hidden_states)
|
| 337 |
+
value = self.to_v(encoder_hidden_states)
|
| 338 |
+
|
| 339 |
+
former_frame_index = torch.arange(video_length) - 1
|
| 340 |
+
former_frame_index[0] = 0
|
| 341 |
+
|
| 342 |
+
key = rearrange(key, "(b f) d c -> b f d c", f=video_length)
|
| 343 |
+
key = torch.cat([key[:, [0] * video_length], key[:, former_frame_index]], dim=2)
|
| 344 |
+
key = rearrange(key, "b f d c -> (b f) d c")
|
| 345 |
+
|
| 346 |
+
value = rearrange(value, "(b f) d c -> b f d c", f=video_length)
|
| 347 |
+
value = torch.cat([value[:, [0] * video_length], value[:, former_frame_index]], dim=2)
|
| 348 |
+
value = rearrange(value, "b f d c -> (b f) d c")
|
| 349 |
+
|
| 350 |
+
key = self.reshape_heads_to_batch_dim(key)
|
| 351 |
+
value = self.reshape_heads_to_batch_dim(value)
|
| 352 |
+
|
| 353 |
+
if attention_mask is not None:
|
| 354 |
+
if attention_mask.shape[-1] != query.shape[1]:
|
| 355 |
+
target_length = query.shape[1]
|
| 356 |
+
attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
|
| 357 |
+
attention_mask = attention_mask.repeat_interleave(self.heads, dim=0)
|
| 358 |
+
|
| 359 |
+
# attention, what we cannot get enough of
|
| 360 |
+
if self._use_memory_efficient_attention_xformers:
|
| 361 |
+
hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
|
| 362 |
+
# Some versions of xformers return output in fp32, cast it back to the dtype of the input
|
| 363 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 364 |
+
else:
|
| 365 |
+
if self._slice_size is None or query.shape[0] // self._slice_size == 1:
|
| 366 |
+
hidden_states = self._attention(query, key, value, attention_mask)
|
| 367 |
+
else:
|
| 368 |
+
hidden_states = self._sliced_attention(query, key, value, sequence_length, dim, attention_mask)
|
| 369 |
+
|
| 370 |
+
# linear proj
|
| 371 |
+
hidden_states = self.to_out[0](hidden_states)
|
| 372 |
+
|
| 373 |
+
# dropout
|
| 374 |
+
hidden_states = self.to_out[1](hidden_states)
|
| 375 |
+
return hidden_states
|
FollowYourPose/followyourpose/models/resnet.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class InflatedConv3d(nn.Conv2d):
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
video_length = x.shape[2]
|
| 13 |
+
|
| 14 |
+
x = rearrange(x, "b c f h w -> (b f) c h w")
|
| 15 |
+
x = super().forward(x)
|
| 16 |
+
x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
|
| 17 |
+
|
| 18 |
+
return x
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Upsample3D(nn.Module):
|
| 22 |
+
def __init__(self, channels, use_conv=False, use_conv_transpose=False, out_channels=None, name="conv"):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.channels = channels
|
| 25 |
+
self.out_channels = out_channels or channels
|
| 26 |
+
self.use_conv = use_conv
|
| 27 |
+
self.use_conv_transpose = use_conv_transpose
|
| 28 |
+
self.name = name
|
| 29 |
+
|
| 30 |
+
conv = None
|
| 31 |
+
if use_conv_transpose:
|
| 32 |
+
raise NotImplementedError
|
| 33 |
+
elif use_conv:
|
| 34 |
+
conv = InflatedConv3d(self.channels, self.out_channels, 3, padding=1)
|
| 35 |
+
|
| 36 |
+
if name == "conv":
|
| 37 |
+
self.conv = conv
|
| 38 |
+
else:
|
| 39 |
+
self.Conv2d_0 = conv
|
| 40 |
+
|
| 41 |
+
def forward(self, hidden_states, output_size=None):
|
| 42 |
+
assert hidden_states.shape[1] == self.channels
|
| 43 |
+
|
| 44 |
+
if self.use_conv_transpose:
|
| 45 |
+
raise NotImplementedError
|
| 46 |
+
|
| 47 |
+
# Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
|
| 48 |
+
dtype = hidden_states.dtype
|
| 49 |
+
if dtype == torch.bfloat16:
|
| 50 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 51 |
+
|
| 52 |
+
# upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
|
| 53 |
+
if hidden_states.shape[0] >= 64:
|
| 54 |
+
hidden_states = hidden_states.contiguous()
|
| 55 |
+
|
| 56 |
+
# if `output_size` is passed we force the interpolation output
|
| 57 |
+
# size and do not make use of `scale_factor=2`
|
| 58 |
+
if output_size is None:
|
| 59 |
+
hidden_states = F.interpolate(hidden_states, scale_factor=[1.0, 2.0, 2.0], mode="nearest")
|
| 60 |
+
else:
|
| 61 |
+
hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
|
| 62 |
+
|
| 63 |
+
# If the input is bfloat16, we cast back to bfloat16
|
| 64 |
+
if dtype == torch.bfloat16:
|
| 65 |
+
hidden_states = hidden_states.to(dtype)
|
| 66 |
+
|
| 67 |
+
if self.use_conv:
|
| 68 |
+
if self.name == "conv":
|
| 69 |
+
hidden_states = self.conv(hidden_states)
|
| 70 |
+
else:
|
| 71 |
+
hidden_states = self.Conv2d_0(hidden_states)
|
| 72 |
+
|
| 73 |
+
return hidden_states
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class Downsample3D(nn.Module):
|
| 77 |
+
def __init__(self, channels, use_conv=False, out_channels=None, padding=1, name="conv"):
|
| 78 |
+
super().__init__()
|
| 79 |
+
self.channels = channels
|
| 80 |
+
self.out_channels = out_channels or channels
|
| 81 |
+
self.use_conv = use_conv
|
| 82 |
+
self.padding = padding
|
| 83 |
+
stride = 2
|
| 84 |
+
self.name = name
|
| 85 |
+
|
| 86 |
+
if use_conv:
|
| 87 |
+
conv = InflatedConv3d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
|
| 88 |
+
else:
|
| 89 |
+
raise NotImplementedError
|
| 90 |
+
|
| 91 |
+
if name == "conv":
|
| 92 |
+
self.Conv2d_0 = conv
|
| 93 |
+
self.conv = conv
|
| 94 |
+
elif name == "Conv2d_0":
|
| 95 |
+
self.conv = conv
|
| 96 |
+
else:
|
| 97 |
+
self.conv = conv
|
| 98 |
+
|
| 99 |
+
def forward(self, hidden_states):
|
| 100 |
+
assert hidden_states.shape[1] == self.channels
|
| 101 |
+
if self.use_conv and self.padding == 0:
|
| 102 |
+
raise NotImplementedError
|
| 103 |
+
|
| 104 |
+
assert hidden_states.shape[1] == self.channels
|
| 105 |
+
hidden_states = self.conv(hidden_states)
|
| 106 |
+
|
| 107 |
+
return hidden_states
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class ResnetBlock3D(nn.Module):
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
*,
|
| 114 |
+
in_channels,
|
| 115 |
+
out_channels=None,
|
| 116 |
+
conv_shortcut=False,
|
| 117 |
+
dropout=0.0,
|
| 118 |
+
temb_channels=512,
|
| 119 |
+
groups=32,
|
| 120 |
+
groups_out=None,
|
| 121 |
+
pre_norm=True,
|
| 122 |
+
eps=1e-6,
|
| 123 |
+
non_linearity="swish",
|
| 124 |
+
time_embedding_norm="default",
|
| 125 |
+
output_scale_factor=1.0,
|
| 126 |
+
use_in_shortcut=None,
|
| 127 |
+
):
|
| 128 |
+
super().__init__()
|
| 129 |
+
self.pre_norm = pre_norm
|
| 130 |
+
self.pre_norm = True
|
| 131 |
+
self.in_channels = in_channels
|
| 132 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 133 |
+
self.out_channels = out_channels
|
| 134 |
+
self.use_conv_shortcut = conv_shortcut
|
| 135 |
+
self.time_embedding_norm = time_embedding_norm
|
| 136 |
+
self.output_scale_factor = output_scale_factor
|
| 137 |
+
|
| 138 |
+
if groups_out is None:
|
| 139 |
+
groups_out = groups
|
| 140 |
+
|
| 141 |
+
self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
|
| 142 |
+
|
| 143 |
+
self.conv1 = InflatedConv3d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 144 |
+
|
| 145 |
+
if temb_channels is not None:
|
| 146 |
+
if self.time_embedding_norm == "default":
|
| 147 |
+
time_emb_proj_out_channels = out_channels
|
| 148 |
+
elif self.time_embedding_norm == "scale_shift":
|
| 149 |
+
time_emb_proj_out_channels = out_channels * 2
|
| 150 |
+
else:
|
| 151 |
+
raise ValueError(f"unknown time_embedding_norm : {self.time_embedding_norm} ")
|
| 152 |
+
|
| 153 |
+
self.time_emb_proj = torch.nn.Linear(temb_channels, time_emb_proj_out_channels)
|
| 154 |
+
else:
|
| 155 |
+
self.time_emb_proj = None
|
| 156 |
+
|
| 157 |
+
self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
|
| 158 |
+
self.dropout = torch.nn.Dropout(dropout)
|
| 159 |
+
self.conv2 = InflatedConv3d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 160 |
+
|
| 161 |
+
if non_linearity == "swish":
|
| 162 |
+
self.nonlinearity = lambda x: F.silu(x)
|
| 163 |
+
elif non_linearity == "mish":
|
| 164 |
+
self.nonlinearity = Mish()
|
| 165 |
+
elif non_linearity == "silu":
|
| 166 |
+
self.nonlinearity = nn.SiLU()
|
| 167 |
+
|
| 168 |
+
self.use_in_shortcut = self.in_channels != self.out_channels if use_in_shortcut is None else use_in_shortcut
|
| 169 |
+
|
| 170 |
+
self.conv_shortcut = None
|
| 171 |
+
if self.use_in_shortcut:
|
| 172 |
+
self.conv_shortcut = InflatedConv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
|
| 173 |
+
|
| 174 |
+
def forward(self, input_tensor, temb):
|
| 175 |
+
hidden_states = input_tensor
|
| 176 |
+
|
| 177 |
+
hidden_states = self.norm1(hidden_states)
|
| 178 |
+
hidden_states = self.nonlinearity(hidden_states)
|
| 179 |
+
|
| 180 |
+
hidden_states = self.conv1(hidden_states)
|
| 181 |
+
|
| 182 |
+
if temb is not None:
|
| 183 |
+
temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None, None]
|
| 184 |
+
|
| 185 |
+
if temb is not None and self.time_embedding_norm == "default":
|
| 186 |
+
hidden_states = hidden_states + temb
|
| 187 |
+
|
| 188 |
+
hidden_states = self.norm2(hidden_states)
|
| 189 |
+
|
| 190 |
+
if temb is not None and self.time_embedding_norm == "scale_shift":
|
| 191 |
+
scale, shift = torch.chunk(temb, 2, dim=1)
|
| 192 |
+
hidden_states = hidden_states * (1 + scale) + shift
|
| 193 |
+
|
| 194 |
+
hidden_states = self.nonlinearity(hidden_states)
|
| 195 |
+
|
| 196 |
+
hidden_states = self.dropout(hidden_states)
|
| 197 |
+
hidden_states = self.conv2(hidden_states)
|
| 198 |
+
|
| 199 |
+
if self.conv_shortcut is not None:
|
| 200 |
+
input_tensor = self.conv_shortcut(input_tensor)
|
| 201 |
+
|
| 202 |
+
output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
|
| 203 |
+
|
| 204 |
+
return output_tensor
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class Mish(torch.nn.Module):
|
| 208 |
+
def forward(self, hidden_states):
|
| 209 |
+
return hidden_states * torch.tanh(torch.nn.functional.softplus(hidden_states))
|
FollowYourPose/followyourpose/models/unet.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import List, Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.utils.checkpoint
|
| 12 |
+
|
| 13 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 14 |
+
from diffusers.modeling_utils import ModelMixin
|
| 15 |
+
from diffusers.utils import BaseOutput, logging
|
| 16 |
+
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
| 17 |
+
from .unet_blocks import (
|
| 18 |
+
CrossAttnDownBlock3D,
|
| 19 |
+
CrossAttnUpBlock3D,
|
| 20 |
+
DownBlock3D,
|
| 21 |
+
UNetMidBlock3DCrossAttn,
|
| 22 |
+
UpBlock3D,
|
| 23 |
+
get_down_block,
|
| 24 |
+
get_up_block,
|
| 25 |
+
conv_nd,
|
| 26 |
+
avg_pool_nd,
|
| 27 |
+
)
|
| 28 |
+
from .resnet import InflatedConv3d
|
| 29 |
+
from einops import rearrange
|
| 30 |
+
import sys
|
| 31 |
+
sys.path.append('FollowYourPose')
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class UNet3DConditionOutput(BaseOutput):
|
| 38 |
+
sample: torch.FloatTensor
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class UNet3DConditionModel(ModelMixin, ConfigMixin):
|
| 42 |
+
_supports_gradient_checkpointing = True
|
| 43 |
+
|
| 44 |
+
@register_to_config
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
sample_size: Optional[int] = None,
|
| 48 |
+
in_channels: int = 4,
|
| 49 |
+
out_channels: int = 4,
|
| 50 |
+
center_input_sample: bool = False,
|
| 51 |
+
flip_sin_to_cos: bool = True,
|
| 52 |
+
freq_shift: int = 0,
|
| 53 |
+
down_block_types: Tuple[str] = (
|
| 54 |
+
"CrossAttnDownBlock3D",
|
| 55 |
+
"CrossAttnDownBlock3D",
|
| 56 |
+
"CrossAttnDownBlock3D",
|
| 57 |
+
"DownBlock3D",
|
| 58 |
+
),
|
| 59 |
+
mid_block_type: str = "UNetMidBlock3DCrossAttn",
|
| 60 |
+
up_block_types: Tuple[str] = (
|
| 61 |
+
"UpBlock3D",
|
| 62 |
+
"CrossAttnUpBlock3D",
|
| 63 |
+
"CrossAttnUpBlock3D",
|
| 64 |
+
"CrossAttnUpBlock3D"
|
| 65 |
+
),
|
| 66 |
+
only_cross_attention: Union[bool, Tuple[bool]] = False,
|
| 67 |
+
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
| 68 |
+
layers_per_block: int = 2,
|
| 69 |
+
downsample_padding: int = 1,
|
| 70 |
+
mid_block_scale_factor: float = 1,
|
| 71 |
+
act_fn: str = "silu",
|
| 72 |
+
norm_num_groups: int = 32,
|
| 73 |
+
norm_eps: float = 1e-5,
|
| 74 |
+
cross_attention_dim: int = 1280,
|
| 75 |
+
attention_head_dim: Union[int, Tuple[int]] = 8,
|
| 76 |
+
dual_cross_attention: bool = False,
|
| 77 |
+
use_linear_projection: bool = False,
|
| 78 |
+
class_embed_type: Optional[str] = None,
|
| 79 |
+
num_class_embeds: Optional[int] = None,
|
| 80 |
+
upcast_attention: bool = False,
|
| 81 |
+
resnet_time_scale_shift: str = "default",
|
| 82 |
+
):
|
| 83 |
+
super().__init__()
|
| 84 |
+
|
| 85 |
+
self.sample_size = sample_size
|
| 86 |
+
time_embed_dim = block_out_channels[0] * 4
|
| 87 |
+
|
| 88 |
+
# input
|
| 89 |
+
self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
|
| 90 |
+
|
| 91 |
+
# time
|
| 92 |
+
self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
|
| 93 |
+
timestep_input_dim = block_out_channels[0]
|
| 94 |
+
|
| 95 |
+
self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
|
| 96 |
+
|
| 97 |
+
# class embedding
|
| 98 |
+
if class_embed_type is None and num_class_embeds is not None:
|
| 99 |
+
self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
|
| 100 |
+
elif class_embed_type == "timestep":
|
| 101 |
+
self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
|
| 102 |
+
elif class_embed_type == "identity":
|
| 103 |
+
self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
|
| 104 |
+
else:
|
| 105 |
+
self.class_embedding = None
|
| 106 |
+
|
| 107 |
+
self.down_blocks = nn.ModuleList([])
|
| 108 |
+
self.mid_block = None
|
| 109 |
+
self.up_blocks = nn.ModuleList([])
|
| 110 |
+
|
| 111 |
+
if isinstance(only_cross_attention, bool):
|
| 112 |
+
only_cross_attention = [only_cross_attention] * len(down_block_types)
|
| 113 |
+
|
| 114 |
+
if isinstance(attention_head_dim, int):
|
| 115 |
+
attention_head_dim = (attention_head_dim,) * len(down_block_types)
|
| 116 |
+
|
| 117 |
+
# down
|
| 118 |
+
output_channel = block_out_channels[0]
|
| 119 |
+
for i, down_block_type in enumerate(down_block_types):
|
| 120 |
+
input_channel = output_channel
|
| 121 |
+
output_channel = block_out_channels[i]
|
| 122 |
+
is_final_block = i == len(block_out_channels) - 1
|
| 123 |
+
|
| 124 |
+
down_block = get_down_block(
|
| 125 |
+
down_block_type,
|
| 126 |
+
num_layers=layers_per_block,
|
| 127 |
+
in_channels=input_channel,
|
| 128 |
+
out_channels=output_channel,
|
| 129 |
+
temb_channels=time_embed_dim,
|
| 130 |
+
add_downsample=not is_final_block,
|
| 131 |
+
resnet_eps=norm_eps,
|
| 132 |
+
resnet_act_fn=act_fn,
|
| 133 |
+
resnet_groups=norm_num_groups,
|
| 134 |
+
cross_attention_dim=cross_attention_dim,
|
| 135 |
+
attn_num_head_channels=attention_head_dim[i],
|
| 136 |
+
downsample_padding=downsample_padding,
|
| 137 |
+
dual_cross_attention=dual_cross_attention,
|
| 138 |
+
use_linear_projection=use_linear_projection,
|
| 139 |
+
only_cross_attention=only_cross_attention[i],
|
| 140 |
+
upcast_attention=upcast_attention,
|
| 141 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
| 142 |
+
)
|
| 143 |
+
self.down_blocks.append(down_block)
|
| 144 |
+
|
| 145 |
+
# mid
|
| 146 |
+
if mid_block_type == "UNetMidBlock3DCrossAttn":
|
| 147 |
+
self.mid_block = UNetMidBlock3DCrossAttn(
|
| 148 |
+
in_channels=block_out_channels[-1],
|
| 149 |
+
temb_channels=time_embed_dim,
|
| 150 |
+
resnet_eps=norm_eps,
|
| 151 |
+
resnet_act_fn=act_fn,
|
| 152 |
+
output_scale_factor=mid_block_scale_factor,
|
| 153 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
| 154 |
+
cross_attention_dim=cross_attention_dim,
|
| 155 |
+
attn_num_head_channels=attention_head_dim[-1],
|
| 156 |
+
resnet_groups=norm_num_groups,
|
| 157 |
+
dual_cross_attention=dual_cross_attention,
|
| 158 |
+
use_linear_projection=use_linear_projection,
|
| 159 |
+
upcast_attention=upcast_attention,
|
| 160 |
+
)
|
| 161 |
+
else:
|
| 162 |
+
raise ValueError(f"unknown mid_block_type : {mid_block_type}")
|
| 163 |
+
|
| 164 |
+
# count how many layers upsample the videos
|
| 165 |
+
self.num_upsamplers = 0
|
| 166 |
+
|
| 167 |
+
# up
|
| 168 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
| 169 |
+
reversed_attention_head_dim = list(reversed(attention_head_dim))
|
| 170 |
+
only_cross_attention = list(reversed(only_cross_attention))
|
| 171 |
+
output_channel = reversed_block_out_channels[0]
|
| 172 |
+
for i, up_block_type in enumerate(up_block_types):
|
| 173 |
+
is_final_block = i == len(block_out_channels) - 1
|
| 174 |
+
|
| 175 |
+
prev_output_channel = output_channel
|
| 176 |
+
output_channel = reversed_block_out_channels[i]
|
| 177 |
+
input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
| 178 |
+
|
| 179 |
+
# add upsample block for all BUT final layer
|
| 180 |
+
if not is_final_block:
|
| 181 |
+
add_upsample = True
|
| 182 |
+
self.num_upsamplers += 1
|
| 183 |
+
else:
|
| 184 |
+
add_upsample = False
|
| 185 |
+
|
| 186 |
+
up_block = get_up_block(
|
| 187 |
+
up_block_type,
|
| 188 |
+
num_layers=layers_per_block + 1,
|
| 189 |
+
in_channels=input_channel,
|
| 190 |
+
out_channels=output_channel,
|
| 191 |
+
prev_output_channel=prev_output_channel,
|
| 192 |
+
temb_channels=time_embed_dim,
|
| 193 |
+
add_upsample=add_upsample,
|
| 194 |
+
resnet_eps=norm_eps,
|
| 195 |
+
resnet_act_fn=act_fn,
|
| 196 |
+
resnet_groups=norm_num_groups,
|
| 197 |
+
cross_attention_dim=cross_attention_dim,
|
| 198 |
+
attn_num_head_channels=reversed_attention_head_dim[i],
|
| 199 |
+
dual_cross_attention=dual_cross_attention,
|
| 200 |
+
use_linear_projection=use_linear_projection,
|
| 201 |
+
only_cross_attention=only_cross_attention[i],
|
| 202 |
+
upcast_attention=upcast_attention,
|
| 203 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
| 204 |
+
)
|
| 205 |
+
self.up_blocks.append(up_block)
|
| 206 |
+
prev_output_channel = output_channel
|
| 207 |
+
|
| 208 |
+
# out
|
| 209 |
+
self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)
|
| 210 |
+
self.conv_act = nn.SiLU()
|
| 211 |
+
self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
|
| 212 |
+
|
| 213 |
+
self.skeleton_adapter = Adapter(cin=int(3*64), channels=[320, 640, 1280, 1280][:4], nums_rb=2, ksize=1, sk=True, use_conv=False)
|
| 214 |
+
adapter_weight = torch.load('./FollowYourPose/checkpoints/pose_encoder.pth')
|
| 215 |
+
self.skeleton_adapter.load_state_dict(adapter_weight)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def set_attention_slice(self, slice_size):
|
| 219 |
+
r"""
|
| 220 |
+
Enable sliced attention computation.
|
| 221 |
+
|
| 222 |
+
When this option is enabled, the attention module will split the input tensor in slices, to compute attention
|
| 223 |
+
in several steps. This is useful to save some memory in exchange for a small speed decrease.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
|
| 227 |
+
When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
|
| 228 |
+
`"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
|
| 229 |
+
provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
|
| 230 |
+
must be a multiple of `slice_size`.
|
| 231 |
+
"""
|
| 232 |
+
sliceable_head_dims = []
|
| 233 |
+
|
| 234 |
+
def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
|
| 235 |
+
if hasattr(module, "set_attention_slice"):
|
| 236 |
+
sliceable_head_dims.append(module.sliceable_head_dim)
|
| 237 |
+
|
| 238 |
+
for child in module.children():
|
| 239 |
+
fn_recursive_retrieve_slicable_dims(child)
|
| 240 |
+
|
| 241 |
+
# retrieve number of attention layers
|
| 242 |
+
for module in self.children():
|
| 243 |
+
fn_recursive_retrieve_slicable_dims(module)
|
| 244 |
+
|
| 245 |
+
num_slicable_layers = len(sliceable_head_dims)
|
| 246 |
+
|
| 247 |
+
if slice_size == "auto":
|
| 248 |
+
# half the attention head size is usually a good trade-off between
|
| 249 |
+
# speed and memory
|
| 250 |
+
slice_size = [dim // 2 for dim in sliceable_head_dims]
|
| 251 |
+
elif slice_size == "max":
|
| 252 |
+
# make smallest slice possible
|
| 253 |
+
slice_size = num_slicable_layers * [1]
|
| 254 |
+
|
| 255 |
+
slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
|
| 256 |
+
|
| 257 |
+
if len(slice_size) != len(sliceable_head_dims):
|
| 258 |
+
raise ValueError(
|
| 259 |
+
f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
|
| 260 |
+
f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
for i in range(len(slice_size)):
|
| 264 |
+
size = slice_size[i]
|
| 265 |
+
dim = sliceable_head_dims[i]
|
| 266 |
+
if size is not None and size > dim:
|
| 267 |
+
raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
|
| 268 |
+
|
| 269 |
+
# Recursively walk through all the children.
|
| 270 |
+
# Any children which exposes the set_attention_slice method
|
| 271 |
+
# gets the message
|
| 272 |
+
def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
|
| 273 |
+
if hasattr(module, "set_attention_slice"):
|
| 274 |
+
module.set_attention_slice(slice_size.pop())
|
| 275 |
+
|
| 276 |
+
for child in module.children():
|
| 277 |
+
fn_recursive_set_attention_slice(child, slice_size)
|
| 278 |
+
|
| 279 |
+
reversed_slice_size = list(reversed(slice_size))
|
| 280 |
+
for module in self.children():
|
| 281 |
+
fn_recursive_set_attention_slice(module, reversed_slice_size)
|
| 282 |
+
|
| 283 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 284 |
+
if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
|
| 285 |
+
module.gradient_checkpointing = value
|
| 286 |
+
|
| 287 |
+
def forward(
|
| 288 |
+
self,
|
| 289 |
+
sample: torch.FloatTensor,
|
| 290 |
+
timestep: Union[torch.Tensor, float, int],
|
| 291 |
+
encoder_hidden_states: torch.Tensor,
|
| 292 |
+
class_labels: Optional[torch.Tensor] = None,
|
| 293 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 294 |
+
return_dict: bool = True,
|
| 295 |
+
skeleton: Optional[torch.FloatTensor] = None,
|
| 296 |
+
train_or_sample: str = 'train',
|
| 297 |
+
) -> Union[UNet3DConditionOutput, Tuple]:
|
| 298 |
+
r"""
|
| 299 |
+
Args:
|
| 300 |
+
sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
|
| 301 |
+
timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
|
| 302 |
+
encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
|
| 303 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 304 |
+
Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
|
| 305 |
+
|
| 306 |
+
Returns:
|
| 307 |
+
[`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
|
| 308 |
+
[`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
|
| 309 |
+
returning a tuple, the first element is the sample tensor.
|
| 310 |
+
"""
|
| 311 |
+
# By default samples have to be AT least a multiple of the overall upsampling factor.
|
| 312 |
+
# The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
|
| 313 |
+
# However, the upsampling interpolation output size can be forced to fit any upsampling size
|
| 314 |
+
# on the fly if necessary.
|
| 315 |
+
default_overall_up_factor = 2**self.num_upsamplers
|
| 316 |
+
|
| 317 |
+
# upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
|
| 318 |
+
forward_upsample_size = False
|
| 319 |
+
upsample_size = None
|
| 320 |
+
|
| 321 |
+
if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
|
| 322 |
+
logger.info("Forward upsample size to force interpolation output size.")
|
| 323 |
+
forward_upsample_size = True
|
| 324 |
+
|
| 325 |
+
# prepare attention_mask
|
| 326 |
+
if attention_mask is not None:
|
| 327 |
+
attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
|
| 328 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 329 |
+
|
| 330 |
+
# center input if necessary
|
| 331 |
+
if self.config.center_input_sample:
|
| 332 |
+
sample = 2 * sample - 1.0
|
| 333 |
+
|
| 334 |
+
# time
|
| 335 |
+
timesteps = timestep
|
| 336 |
+
if not torch.is_tensor(timesteps):
|
| 337 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
| 338 |
+
is_mps = sample.device.type == "mps"
|
| 339 |
+
if isinstance(timestep, float):
|
| 340 |
+
dtype = torch.float32 if is_mps else torch.float64
|
| 341 |
+
else:
|
| 342 |
+
dtype = torch.int32 if is_mps else torch.int64
|
| 343 |
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
| 344 |
+
elif len(timesteps.shape) == 0:
|
| 345 |
+
timesteps = timesteps[None].to(sample.device)
|
| 346 |
+
|
| 347 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 348 |
+
timesteps = timesteps.expand(sample.shape[0])
|
| 349 |
+
|
| 350 |
+
t_emb = self.time_proj(timesteps)
|
| 351 |
+
|
| 352 |
+
# timesteps does not contain any weights and will always return f32 tensors
|
| 353 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
| 354 |
+
# there might be better ways to encapsulate this.
|
| 355 |
+
t_emb = t_emb.to(dtype=self.dtype)
|
| 356 |
+
emb = self.time_embedding(t_emb)
|
| 357 |
+
|
| 358 |
+
if self.class_embedding is not None:
|
| 359 |
+
if class_labels is None:
|
| 360 |
+
raise ValueError("class_labels should be provided when num_class_embeds > 0")
|
| 361 |
+
|
| 362 |
+
if self.config.class_embed_type == "timestep":
|
| 363 |
+
class_labels = self.time_proj(class_labels)
|
| 364 |
+
|
| 365 |
+
class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
|
| 366 |
+
emb = emb + class_emb
|
| 367 |
+
|
| 368 |
+
# pre-process
|
| 369 |
+
sample = self.conv_in(sample)
|
| 370 |
+
|
| 371 |
+
# down
|
| 372 |
+
down_block_res_samples = (sample,)
|
| 373 |
+
features_adapter = self.skeleton_adapter(skeleton)
|
| 374 |
+
|
| 375 |
+
for idx, downsample_block in enumerate(self.down_blocks):
|
| 376 |
+
|
| 377 |
+
if train_or_sample == 'train':
|
| 378 |
+
skeleton_feature = None
|
| 379 |
+
else:
|
| 380 |
+
skeleton_feature = features_adapter[idx]
|
| 381 |
+
|
| 382 |
+
if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
|
| 383 |
+
sample, res_samples = downsample_block(
|
| 384 |
+
hidden_states=sample,
|
| 385 |
+
temb=emb,
|
| 386 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 387 |
+
attention_mask=attention_mask,
|
| 388 |
+
features_adapter=skeleton_feature
|
| 389 |
+
)
|
| 390 |
+
else:
|
| 391 |
+
sample, res_samples = downsample_block(hidden_states=sample, temb=emb, features_adapter=skeleton_feature)
|
| 392 |
+
|
| 393 |
+
down_block_res_samples += res_samples
|
| 394 |
+
|
| 395 |
+
# mid
|
| 396 |
+
sample = self.mid_block(
|
| 397 |
+
sample, emb, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
# up
|
| 401 |
+
for i, upsample_block in enumerate(self.up_blocks):
|
| 402 |
+
is_final_block = i == len(self.up_blocks) - 1
|
| 403 |
+
|
| 404 |
+
res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
|
| 405 |
+
down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
|
| 406 |
+
|
| 407 |
+
# if we have not reached the final block and need to forward the
|
| 408 |
+
# upsample size, we do it here
|
| 409 |
+
if not is_final_block and forward_upsample_size:
|
| 410 |
+
upsample_size = down_block_res_samples[-1].shape[2:]
|
| 411 |
+
|
| 412 |
+
if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
|
| 413 |
+
sample = upsample_block(
|
| 414 |
+
hidden_states=sample,
|
| 415 |
+
temb=emb,
|
| 416 |
+
res_hidden_states_tuple=res_samples,
|
| 417 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 418 |
+
upsample_size=upsample_size,
|
| 419 |
+
attention_mask=attention_mask,
|
| 420 |
+
)
|
| 421 |
+
else:
|
| 422 |
+
sample = upsample_block(
|
| 423 |
+
hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size
|
| 424 |
+
)
|
| 425 |
+
# post-process
|
| 426 |
+
sample = self.conv_norm_out(sample)
|
| 427 |
+
sample = self.conv_act(sample)
|
| 428 |
+
sample = self.conv_out(sample)
|
| 429 |
+
|
| 430 |
+
if not return_dict:
|
| 431 |
+
return (sample,)
|
| 432 |
+
|
| 433 |
+
return UNet3DConditionOutput(sample=sample)
|
| 434 |
+
|
| 435 |
+
@classmethod
|
| 436 |
+
def from_pretrained_2d(cls, pretrained_model_path, subfolder=None):
|
| 437 |
+
if subfolder is not None:
|
| 438 |
+
pretrained_model_path = os.path.join(pretrained_model_path, subfolder)
|
| 439 |
+
|
| 440 |
+
config_file = os.path.join(pretrained_model_path, 'config.json')
|
| 441 |
+
if not os.path.isfile(config_file):
|
| 442 |
+
raise RuntimeError(f"{config_file} does not exist")
|
| 443 |
+
with open(config_file, "r") as f:
|
| 444 |
+
config = json.load(f)
|
| 445 |
+
config["_class_name"] = cls.__name__
|
| 446 |
+
config["down_block_types"] = [
|
| 447 |
+
"CrossAttnDownBlock3D",
|
| 448 |
+
"CrossAttnDownBlock3D",
|
| 449 |
+
"CrossAttnDownBlock3D",
|
| 450 |
+
"DownBlock3D"
|
| 451 |
+
]
|
| 452 |
+
config["up_block_types"] = [
|
| 453 |
+
"UpBlock3D",
|
| 454 |
+
"CrossAttnUpBlock3D",
|
| 455 |
+
"CrossAttnUpBlock3D",
|
| 456 |
+
"CrossAttnUpBlock3D"
|
| 457 |
+
]
|
| 458 |
+
|
| 459 |
+
from diffusers.utils import WEIGHTS_NAME
|
| 460 |
+
model = cls.from_config(config)
|
| 461 |
+
model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)
|
| 462 |
+
if not os.path.isfile(model_file):
|
| 463 |
+
raise RuntimeError(f"{model_file} does not exist")
|
| 464 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 465 |
+
for k, v in model.state_dict().items():
|
| 466 |
+
if '_temp.' in k:
|
| 467 |
+
state_dict.update({k: v})
|
| 468 |
+
model.load_state_dict(state_dict, strict=False)
|
| 469 |
+
|
| 470 |
+
return model
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class Adapter(nn.Module):
|
| 476 |
+
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True):
|
| 477 |
+
super(Adapter, self).__init__()
|
| 478 |
+
self.unshuffle = nn.PixelUnshuffle(8)
|
| 479 |
+
self.channels = channels
|
| 480 |
+
self.nums_rb = nums_rb
|
| 481 |
+
self.body = []
|
| 482 |
+
for i in range(len(channels)):
|
| 483 |
+
for j in range(nums_rb):
|
| 484 |
+
if (i!=0) and (j==0):
|
| 485 |
+
self.body.append(ResnetBlock(channels[i-1], channels[i], down=True, ksize=ksize, sk=sk, use_conv=use_conv))
|
| 486 |
+
else:
|
| 487 |
+
self.body.append(ResnetBlock(channels[i], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv))
|
| 488 |
+
self.body = nn.ModuleList(self.body)
|
| 489 |
+
self.conv_in = nn.Conv2d(cin,channels[0], 3, 1, 1)
|
| 490 |
+
|
| 491 |
+
def forward(self, x):
|
| 492 |
+
b, t, c, h, w = x.shape
|
| 493 |
+
x = rearrange(x, 'b t c h w -> (b t) c h w')
|
| 494 |
+
# unshuffle
|
| 495 |
+
x = self.unshuffle(x)
|
| 496 |
+
# extract features
|
| 497 |
+
features = []
|
| 498 |
+
x = self.conv_in(x)
|
| 499 |
+
for i in range(len(self.channels)):
|
| 500 |
+
for j in range(self.nums_rb):
|
| 501 |
+
idx = i*self.nums_rb +j
|
| 502 |
+
x = self.body[idx](x)
|
| 503 |
+
features.append(x)
|
| 504 |
+
|
| 505 |
+
features = [ rearrange(fn, '(b t) c h w -> b c t h w', b=b, t=t) for fn in features]
|
| 506 |
+
return features
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
class ResnetBlock(nn.Module):
|
| 511 |
+
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
|
| 512 |
+
super().__init__()
|
| 513 |
+
ps = ksize//2
|
| 514 |
+
if in_c != out_c or sk==False:
|
| 515 |
+
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
| 516 |
+
else:
|
| 517 |
+
# print('n_in')
|
| 518 |
+
self.in_conv = None
|
| 519 |
+
self.block1 = nn.Conv2d(out_c, out_c, 3, 1, 1)
|
| 520 |
+
self.act = nn.ReLU()
|
| 521 |
+
self.block2 = nn.Conv2d(out_c, out_c, ksize, 1, ps)
|
| 522 |
+
if sk==False:
|
| 523 |
+
self.skep = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
| 524 |
+
else:
|
| 525 |
+
self.skep = None
|
| 526 |
+
|
| 527 |
+
self.down = down
|
| 528 |
+
if self.down == True:
|
| 529 |
+
self.down_opt = Downsample(in_c, use_conv=use_conv)
|
| 530 |
+
|
| 531 |
+
def forward(self, x):
|
| 532 |
+
if self.down == True:
|
| 533 |
+
x = self.down_opt(x)
|
| 534 |
+
if self.in_conv is not None: # edit
|
| 535 |
+
x = self.in_conv(x)
|
| 536 |
+
|
| 537 |
+
h = self.block1(x)
|
| 538 |
+
h = self.act(h)
|
| 539 |
+
h = self.block2(h)
|
| 540 |
+
if self.skep is not None:
|
| 541 |
+
return h + self.skep(x)
|
| 542 |
+
else:
|
| 543 |
+
return h + x
|
| 544 |
+
|
| 545 |
+
class Downsample(nn.Module):
|
| 546 |
+
"""
|
| 547 |
+
A downsampling layer with an optional convolution.
|
| 548 |
+
:param channels: channels in the inputs and outputs.
|
| 549 |
+
:param use_conv: a bool determining if a convolution is applied.
|
| 550 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
| 551 |
+
downsampling occurs in the inner-two dimensions.
|
| 552 |
+
"""
|
| 553 |
+
|
| 554 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
|
| 555 |
+
super().__init__()
|
| 556 |
+
self.channels = channels
|
| 557 |
+
self.out_channels = out_channels or channels
|
| 558 |
+
self.use_conv = use_conv
|
| 559 |
+
self.dims = dims
|
| 560 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
| 561 |
+
if use_conv:
|
| 562 |
+
self.op = conv_nd(
|
| 563 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
|
| 564 |
+
)
|
| 565 |
+
else:
|
| 566 |
+
assert self.channels == self.out_channels
|
| 567 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
| 568 |
+
|
| 569 |
+
def forward(self, x):
|
| 570 |
+
assert x.shape[1] == self.channels
|
| 571 |
+
return self.op(x)
|
FollowYourPose/followyourpose/models/unet_blocks.py
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
from .attention import Transformer3DModel
|
| 7 |
+
from .resnet import Downsample3D, ResnetBlock3D, Upsample3D
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def get_down_block(
|
| 11 |
+
down_block_type,
|
| 12 |
+
num_layers,
|
| 13 |
+
in_channels,
|
| 14 |
+
out_channels,
|
| 15 |
+
temb_channels,
|
| 16 |
+
add_downsample,
|
| 17 |
+
resnet_eps,
|
| 18 |
+
resnet_act_fn,
|
| 19 |
+
attn_num_head_channels,
|
| 20 |
+
resnet_groups=None,
|
| 21 |
+
cross_attention_dim=None,
|
| 22 |
+
downsample_padding=None,
|
| 23 |
+
dual_cross_attention=False,
|
| 24 |
+
use_linear_projection=False,
|
| 25 |
+
only_cross_attention=False,
|
| 26 |
+
upcast_attention=False,
|
| 27 |
+
resnet_time_scale_shift="default",
|
| 28 |
+
):
|
| 29 |
+
down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
|
| 30 |
+
if down_block_type == "DownBlock3D":
|
| 31 |
+
return DownBlock3D(
|
| 32 |
+
num_layers=num_layers,
|
| 33 |
+
in_channels=in_channels,
|
| 34 |
+
out_channels=out_channels,
|
| 35 |
+
temb_channels=temb_channels,
|
| 36 |
+
add_downsample=add_downsample,
|
| 37 |
+
resnet_eps=resnet_eps,
|
| 38 |
+
resnet_act_fn=resnet_act_fn,
|
| 39 |
+
resnet_groups=resnet_groups,
|
| 40 |
+
downsample_padding=downsample_padding,
|
| 41 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
| 42 |
+
)
|
| 43 |
+
elif down_block_type == "CrossAttnDownBlock3D":
|
| 44 |
+
if cross_attention_dim is None:
|
| 45 |
+
raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
|
| 46 |
+
return CrossAttnDownBlock3D(
|
| 47 |
+
num_layers=num_layers,
|
| 48 |
+
in_channels=in_channels,
|
| 49 |
+
out_channels=out_channels,
|
| 50 |
+
temb_channels=temb_channels,
|
| 51 |
+
add_downsample=add_downsample,
|
| 52 |
+
resnet_eps=resnet_eps,
|
| 53 |
+
resnet_act_fn=resnet_act_fn,
|
| 54 |
+
resnet_groups=resnet_groups,
|
| 55 |
+
downsample_padding=downsample_padding,
|
| 56 |
+
cross_attention_dim=cross_attention_dim,
|
| 57 |
+
attn_num_head_channels=attn_num_head_channels,
|
| 58 |
+
dual_cross_attention=dual_cross_attention,
|
| 59 |
+
use_linear_projection=use_linear_projection,
|
| 60 |
+
only_cross_attention=only_cross_attention,
|
| 61 |
+
upcast_attention=upcast_attention,
|
| 62 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
| 63 |
+
)
|
| 64 |
+
raise ValueError(f"{down_block_type} does not exist.")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_up_block(
|
| 68 |
+
up_block_type,
|
| 69 |
+
num_layers,
|
| 70 |
+
in_channels,
|
| 71 |
+
out_channels,
|
| 72 |
+
prev_output_channel,
|
| 73 |
+
temb_channels,
|
| 74 |
+
add_upsample,
|
| 75 |
+
resnet_eps,
|
| 76 |
+
resnet_act_fn,
|
| 77 |
+
attn_num_head_channels,
|
| 78 |
+
resnet_groups=None,
|
| 79 |
+
cross_attention_dim=None,
|
| 80 |
+
dual_cross_attention=False,
|
| 81 |
+
use_linear_projection=False,
|
| 82 |
+
only_cross_attention=False,
|
| 83 |
+
upcast_attention=False,
|
| 84 |
+
resnet_time_scale_shift="default",
|
| 85 |
+
):
|
| 86 |
+
up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
|
| 87 |
+
if up_block_type == "UpBlock3D":
|
| 88 |
+
return UpBlock3D(
|
| 89 |
+
num_layers=num_layers,
|
| 90 |
+
in_channels=in_channels,
|
| 91 |
+
out_channels=out_channels,
|
| 92 |
+
prev_output_channel=prev_output_channel,
|
| 93 |
+
temb_channels=temb_channels,
|
| 94 |
+
add_upsample=add_upsample,
|
| 95 |
+
resnet_eps=resnet_eps,
|
| 96 |
+
resnet_act_fn=resnet_act_fn,
|
| 97 |
+
resnet_groups=resnet_groups,
|
| 98 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
| 99 |
+
)
|
| 100 |
+
elif up_block_type == "CrossAttnUpBlock3D":
|
| 101 |
+
if cross_attention_dim is None:
|
| 102 |
+
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
|
| 103 |
+
return CrossAttnUpBlock3D(
|
| 104 |
+
num_layers=num_layers,
|
| 105 |
+
in_channels=in_channels,
|
| 106 |
+
out_channels=out_channels,
|
| 107 |
+
prev_output_channel=prev_output_channel,
|
| 108 |
+
temb_channels=temb_channels,
|
| 109 |
+
add_upsample=add_upsample,
|
| 110 |
+
resnet_eps=resnet_eps,
|
| 111 |
+
resnet_act_fn=resnet_act_fn,
|
| 112 |
+
resnet_groups=resnet_groups,
|
| 113 |
+
cross_attention_dim=cross_attention_dim,
|
| 114 |
+
attn_num_head_channels=attn_num_head_channels,
|
| 115 |
+
dual_cross_attention=dual_cross_attention,
|
| 116 |
+
use_linear_projection=use_linear_projection,
|
| 117 |
+
only_cross_attention=only_cross_attention,
|
| 118 |
+
upcast_attention=upcast_attention,
|
| 119 |
+
resnet_time_scale_shift=resnet_time_scale_shift,
|
| 120 |
+
)
|
| 121 |
+
raise ValueError(f"{up_block_type} does not exist.")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class UNetMidBlock3DCrossAttn(nn.Module):
|
| 125 |
+
def __init__(
|
| 126 |
+
self,
|
| 127 |
+
in_channels: int,
|
| 128 |
+
temb_channels: int,
|
| 129 |
+
dropout: float = 0.0,
|
| 130 |
+
num_layers: int = 1,
|
| 131 |
+
resnet_eps: float = 1e-6,
|
| 132 |
+
resnet_time_scale_shift: str = "default",
|
| 133 |
+
resnet_act_fn: str = "swish",
|
| 134 |
+
resnet_groups: int = 32,
|
| 135 |
+
resnet_pre_norm: bool = True,
|
| 136 |
+
attn_num_head_channels=1,
|
| 137 |
+
output_scale_factor=1.0,
|
| 138 |
+
cross_attention_dim=1280,
|
| 139 |
+
dual_cross_attention=False,
|
| 140 |
+
use_linear_projection=False,
|
| 141 |
+
upcast_attention=False,
|
| 142 |
+
):
|
| 143 |
+
super().__init__()
|
| 144 |
+
|
| 145 |
+
self.has_cross_attention = True
|
| 146 |
+
self.attn_num_head_channels = attn_num_head_channels
|
| 147 |
+
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
|
| 148 |
+
|
| 149 |
+
# there is always at least one resnet
|
| 150 |
+
resnets = [
|
| 151 |
+
ResnetBlock3D(
|
| 152 |
+
in_channels=in_channels,
|
| 153 |
+
out_channels=in_channels,
|
| 154 |
+
temb_channels=temb_channels,
|
| 155 |
+
eps=resnet_eps,
|
| 156 |
+
groups=resnet_groups,
|
| 157 |
+
dropout=dropout,
|
| 158 |
+
time_embedding_norm=resnet_time_scale_shift,
|
| 159 |
+
non_linearity=resnet_act_fn,
|
| 160 |
+
output_scale_factor=output_scale_factor,
|
| 161 |
+
pre_norm=resnet_pre_norm,
|
| 162 |
+
)
|
| 163 |
+
]
|
| 164 |
+
attentions = []
|
| 165 |
+
|
| 166 |
+
for _ in range(num_layers):
|
| 167 |
+
if dual_cross_attention:
|
| 168 |
+
raise NotImplementedError
|
| 169 |
+
attentions.append(
|
| 170 |
+
Transformer3DModel(
|
| 171 |
+
attn_num_head_channels,
|
| 172 |
+
in_channels // attn_num_head_channels,
|
| 173 |
+
in_channels=in_channels,
|
| 174 |
+
num_layers=1,
|
| 175 |
+
cross_attention_dim=cross_attention_dim,
|
| 176 |
+
norm_num_groups=resnet_groups,
|
| 177 |
+
use_linear_projection=use_linear_projection,
|
| 178 |
+
upcast_attention=upcast_attention,
|
| 179 |
+
)
|
| 180 |
+
)
|
| 181 |
+
resnets.append(
|
| 182 |
+
ResnetBlock3D(
|
| 183 |
+
in_channels=in_channels,
|
| 184 |
+
out_channels=in_channels,
|
| 185 |
+
temb_channels=temb_channels,
|
| 186 |
+
eps=resnet_eps,
|
| 187 |
+
groups=resnet_groups,
|
| 188 |
+
dropout=dropout,
|
| 189 |
+
time_embedding_norm=resnet_time_scale_shift,
|
| 190 |
+
non_linearity=resnet_act_fn,
|
| 191 |
+
output_scale_factor=output_scale_factor,
|
| 192 |
+
pre_norm=resnet_pre_norm,
|
| 193 |
+
)
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
self.attentions = nn.ModuleList(attentions)
|
| 197 |
+
self.resnets = nn.ModuleList(resnets)
|
| 198 |
+
|
| 199 |
+
def forward(self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None):
|
| 200 |
+
hidden_states = self.resnets[0](hidden_states, temb)
|
| 201 |
+
for attn, resnet in zip(self.attentions, self.resnets[1:]):
|
| 202 |
+
hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
|
| 203 |
+
hidden_states = resnet(hidden_states, temb)
|
| 204 |
+
|
| 205 |
+
return hidden_states
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class CrossAttnDownBlock3D(nn.Module):
|
| 209 |
+
def __init__(
|
| 210 |
+
self,
|
| 211 |
+
in_channels: int,
|
| 212 |
+
out_channels: int,
|
| 213 |
+
temb_channels: int,
|
| 214 |
+
dropout: float = 0.0,
|
| 215 |
+
num_layers: int = 1,
|
| 216 |
+
resnet_eps: float = 1e-6,
|
| 217 |
+
resnet_time_scale_shift: str = "default",
|
| 218 |
+
resnet_act_fn: str = "swish",
|
| 219 |
+
resnet_groups: int = 32,
|
| 220 |
+
resnet_pre_norm: bool = True,
|
| 221 |
+
attn_num_head_channels=1,
|
| 222 |
+
cross_attention_dim=1280,
|
| 223 |
+
output_scale_factor=1.0,
|
| 224 |
+
downsample_padding=1,
|
| 225 |
+
add_downsample=True,
|
| 226 |
+
dual_cross_attention=False,
|
| 227 |
+
use_linear_projection=False,
|
| 228 |
+
only_cross_attention=False,
|
| 229 |
+
upcast_attention=False,
|
| 230 |
+
):
|
| 231 |
+
super().__init__()
|
| 232 |
+
resnets = []
|
| 233 |
+
attentions = []
|
| 234 |
+
|
| 235 |
+
self.has_cross_attention = True
|
| 236 |
+
self.attn_num_head_channels = attn_num_head_channels
|
| 237 |
+
|
| 238 |
+
for i in range(num_layers):
|
| 239 |
+
in_channels = in_channels if i == 0 else out_channels
|
| 240 |
+
resnets.append(
|
| 241 |
+
ResnetBlock3D(
|
| 242 |
+
in_channels=in_channels,
|
| 243 |
+
out_channels=out_channels,
|
| 244 |
+
temb_channels=temb_channels,
|
| 245 |
+
eps=resnet_eps,
|
| 246 |
+
groups=resnet_groups,
|
| 247 |
+
dropout=dropout,
|
| 248 |
+
time_embedding_norm=resnet_time_scale_shift,
|
| 249 |
+
non_linearity=resnet_act_fn,
|
| 250 |
+
output_scale_factor=output_scale_factor,
|
| 251 |
+
pre_norm=resnet_pre_norm,
|
| 252 |
+
)
|
| 253 |
+
)
|
| 254 |
+
if dual_cross_attention:
|
| 255 |
+
raise NotImplementedError
|
| 256 |
+
attentions.append(
|
| 257 |
+
Transformer3DModel(
|
| 258 |
+
attn_num_head_channels,
|
| 259 |
+
out_channels // attn_num_head_channels,
|
| 260 |
+
in_channels=out_channels,
|
| 261 |
+
num_layers=1,
|
| 262 |
+
cross_attention_dim=cross_attention_dim,
|
| 263 |
+
norm_num_groups=resnet_groups,
|
| 264 |
+
use_linear_projection=use_linear_projection,
|
| 265 |
+
only_cross_attention=only_cross_attention,
|
| 266 |
+
upcast_attention=upcast_attention,
|
| 267 |
+
)
|
| 268 |
+
)
|
| 269 |
+
self.attentions = nn.ModuleList(attentions)
|
| 270 |
+
self.resnets = nn.ModuleList(resnets)
|
| 271 |
+
|
| 272 |
+
if add_downsample:
|
| 273 |
+
self.downsamplers = nn.ModuleList(
|
| 274 |
+
[
|
| 275 |
+
Downsample3D(
|
| 276 |
+
out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
|
| 277 |
+
)
|
| 278 |
+
]
|
| 279 |
+
)
|
| 280 |
+
else:
|
| 281 |
+
self.downsamplers = None
|
| 282 |
+
|
| 283 |
+
self.gradient_checkpointing = False
|
| 284 |
+
|
| 285 |
+
def forward(self, hidden_states, temb=None, encoder_hidden_states=None, attention_mask=None, features_adapter=None):
|
| 286 |
+
output_states = ()
|
| 287 |
+
idx = 1
|
| 288 |
+
for resnet, attn in zip(self.resnets, self.attentions):
|
| 289 |
+
if self.training and self.gradient_checkpointing:
|
| 290 |
+
|
| 291 |
+
def create_custom_forward(module, return_dict=None):
|
| 292 |
+
def custom_forward(*inputs):
|
| 293 |
+
if return_dict is not None:
|
| 294 |
+
return module(*inputs, return_dict=return_dict)
|
| 295 |
+
else:
|
| 296 |
+
return module(*inputs)
|
| 297 |
+
|
| 298 |
+
return custom_forward
|
| 299 |
+
|
| 300 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
| 301 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
| 302 |
+
create_custom_forward(attn, return_dict=False),
|
| 303 |
+
hidden_states,
|
| 304 |
+
encoder_hidden_states,
|
| 305 |
+
)[0]
|
| 306 |
+
else:
|
| 307 |
+
hidden_states = resnet(hidden_states, temb)
|
| 308 |
+
hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
|
| 309 |
+
if ((idx+1)%3 == 0) and features_adapter is not None and len(features_adapter):
|
| 310 |
+
hidden_states = hidden_states + features_adapter
|
| 311 |
+
idx = idx + 1
|
| 312 |
+
|
| 313 |
+
output_states += (hidden_states,)
|
| 314 |
+
|
| 315 |
+
if self.downsamplers is not None:
|
| 316 |
+
for downsampler in self.downsamplers:
|
| 317 |
+
hidden_states = downsampler(hidden_states)
|
| 318 |
+
|
| 319 |
+
output_states += (hidden_states,)
|
| 320 |
+
|
| 321 |
+
return hidden_states, output_states
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class DownBlock3D(nn.Module):
|
| 325 |
+
def __init__(
|
| 326 |
+
self,
|
| 327 |
+
in_channels: int,
|
| 328 |
+
out_channels: int,
|
| 329 |
+
temb_channels: int,
|
| 330 |
+
dropout: float = 0.0,
|
| 331 |
+
num_layers: int = 1,
|
| 332 |
+
resnet_eps: float = 1e-6,
|
| 333 |
+
resnet_time_scale_shift: str = "default",
|
| 334 |
+
resnet_act_fn: str = "swish",
|
| 335 |
+
resnet_groups: int = 32,
|
| 336 |
+
resnet_pre_norm: bool = True,
|
| 337 |
+
output_scale_factor=1.0,
|
| 338 |
+
add_downsample=True,
|
| 339 |
+
downsample_padding=1,
|
| 340 |
+
):
|
| 341 |
+
super().__init__()
|
| 342 |
+
resnets = []
|
| 343 |
+
|
| 344 |
+
for i in range(num_layers):
|
| 345 |
+
in_channels = in_channels if i == 0 else out_channels
|
| 346 |
+
resnets.append(
|
| 347 |
+
ResnetBlock3D(
|
| 348 |
+
in_channels=in_channels,
|
| 349 |
+
out_channels=out_channels,
|
| 350 |
+
temb_channels=temb_channels,
|
| 351 |
+
eps=resnet_eps,
|
| 352 |
+
groups=resnet_groups,
|
| 353 |
+
dropout=dropout,
|
| 354 |
+
time_embedding_norm=resnet_time_scale_shift,
|
| 355 |
+
non_linearity=resnet_act_fn,
|
| 356 |
+
output_scale_factor=output_scale_factor,
|
| 357 |
+
pre_norm=resnet_pre_norm,
|
| 358 |
+
)
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
self.resnets = nn.ModuleList(resnets)
|
| 362 |
+
|
| 363 |
+
if add_downsample:
|
| 364 |
+
self.downsamplers = nn.ModuleList(
|
| 365 |
+
[
|
| 366 |
+
Downsample3D(
|
| 367 |
+
out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
|
| 368 |
+
)
|
| 369 |
+
]
|
| 370 |
+
)
|
| 371 |
+
else:
|
| 372 |
+
self.downsamplers = None
|
| 373 |
+
|
| 374 |
+
self.gradient_checkpointing = False
|
| 375 |
+
|
| 376 |
+
def forward(self, hidden_states, temb=None, features_adapter=None):
|
| 377 |
+
output_states = ()
|
| 378 |
+
idx = 1
|
| 379 |
+
for resnet in self.resnets:
|
| 380 |
+
if self.training and self.gradient_checkpointing:
|
| 381 |
+
|
| 382 |
+
def create_custom_forward(module):
|
| 383 |
+
def custom_forward(*inputs):
|
| 384 |
+
return module(*inputs)
|
| 385 |
+
|
| 386 |
+
return custom_forward
|
| 387 |
+
|
| 388 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
| 389 |
+
else:
|
| 390 |
+
hidden_states = resnet(hidden_states, temb)
|
| 391 |
+
if ((idx+1)%3 == 0) and features_adapter is not None and len(features_adapter):
|
| 392 |
+
hidden_states = hidden_states + features_adapter
|
| 393 |
+
idx = idx + 1
|
| 394 |
+
|
| 395 |
+
output_states += (hidden_states,)
|
| 396 |
+
|
| 397 |
+
if self.downsamplers is not None:
|
| 398 |
+
for downsampler in self.downsamplers:
|
| 399 |
+
hidden_states = downsampler(hidden_states)
|
| 400 |
+
|
| 401 |
+
output_states += (hidden_states,)
|
| 402 |
+
|
| 403 |
+
return hidden_states, output_states
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
class CrossAttnUpBlock3D(nn.Module):
|
| 407 |
+
def __init__(
|
| 408 |
+
self,
|
| 409 |
+
in_channels: int,
|
| 410 |
+
out_channels: int,
|
| 411 |
+
prev_output_channel: int,
|
| 412 |
+
temb_channels: int,
|
| 413 |
+
dropout: float = 0.0,
|
| 414 |
+
num_layers: int = 1,
|
| 415 |
+
resnet_eps: float = 1e-6,
|
| 416 |
+
resnet_time_scale_shift: str = "default",
|
| 417 |
+
resnet_act_fn: str = "swish",
|
| 418 |
+
resnet_groups: int = 32,
|
| 419 |
+
resnet_pre_norm: bool = True,
|
| 420 |
+
attn_num_head_channels=1,
|
| 421 |
+
cross_attention_dim=1280,
|
| 422 |
+
output_scale_factor=1.0,
|
| 423 |
+
add_upsample=True,
|
| 424 |
+
dual_cross_attention=False,
|
| 425 |
+
use_linear_projection=False,
|
| 426 |
+
only_cross_attention=False,
|
| 427 |
+
upcast_attention=False,
|
| 428 |
+
):
|
| 429 |
+
super().__init__()
|
| 430 |
+
resnets = []
|
| 431 |
+
attentions = []
|
| 432 |
+
|
| 433 |
+
self.has_cross_attention = True
|
| 434 |
+
self.attn_num_head_channels = attn_num_head_channels
|
| 435 |
+
|
| 436 |
+
for i in range(num_layers):
|
| 437 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
| 438 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
| 439 |
+
|
| 440 |
+
resnets.append(
|
| 441 |
+
ResnetBlock3D(
|
| 442 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
| 443 |
+
out_channels=out_channels,
|
| 444 |
+
temb_channels=temb_channels,
|
| 445 |
+
eps=resnet_eps,
|
| 446 |
+
groups=resnet_groups,
|
| 447 |
+
dropout=dropout,
|
| 448 |
+
time_embedding_norm=resnet_time_scale_shift,
|
| 449 |
+
non_linearity=resnet_act_fn,
|
| 450 |
+
output_scale_factor=output_scale_factor,
|
| 451 |
+
pre_norm=resnet_pre_norm,
|
| 452 |
+
)
|
| 453 |
+
)
|
| 454 |
+
if dual_cross_attention:
|
| 455 |
+
raise NotImplementedError
|
| 456 |
+
attentions.append(
|
| 457 |
+
Transformer3DModel(
|
| 458 |
+
attn_num_head_channels,
|
| 459 |
+
out_channels // attn_num_head_channels,
|
| 460 |
+
in_channels=out_channels,
|
| 461 |
+
num_layers=1,
|
| 462 |
+
cross_attention_dim=cross_attention_dim,
|
| 463 |
+
norm_num_groups=resnet_groups,
|
| 464 |
+
use_linear_projection=use_linear_projection,
|
| 465 |
+
only_cross_attention=only_cross_attention,
|
| 466 |
+
upcast_attention=upcast_attention,
|
| 467 |
+
)
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
self.attentions = nn.ModuleList(attentions)
|
| 471 |
+
self.resnets = nn.ModuleList(resnets)
|
| 472 |
+
|
| 473 |
+
if add_upsample:
|
| 474 |
+
self.upsamplers = nn.ModuleList([Upsample3D(out_channels, use_conv=True, out_channels=out_channels)])
|
| 475 |
+
else:
|
| 476 |
+
self.upsamplers = None
|
| 477 |
+
|
| 478 |
+
self.gradient_checkpointing = False
|
| 479 |
+
|
| 480 |
+
def forward(
|
| 481 |
+
self,
|
| 482 |
+
hidden_states,
|
| 483 |
+
res_hidden_states_tuple,
|
| 484 |
+
temb=None,
|
| 485 |
+
encoder_hidden_states=None,
|
| 486 |
+
upsample_size=None,
|
| 487 |
+
attention_mask=None,
|
| 488 |
+
):
|
| 489 |
+
for resnet, attn in zip(self.resnets, self.attentions):
|
| 490 |
+
# pop res hidden states
|
| 491 |
+
res_hidden_states = res_hidden_states_tuple[-1]
|
| 492 |
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
| 493 |
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
| 494 |
+
|
| 495 |
+
if self.training and self.gradient_checkpointing:
|
| 496 |
+
|
| 497 |
+
def create_custom_forward(module, return_dict=None):
|
| 498 |
+
def custom_forward(*inputs):
|
| 499 |
+
if return_dict is not None:
|
| 500 |
+
return module(*inputs, return_dict=return_dict)
|
| 501 |
+
else:
|
| 502 |
+
return module(*inputs)
|
| 503 |
+
|
| 504 |
+
return custom_forward
|
| 505 |
+
|
| 506 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
| 507 |
+
hidden_states = torch.utils.checkpoint.checkpoint(
|
| 508 |
+
create_custom_forward(attn, return_dict=False),
|
| 509 |
+
hidden_states,
|
| 510 |
+
encoder_hidden_states,
|
| 511 |
+
)[0]
|
| 512 |
+
else:
|
| 513 |
+
hidden_states = resnet(hidden_states, temb)
|
| 514 |
+
hidden_states = attn(hidden_states, encoder_hidden_states=encoder_hidden_states).sample
|
| 515 |
+
|
| 516 |
+
if self.upsamplers is not None:
|
| 517 |
+
for upsampler in self.upsamplers:
|
| 518 |
+
hidden_states = upsampler(hidden_states, upsample_size)
|
| 519 |
+
|
| 520 |
+
return hidden_states
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class UpBlock3D(nn.Module):
|
| 524 |
+
def __init__(
|
| 525 |
+
self,
|
| 526 |
+
in_channels: int,
|
| 527 |
+
prev_output_channel: int,
|
| 528 |
+
out_channels: int,
|
| 529 |
+
temb_channels: int,
|
| 530 |
+
dropout: float = 0.0,
|
| 531 |
+
num_layers: int = 1,
|
| 532 |
+
resnet_eps: float = 1e-6,
|
| 533 |
+
resnet_time_scale_shift: str = "default",
|
| 534 |
+
resnet_act_fn: str = "swish",
|
| 535 |
+
resnet_groups: int = 32,
|
| 536 |
+
resnet_pre_norm: bool = True,
|
| 537 |
+
output_scale_factor=1.0,
|
| 538 |
+
add_upsample=True,
|
| 539 |
+
):
|
| 540 |
+
super().__init__()
|
| 541 |
+
resnets = []
|
| 542 |
+
|
| 543 |
+
for i in range(num_layers):
|
| 544 |
+
res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
|
| 545 |
+
resnet_in_channels = prev_output_channel if i == 0 else out_channels
|
| 546 |
+
|
| 547 |
+
resnets.append(
|
| 548 |
+
ResnetBlock3D(
|
| 549 |
+
in_channels=resnet_in_channels + res_skip_channels,
|
| 550 |
+
out_channels=out_channels,
|
| 551 |
+
temb_channels=temb_channels,
|
| 552 |
+
eps=resnet_eps,
|
| 553 |
+
groups=resnet_groups,
|
| 554 |
+
dropout=dropout,
|
| 555 |
+
time_embedding_norm=resnet_time_scale_shift,
|
| 556 |
+
non_linearity=resnet_act_fn,
|
| 557 |
+
output_scale_factor=output_scale_factor,
|
| 558 |
+
pre_norm=resnet_pre_norm,
|
| 559 |
+
)
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
self.resnets = nn.ModuleList(resnets)
|
| 563 |
+
|
| 564 |
+
if add_upsample:
|
| 565 |
+
self.upsamplers = nn.ModuleList([Upsample3D(out_channels, use_conv=True, out_channels=out_channels)])
|
| 566 |
+
else:
|
| 567 |
+
self.upsamplers = None
|
| 568 |
+
|
| 569 |
+
self.gradient_checkpointing = False
|
| 570 |
+
|
| 571 |
+
def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
|
| 572 |
+
for resnet in self.resnets:
|
| 573 |
+
# pop res hidden states
|
| 574 |
+
res_hidden_states = res_hidden_states_tuple[-1]
|
| 575 |
+
res_hidden_states_tuple = res_hidden_states_tuple[:-1]
|
| 576 |
+
hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
|
| 577 |
+
|
| 578 |
+
if self.training and self.gradient_checkpointing:
|
| 579 |
+
|
| 580 |
+
def create_custom_forward(module):
|
| 581 |
+
def custom_forward(*inputs):
|
| 582 |
+
return module(*inputs)
|
| 583 |
+
|
| 584 |
+
return custom_forward
|
| 585 |
+
|
| 586 |
+
hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
|
| 587 |
+
else:
|
| 588 |
+
hidden_states = resnet(hidden_states, temb)
|
| 589 |
+
|
| 590 |
+
if self.upsamplers is not None:
|
| 591 |
+
for upsampler in self.upsamplers:
|
| 592 |
+
hidden_states = upsampler(hidden_states, upsample_size)
|
| 593 |
+
|
| 594 |
+
return hidden_states
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def conv_nd(dims, in_channels, out_channels, kernel_size, **kwargs):
|
| 600 |
+
"""
|
| 601 |
+
Create a 1D, 2D, or 3D convolution module.
|
| 602 |
+
"""
|
| 603 |
+
if dims == 1:
|
| 604 |
+
return nn.Conv1d(in_channels, out_channels, kernel_size, **kwargs)
|
| 605 |
+
elif dims == 2:
|
| 606 |
+
return nn.Conv2d(in_channels, out_channels, kernel_size, **kwargs)
|
| 607 |
+
elif dims == 3:
|
| 608 |
+
if isinstance(kernel_size, int):
|
| 609 |
+
kernel_size = (1, *((kernel_size,) * 2))
|
| 610 |
+
if 'stride' in kwargs.keys():
|
| 611 |
+
if isinstance(kwargs['stride'], int):
|
| 612 |
+
kwargs['stride'] = (1, *((kwargs['stride'],) * 2))
|
| 613 |
+
if 'padding' in kwargs.keys():
|
| 614 |
+
if isinstance(kwargs['padding'], int):
|
| 615 |
+
kwargs['padding'] = (0, *((kwargs['padding'],) * 2))
|
| 616 |
+
return nn.Conv3d(in_channels, out_channels, kernel_size, **kwargs)
|
| 617 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
| 622 |
+
"""
|
| 623 |
+
Create a 1D, 2D, or 3D average pooling module.
|
| 624 |
+
"""
|
| 625 |
+
if dims == 1:
|
| 626 |
+
return nn.AvgPool1d(*args, **kwargs)
|
| 627 |
+
elif dims == 2:
|
| 628 |
+
return nn.AvgPool2d(*args, **kwargs)
|
| 629 |
+
elif dims == 3:
|
| 630 |
+
return nn.AvgPool3d(*args, **kwargs)
|
| 631 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
FollowYourPose/followyourpose/pipelines/__pycache__/pipeline_followyourpose.cpython-38.pyc
ADDED
|
Binary file (12.7 kB). View file
|
|
|
FollowYourPose/followyourpose/pipelines/__pycache__/pipeline_tuneavideo.cpython-38.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
FollowYourPose/followyourpose/pipelines/pipeline_followyourpose.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
from typing import Callable, List, Optional, Union
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from diffusers.utils import is_accelerate_available
|
| 11 |
+
from packaging import version
|
| 12 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 13 |
+
|
| 14 |
+
from diffusers.configuration_utils import FrozenDict
|
| 15 |
+
from diffusers.models import AutoencoderKL
|
| 16 |
+
from diffusers.pipeline_utils import DiffusionPipeline
|
| 17 |
+
from diffusers.schedulers import (
|
| 18 |
+
DDIMScheduler,
|
| 19 |
+
DPMSolverMultistepScheduler,
|
| 20 |
+
EulerAncestralDiscreteScheduler,
|
| 21 |
+
EulerDiscreteScheduler,
|
| 22 |
+
LMSDiscreteScheduler,
|
| 23 |
+
PNDMScheduler,
|
| 24 |
+
)
|
| 25 |
+
from diffusers.utils import deprecate, logging, BaseOutput
|
| 26 |
+
|
| 27 |
+
from einops import rearrange
|
| 28 |
+
|
| 29 |
+
from ..models.unet import UNet3DConditionModel
|
| 30 |
+
from torchvision import transforms
|
| 31 |
+
import torchvision.transforms._transforms_video as transforms_video
|
| 32 |
+
import decord
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class FollowYourPosePipelineOutput(BaseOutput):
|
| 40 |
+
videos: Union[torch.Tensor, np.ndarray]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class FollowYourPosePipeline(DiffusionPipeline):
|
| 44 |
+
_optional_components = []
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
vae: AutoencoderKL,
|
| 49 |
+
text_encoder: CLIPTextModel,
|
| 50 |
+
tokenizer: CLIPTokenizer,
|
| 51 |
+
unet: UNet3DConditionModel,
|
| 52 |
+
scheduler: Union[
|
| 53 |
+
DDIMScheduler,
|
| 54 |
+
PNDMScheduler,
|
| 55 |
+
LMSDiscreteScheduler,
|
| 56 |
+
EulerDiscreteScheduler,
|
| 57 |
+
EulerAncestralDiscreteScheduler,
|
| 58 |
+
DPMSolverMultistepScheduler,
|
| 59 |
+
],
|
| 60 |
+
):
|
| 61 |
+
super().__init__()
|
| 62 |
+
|
| 63 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
| 64 |
+
deprecation_message = (
|
| 65 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
| 66 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
| 67 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
| 68 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
| 69 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
| 70 |
+
" file"
|
| 71 |
+
)
|
| 72 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
| 73 |
+
new_config = dict(scheduler.config)
|
| 74 |
+
new_config["steps_offset"] = 1
|
| 75 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 76 |
+
|
| 77 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
| 78 |
+
deprecation_message = (
|
| 79 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
| 80 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
| 81 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
| 82 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
| 83 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
| 84 |
+
)
|
| 85 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
| 86 |
+
new_config = dict(scheduler.config)
|
| 87 |
+
new_config["clip_sample"] = False
|
| 88 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 89 |
+
|
| 90 |
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
| 91 |
+
version.parse(unet.config._diffusers_version).base_version
|
| 92 |
+
) < version.parse("0.9.0.dev0")
|
| 93 |
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
| 94 |
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
| 95 |
+
deprecation_message = (
|
| 96 |
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
| 97 |
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
| 98 |
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
| 99 |
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
| 100 |
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
| 101 |
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
| 102 |
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
| 103 |
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
| 104 |
+
" the `unet/config.json` file"
|
| 105 |
+
)
|
| 106 |
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
| 107 |
+
new_config = dict(unet.config)
|
| 108 |
+
new_config["sample_size"] = 64
|
| 109 |
+
unet._internal_dict = FrozenDict(new_config)
|
| 110 |
+
|
| 111 |
+
self.register_modules(
|
| 112 |
+
vae=vae,
|
| 113 |
+
text_encoder=text_encoder,
|
| 114 |
+
tokenizer=tokenizer,
|
| 115 |
+
unet=unet,
|
| 116 |
+
scheduler=scheduler,
|
| 117 |
+
)
|
| 118 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 119 |
+
|
| 120 |
+
def enable_vae_slicing(self):
|
| 121 |
+
self.vae.enable_slicing()
|
| 122 |
+
|
| 123 |
+
def disable_vae_slicing(self):
|
| 124 |
+
self.vae.disable_slicing()
|
| 125 |
+
|
| 126 |
+
def enable_sequential_cpu_offload(self, gpu_id=0):
|
| 127 |
+
if is_accelerate_available():
|
| 128 |
+
from accelerate import cpu_offload
|
| 129 |
+
else:
|
| 130 |
+
raise ImportError("Please install accelerate via `pip install accelerate`")
|
| 131 |
+
|
| 132 |
+
device = torch.device(f"cuda:{gpu_id}")
|
| 133 |
+
|
| 134 |
+
for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
|
| 135 |
+
if cpu_offloaded_model is not None:
|
| 136 |
+
cpu_offload(cpu_offloaded_model, device)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@property
|
| 140 |
+
def _execution_device(self):
|
| 141 |
+
if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
|
| 142 |
+
return self.device
|
| 143 |
+
for module in self.unet.modules():
|
| 144 |
+
if (
|
| 145 |
+
hasattr(module, "_hf_hook")
|
| 146 |
+
and hasattr(module._hf_hook, "execution_device")
|
| 147 |
+
and module._hf_hook.execution_device is not None
|
| 148 |
+
):
|
| 149 |
+
return torch.device(module._hf_hook.execution_device)
|
| 150 |
+
return self.device
|
| 151 |
+
|
| 152 |
+
def _encode_prompt(self, prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt):
|
| 153 |
+
batch_size = len(prompt) if isinstance(prompt, list) else 1
|
| 154 |
+
|
| 155 |
+
text_inputs = self.tokenizer(
|
| 156 |
+
prompt,
|
| 157 |
+
padding="max_length",
|
| 158 |
+
max_length=self.tokenizer.model_max_length,
|
| 159 |
+
truncation=True,
|
| 160 |
+
return_tensors="pt",
|
| 161 |
+
)
|
| 162 |
+
text_input_ids = text_inputs.input_ids
|
| 163 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 164 |
+
|
| 165 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
| 166 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
|
| 167 |
+
logger.warning(
|
| 168 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 169 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 173 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 174 |
+
else:
|
| 175 |
+
attention_mask = None
|
| 176 |
+
|
| 177 |
+
text_embeddings = self.text_encoder(
|
| 178 |
+
text_input_ids.to(device),
|
| 179 |
+
attention_mask=attention_mask,
|
| 180 |
+
)
|
| 181 |
+
text_embeddings = text_embeddings[0]
|
| 182 |
+
|
| 183 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 184 |
+
bs_embed, seq_len, _ = text_embeddings.shape
|
| 185 |
+
text_embeddings = text_embeddings.repeat(1, num_videos_per_prompt, 1)
|
| 186 |
+
text_embeddings = text_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1)
|
| 187 |
+
|
| 188 |
+
# get unconditional embeddings for classifier free guidance
|
| 189 |
+
if do_classifier_free_guidance:
|
| 190 |
+
uncond_tokens: List[str]
|
| 191 |
+
if negative_prompt is None:
|
| 192 |
+
uncond_tokens = [""] * batch_size
|
| 193 |
+
elif type(prompt) is not type(negative_prompt):
|
| 194 |
+
raise TypeError(
|
| 195 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 196 |
+
f" {type(prompt)}."
|
| 197 |
+
)
|
| 198 |
+
elif isinstance(negative_prompt, str):
|
| 199 |
+
uncond_tokens = [negative_prompt]
|
| 200 |
+
elif batch_size != len(negative_prompt):
|
| 201 |
+
raise ValueError(
|
| 202 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 203 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 204 |
+
" the batch size of `prompt`."
|
| 205 |
+
)
|
| 206 |
+
else:
|
| 207 |
+
uncond_tokens = negative_prompt
|
| 208 |
+
|
| 209 |
+
max_length = text_input_ids.shape[-1]
|
| 210 |
+
uncond_input = self.tokenizer(
|
| 211 |
+
uncond_tokens,
|
| 212 |
+
padding="max_length",
|
| 213 |
+
max_length=max_length,
|
| 214 |
+
truncation=True,
|
| 215 |
+
return_tensors="pt",
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 219 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 220 |
+
else:
|
| 221 |
+
attention_mask = None
|
| 222 |
+
|
| 223 |
+
uncond_embeddings = self.text_encoder(
|
| 224 |
+
uncond_input.input_ids.to(device),
|
| 225 |
+
attention_mask=attention_mask,
|
| 226 |
+
)
|
| 227 |
+
uncond_embeddings = uncond_embeddings[0]
|
| 228 |
+
|
| 229 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 230 |
+
seq_len = uncond_embeddings.shape[1]
|
| 231 |
+
uncond_embeddings = uncond_embeddings.repeat(1, num_videos_per_prompt, 1)
|
| 232 |
+
uncond_embeddings = uncond_embeddings.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 233 |
+
|
| 234 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 235 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 236 |
+
# to avoid doing two forward passes
|
| 237 |
+
text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
|
| 238 |
+
|
| 239 |
+
return text_embeddings
|
| 240 |
+
|
| 241 |
+
def decode_latents(self, latents):
|
| 242 |
+
video_length = latents.shape[2]
|
| 243 |
+
latents = 1 / 0.18215 * latents
|
| 244 |
+
latents = rearrange(latents, "b c f h w -> (b f) c h w")
|
| 245 |
+
video = self.vae.decode(latents).sample
|
| 246 |
+
video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
|
| 247 |
+
video = (video / 2 + 0.5).clamp(0, 1)
|
| 248 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
|
| 249 |
+
video = video.cpu().float().numpy()
|
| 250 |
+
return video
|
| 251 |
+
|
| 252 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 253 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 254 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 255 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 256 |
+
# and should be between [0, 1]
|
| 257 |
+
|
| 258 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 259 |
+
extra_step_kwargs = {}
|
| 260 |
+
if accepts_eta:
|
| 261 |
+
extra_step_kwargs["eta"] = eta
|
| 262 |
+
|
| 263 |
+
# check if the scheduler accepts generator
|
| 264 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 265 |
+
if accepts_generator:
|
| 266 |
+
extra_step_kwargs["generator"] = generator
|
| 267 |
+
return extra_step_kwargs
|
| 268 |
+
|
| 269 |
+
def check_inputs(self, prompt, height, width, callback_steps):
|
| 270 |
+
if not isinstance(prompt, str) and not isinstance(prompt, list):
|
| 271 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 272 |
+
|
| 273 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 274 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 275 |
+
|
| 276 |
+
if (callback_steps is None) or (
|
| 277 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 278 |
+
):
|
| 279 |
+
raise ValueError(
|
| 280 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 281 |
+
f" {type(callback_steps)}."
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
def prepare_latents(self, batch_size, num_channels_latents, video_length, height, width, dtype, device, generator, latents=None):
|
| 285 |
+
shape = (batch_size, num_channels_latents, video_length, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 286 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 287 |
+
raise ValueError(
|
| 288 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 289 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
if latents is None:
|
| 293 |
+
rand_device = "cpu" if device.type == "mps" else device
|
| 294 |
+
|
| 295 |
+
if isinstance(generator, list):
|
| 296 |
+
shape = (1,) + shape[1:]
|
| 297 |
+
latents = [
|
| 298 |
+
torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype)
|
| 299 |
+
for i in range(batch_size)
|
| 300 |
+
]
|
| 301 |
+
latents = torch.cat(latents, dim=0).to(device)
|
| 302 |
+
else:
|
| 303 |
+
latents = torch.randn(shape, generator=generator, device=rand_device, dtype=dtype).to(device)
|
| 304 |
+
else:
|
| 305 |
+
if latents.shape != shape:
|
| 306 |
+
raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
|
| 307 |
+
latents = latents.to(device)
|
| 308 |
+
|
| 309 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 310 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 311 |
+
return latents
|
| 312 |
+
|
| 313 |
+
@torch.no_grad()
|
| 314 |
+
def __call__(
|
| 315 |
+
self,
|
| 316 |
+
prompt: Union[str, List[str]],
|
| 317 |
+
video_length: Optional[int],
|
| 318 |
+
height: Optional[int] = None,
|
| 319 |
+
width: Optional[int] = None,
|
| 320 |
+
num_inference_steps: int = 50,
|
| 321 |
+
guidance_scale: float = 7.5,
|
| 322 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 323 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 324 |
+
eta: float = 0.0,
|
| 325 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 326 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 327 |
+
output_type: Optional[str] = "tensor",
|
| 328 |
+
return_dict: bool = True,
|
| 329 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 330 |
+
callback_steps: Optional[int] = 1,
|
| 331 |
+
skeleton_path: Optional[str] = None,
|
| 332 |
+
**kwargs,
|
| 333 |
+
):
|
| 334 |
+
# Default height and width to unet
|
| 335 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 336 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 337 |
+
|
| 338 |
+
# Check inputs. Raise error if not correct
|
| 339 |
+
self.check_inputs(prompt, height, width, callback_steps)
|
| 340 |
+
|
| 341 |
+
# Define call parameters
|
| 342 |
+
batch_size = 1 if isinstance(prompt, str) else len(prompt)
|
| 343 |
+
device = self._execution_device
|
| 344 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 345 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 346 |
+
# corresponds to doing no classifier free guidance.
|
| 347 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 348 |
+
|
| 349 |
+
# Encode input prompt
|
| 350 |
+
text_embeddings = self._encode_prompt(
|
| 351 |
+
prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# Prepare timesteps
|
| 355 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 356 |
+
timesteps = self.scheduler.timesteps
|
| 357 |
+
|
| 358 |
+
# Prepare latent variables
|
| 359 |
+
num_channels_latents = self.unet.in_channels
|
| 360 |
+
latents = self.prepare_latents(
|
| 361 |
+
batch_size * num_videos_per_prompt,
|
| 362 |
+
num_channels_latents,
|
| 363 |
+
video_length,
|
| 364 |
+
height,
|
| 365 |
+
width,
|
| 366 |
+
text_embeddings.dtype,
|
| 367 |
+
device,
|
| 368 |
+
generator,
|
| 369 |
+
latents,
|
| 370 |
+
)
|
| 371 |
+
latents_dtype = latents.dtype
|
| 372 |
+
|
| 373 |
+
# Prepare extra step kwargs.
|
| 374 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 375 |
+
|
| 376 |
+
# Denoising loop
|
| 377 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 378 |
+
|
| 379 |
+
skeleton, save_skeleton = self.get_skeleton(skeleton_path)
|
| 380 |
+
skeleton = skeleton.to(latents.device).repeat(2,1,1,1,1)
|
| 381 |
+
|
| 382 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 383 |
+
for i, t in enumerate(timesteps):
|
| 384 |
+
# expand the latents if we are doing classifier free guidance
|
| 385 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 386 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 387 |
+
|
| 388 |
+
# predict the noise residual
|
| 389 |
+
noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, skeleton=skeleton, train_or_sample='sample').sample.to(dtype=latents_dtype)
|
| 390 |
+
|
| 391 |
+
# perform guidance
|
| 392 |
+
if do_classifier_free_guidance:
|
| 393 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 394 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 395 |
+
|
| 396 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 397 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
| 398 |
+
|
| 399 |
+
# call the callback, if provided
|
| 400 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 401 |
+
progress_bar.update()
|
| 402 |
+
if callback is not None and i % callback_steps == 0:
|
| 403 |
+
callback(i, t, latents)
|
| 404 |
+
|
| 405 |
+
# Post-processing
|
| 406 |
+
video = self.decode_latents(latents)
|
| 407 |
+
|
| 408 |
+
# Convert to tensor
|
| 409 |
+
if output_type == "tensor":
|
| 410 |
+
video = torch.from_numpy(video)
|
| 411 |
+
video_skeleton = rearrange(save_skeleton, 'b t h w c -> b c t h w')
|
| 412 |
+
video = torch.cat([video_skeleton,video],dim=-1)
|
| 413 |
+
|
| 414 |
+
if not return_dict:
|
| 415 |
+
return video
|
| 416 |
+
|
| 417 |
+
return FollowYourPosePipelineOutput(videos=video)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
@torch.no_grad()
|
| 421 |
+
def get_skeleton(self,skeleton_path):
|
| 422 |
+
skeleton_start_end = list(range(0, 16, 2))
|
| 423 |
+
self_transform = transforms.Compose([transforms.Resize(512),
|
| 424 |
+
transforms_video.CenterCropVideo(512)])
|
| 425 |
+
|
| 426 |
+
vr_skeleton = decord.VideoReader(skeleton_path)
|
| 427 |
+
# sample frames
|
| 428 |
+
|
| 429 |
+
# for start_end in skeleton_start_end:
|
| 430 |
+
skeleton = vr_skeleton.get_batch(skeleton_start_end)
|
| 431 |
+
if not isinstance(skeleton,torch.Tensor):
|
| 432 |
+
skeleton = torch.from_numpy(skeleton.asnumpy()).float()
|
| 433 |
+
skeleton_video_trans = self_transform(skeleton.permute(3, 0, 1, 2))
|
| 434 |
+
skeleton_final = skeleton_video_trans.permute(1, 2, 3, 0)
|
| 435 |
+
# import pdb;pdb.set_trace()
|
| 436 |
+
|
| 437 |
+
skeleton_video = (skeleton_final / 255).unsqueeze(0)
|
| 438 |
+
save_skeleton = skeleton_video.clone().detach()
|
| 439 |
+
skeleton_video = rearrange(skeleton_video, 'b t h w c -> b t c h w')
|
| 440 |
+
# skeleton_video = skeleton_video.to(model.device)
|
| 441 |
+
|
| 442 |
+
return skeleton_video, save_skeleton
|
FollowYourPose/followyourpose/util.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import imageio
|
| 3 |
+
import numpy as np
|
| 4 |
+
from typing import Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torchvision
|
| 8 |
+
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=4, fps=8):
|
| 14 |
+
videos = rearrange(videos, "b c t h w -> t b c h w")
|
| 15 |
+
outputs = []
|
| 16 |
+
for x in videos:
|
| 17 |
+
x = torchvision.utils.make_grid(x, nrow=n_rows)
|
| 18 |
+
x = x.transpose(0, 1).transpose(1, 2).squeeze(-1)
|
| 19 |
+
if rescale:
|
| 20 |
+
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
|
| 21 |
+
x = (x * 255).numpy().astype(np.uint8)
|
| 22 |
+
outputs.append(x)
|
| 23 |
+
|
| 24 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 25 |
+
imageio.mimsave(path, outputs, fps=fps)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# DDIM Inversion
|
| 29 |
+
@torch.no_grad()
|
| 30 |
+
def init_prompt(prompt, pipeline):
|
| 31 |
+
uncond_input = pipeline.tokenizer(
|
| 32 |
+
[""], padding="max_length", max_length=pipeline.tokenizer.model_max_length,
|
| 33 |
+
return_tensors="pt"
|
| 34 |
+
)
|
| 35 |
+
uncond_embeddings = pipeline.text_encoder(uncond_input.input_ids.to(pipeline.device))[0]
|
| 36 |
+
text_input = pipeline.tokenizer(
|
| 37 |
+
[prompt],
|
| 38 |
+
padding="max_length",
|
| 39 |
+
max_length=pipeline.tokenizer.model_max_length,
|
| 40 |
+
truncation=True,
|
| 41 |
+
return_tensors="pt",
|
| 42 |
+
)
|
| 43 |
+
text_embeddings = pipeline.text_encoder(text_input.input_ids.to(pipeline.device))[0]
|
| 44 |
+
context = torch.cat([uncond_embeddings, text_embeddings])
|
| 45 |
+
|
| 46 |
+
return context
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def next_step(model_output: Union[torch.FloatTensor, np.ndarray], timestep: int,
|
| 50 |
+
sample: Union[torch.FloatTensor, np.ndarray], ddim_scheduler):
|
| 51 |
+
timestep, next_timestep = min(
|
| 52 |
+
timestep - ddim_scheduler.config.num_train_timesteps // ddim_scheduler.num_inference_steps, 999), timestep
|
| 53 |
+
alpha_prod_t = ddim_scheduler.alphas_cumprod[timestep] if timestep >= 0 else ddim_scheduler.final_alpha_cumprod
|
| 54 |
+
alpha_prod_t_next = ddim_scheduler.alphas_cumprod[next_timestep]
|
| 55 |
+
beta_prod_t = 1 - alpha_prod_t
|
| 56 |
+
next_original_sample = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
|
| 57 |
+
next_sample_direction = (1 - alpha_prod_t_next) ** 0.5 * model_output
|
| 58 |
+
next_sample = alpha_prod_t_next ** 0.5 * next_original_sample + next_sample_direction
|
| 59 |
+
return next_sample
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_noise_pred_single(latents, t, context, unet):
|
| 63 |
+
noise_pred = unet(latents, t, encoder_hidden_states=context)["sample"]
|
| 64 |
+
return noise_pred
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@torch.no_grad()
|
| 68 |
+
def ddim_loop(pipeline, ddim_scheduler, latent, num_inv_steps, prompt):
|
| 69 |
+
context = init_prompt(prompt, pipeline)
|
| 70 |
+
uncond_embeddings, cond_embeddings = context.chunk(2)
|
| 71 |
+
all_latent = [latent]
|
| 72 |
+
latent = latent.clone().detach()
|
| 73 |
+
for i in tqdm(range(num_inv_steps)):
|
| 74 |
+
t = ddim_scheduler.timesteps[len(ddim_scheduler.timesteps) - i - 1]
|
| 75 |
+
noise_pred = get_noise_pred_single(latent, t, cond_embeddings, pipeline.unet)
|
| 76 |
+
latent = next_step(noise_pred, t, latent, ddim_scheduler)
|
| 77 |
+
all_latent.append(latent)
|
| 78 |
+
return all_latent
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@torch.no_grad()
|
| 82 |
+
def ddim_inversion(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt=""):
|
| 83 |
+
ddim_latents = ddim_loop(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt)
|
| 84 |
+
return ddim_latents
|
FollowYourPose/test_followyourpose.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import datetime
|
| 3 |
+
import logging
|
| 4 |
+
import inspect
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
from typing import Dict, Optional, Tuple
|
| 8 |
+
from omegaconf import OmegaConf
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import torch.utils.checkpoint
|
| 13 |
+
|
| 14 |
+
import diffusers
|
| 15 |
+
import transformers
|
| 16 |
+
from accelerate import Accelerator
|
| 17 |
+
from accelerate.logging import get_logger
|
| 18 |
+
from accelerate.utils import set_seed
|
| 19 |
+
from diffusers import AutoencoderKL, DDPMScheduler, DDIMScheduler
|
| 20 |
+
from diffusers.optimization import get_scheduler
|
| 21 |
+
from diffusers.utils import check_min_version
|
| 22 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 23 |
+
from tqdm.auto import tqdm
|
| 24 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 25 |
+
|
| 26 |
+
import sys
|
| 27 |
+
sys.path.append('FollowYourPose')
|
| 28 |
+
from followyourpose.models.unet import UNet3DConditionModel
|
| 29 |
+
from followyourpose.pipelines.pipeline_followyourpose import FollowYourPosePipeline
|
| 30 |
+
from followyourpose.util import save_videos_grid, ddim_inversion
|
| 31 |
+
from einops import rearrange
|
| 32 |
+
|
| 33 |
+
check_min_version("0.10.0.dev0")
|
| 34 |
+
|
| 35 |
+
logger = get_logger(__name__, log_level="INFO")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def collate_fn(examples):
|
| 39 |
+
"""Concat a batch of sampled image in dataloader
|
| 40 |
+
"""
|
| 41 |
+
batch = {
|
| 42 |
+
"prompt_ids": torch.cat([example["prompt_ids"] for example in examples], dim=0),
|
| 43 |
+
"images": torch.stack([example["images"] for example in examples]),
|
| 44 |
+
}
|
| 45 |
+
return batch
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test(
|
| 50 |
+
pretrained_model_path: str,
|
| 51 |
+
output_dir: str,
|
| 52 |
+
validation_data: Dict,
|
| 53 |
+
validation_steps: int = 100,
|
| 54 |
+
train_batch_size: int = 1,
|
| 55 |
+
gradient_accumulation_steps: int = 1,
|
| 56 |
+
gradient_checkpointing: bool = True,
|
| 57 |
+
resume_from_checkpoint: Optional[str] = None,
|
| 58 |
+
mixed_precision: Optional[str] = "fp16",
|
| 59 |
+
enable_xformers_memory_efficient_attention: bool = True,
|
| 60 |
+
seed: Optional[int] = None,
|
| 61 |
+
skeleton_path: Optional[str] = None,
|
| 62 |
+
):
|
| 63 |
+
*_, config = inspect.getargvalues(inspect.currentframe())
|
| 64 |
+
|
| 65 |
+
accelerator = Accelerator(
|
| 66 |
+
gradient_accumulation_steps=gradient_accumulation_steps,
|
| 67 |
+
mixed_precision=mixed_precision,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Make one log on every process with the configuration for debugging.
|
| 71 |
+
logging.basicConfig(
|
| 72 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 73 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 74 |
+
level=logging.INFO,
|
| 75 |
+
)
|
| 76 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 77 |
+
if accelerator.is_local_main_process:
|
| 78 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 79 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 80 |
+
else:
|
| 81 |
+
transformers.utils.logging.set_verbosity_error()
|
| 82 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 83 |
+
|
| 84 |
+
# If passed along, set the training seed now.
|
| 85 |
+
if seed is not None:
|
| 86 |
+
set_seed(seed)
|
| 87 |
+
|
| 88 |
+
# Handle the output folder creation
|
| 89 |
+
if accelerator.is_main_process:
|
| 90 |
+
|
| 91 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 92 |
+
os.makedirs(f"{output_dir}/samples", exist_ok=True)
|
| 93 |
+
os.makedirs(f"{output_dir}/inv_latents", exist_ok=True)
|
| 94 |
+
OmegaConf.save(config, os.path.join(output_dir, 'config.yaml'))
|
| 95 |
+
|
| 96 |
+
# Load scheduler, tokenizer and models.
|
| 97 |
+
noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_path, subfolder="scheduler")
|
| 98 |
+
tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_path, subfolder="tokenizer")
|
| 99 |
+
text_encoder = CLIPTextModel.from_pretrained(pretrained_model_path, subfolder="text_encoder")
|
| 100 |
+
vae = AutoencoderKL.from_pretrained(pretrained_model_path, subfolder="vae")
|
| 101 |
+
unet = UNet3DConditionModel.from_pretrained_2d(pretrained_model_path, subfolder="unet")
|
| 102 |
+
|
| 103 |
+
# Freeze vae and text_encoder
|
| 104 |
+
vae.requires_grad_(False)
|
| 105 |
+
text_encoder.requires_grad_(False)
|
| 106 |
+
|
| 107 |
+
unet.requires_grad_(False)
|
| 108 |
+
|
| 109 |
+
if enable_xformers_memory_efficient_attention:
|
| 110 |
+
if is_xformers_available():
|
| 111 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 112 |
+
else:
|
| 113 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 114 |
+
|
| 115 |
+
if gradient_checkpointing:
|
| 116 |
+
unet.enable_gradient_checkpointing()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# Get the validation pipeline
|
| 120 |
+
validation_pipeline = FollowYourPosePipeline(
|
| 121 |
+
vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet,
|
| 122 |
+
scheduler=DDIMScheduler.from_pretrained(pretrained_model_path, subfolder="scheduler")
|
| 123 |
+
)
|
| 124 |
+
validation_pipeline.enable_vae_slicing()
|
| 125 |
+
ddim_inv_scheduler = DDIMScheduler.from_pretrained(pretrained_model_path, subfolder='scheduler')
|
| 126 |
+
ddim_inv_scheduler.set_timesteps(validation_data.num_inv_steps)
|
| 127 |
+
|
| 128 |
+
unet = accelerator.prepare(unet)
|
| 129 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 130 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 131 |
+
weight_dtype = torch.float32
|
| 132 |
+
if accelerator.mixed_precision == "fp16":
|
| 133 |
+
weight_dtype = torch.float16
|
| 134 |
+
elif accelerator.mixed_precision == "bf16":
|
| 135 |
+
weight_dtype = torch.bfloat16
|
| 136 |
+
|
| 137 |
+
# Move text_encode and vae to gpu and cast to weight_dtype
|
| 138 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 139 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 140 |
+
|
| 141 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 142 |
+
|
| 143 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 144 |
+
# The trackers initializes automatically on the main process.
|
| 145 |
+
if accelerator.is_main_process:
|
| 146 |
+
accelerator.init_trackers("text2video-fine-tune")
|
| 147 |
+
|
| 148 |
+
global_step = 0
|
| 149 |
+
first_epoch = 0
|
| 150 |
+
|
| 151 |
+
# Potentially load in the weights and states from a previous save
|
| 152 |
+
load_path = None
|
| 153 |
+
if resume_from_checkpoint:
|
| 154 |
+
if resume_from_checkpoint != "latest":
|
| 155 |
+
|
| 156 |
+
load_path = resume_from_checkpoint
|
| 157 |
+
output_dir = os.path.abspath(os.path.join(resume_from_checkpoint, ".."))
|
| 158 |
+
accelerator.print(f"load from checkpoint {load_path}")
|
| 159 |
+
accelerator.load_state(load_path)
|
| 160 |
+
|
| 161 |
+
global_step = int(load_path.split("-")[-1])
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
if accelerator.is_main_process:
|
| 165 |
+
samples = []
|
| 166 |
+
generator = torch.Generator(device=accelerator.device)
|
| 167 |
+
generator.manual_seed(seed)
|
| 168 |
+
|
| 169 |
+
ddim_inv_latent = None
|
| 170 |
+
from datetime import datetime
|
| 171 |
+
now = str(datetime.now())
|
| 172 |
+
print(now)
|
| 173 |
+
for idx, prompt in enumerate(validation_data.prompts):
|
| 174 |
+
sample = validation_pipeline(prompt, generator=generator, latents=ddim_inv_latent,
|
| 175 |
+
skeleton_path=skeleton_path,
|
| 176 |
+
**validation_data).videos
|
| 177 |
+
save_path = f"{output_dir}/inference/sample-{global_step}-{str(seed)}-{now}/{prompt}.gif"
|
| 178 |
+
save_videos_grid(sample, save_path)
|
| 179 |
+
# samples.append(sample)
|
| 180 |
+
# samples = torch.concat(samples)
|
| 181 |
+
# save_path = f"{output_dir}/inference/sample-{global_step}-{str(seed)}-{now}.mp4"
|
| 182 |
+
# save_videos_grid(samples, save_path)
|
| 183 |
+
logger.info(f"Saved samples to {save_path}")
|
| 184 |
+
|
| 185 |
+
return save_path
|
| 186 |
+
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2022 hysts
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: FollowYourPose
|
| 3 |
+
emoji: ⚡
|
| 4 |
+
colorFrom: gray
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 3.24.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
duplicated_from: YueMafighting/FollowYourPose
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
__pycache__/example.cpython-38.pyc
ADDED
|
Binary file (521 Bytes). View file
|
|
|
__pycache__/inference_followyourpose.cpython-38.pyc
ADDED
|
Binary file (2.51 kB). View file
|
|
|
app.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
from inference_followyourpose import merge_config_then_run
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
HF_TOKEN = os.getenv('HF_TOKEN')
|
| 13 |
+
pipe = merge_config_then_run()
|
| 14 |
+
|
| 15 |
+
with gr.Blocks(css='style.css') as demo:
|
| 16 |
+
gr.HTML(
|
| 17 |
+
"""
|
| 18 |
+
<div style="text-align: center; max-width: 1200px; margin: 20px auto;">
|
| 19 |
+
<h1 style="font-weight: 900; font-size: 2rem; margin: 0rem">
|
| 20 |
+
🕺🕺🕺 Follow Your Pose 💃💃💃 </font></center> <br> <center>Pose-Guided Text-to-Video Generation using Pose-Free Videos
|
| 21 |
+
</h1>
|
| 22 |
+
<h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
|
| 23 |
+
<a href="https://mayuelala.github.io/">Yue Ma*</a>
|
| 24 |
+
<a href="https://github.com/YingqingHe">Yingqing He*</a> , <a href="http://vinthony.github.io/">Xiaodong Cun</a>,
|
| 25 |
+
<a href="https://xinntao.github.io/"> Xintao Wang </a>,
|
| 26 |
+
<a href="https://scholar.google.com/citations?user=4oXBp9UAAAAJ&hl=zh-CN">Ying Shan</a>,
|
| 27 |
+
<a href="https://scholar.google.com/citations?user=Xrh1OIUAAAAJ&hl=zh-CN">Xiu Li</a>,
|
| 28 |
+
<a href="http://cqf.io">Qifeng Chen</a>
|
| 29 |
+
</h2>
|
| 30 |
+
|
| 31 |
+
<h2 style="font-weight: 450; font-size: 1rem; margin: 0rem">
|
| 32 |
+
<span class="link-block">
|
| 33 |
+
[<a href="https://arxiv.org/abs/2304.01186" target="_blank"
|
| 34 |
+
class="external-link ">
|
| 35 |
+
<span class="icon">
|
| 36 |
+
<i class="ai ai-arxiv"></i>
|
| 37 |
+
</span>
|
| 38 |
+
<span>arXiv</span>
|
| 39 |
+
</a>]
|
| 40 |
+
</span>
|
| 41 |
+
|
| 42 |
+
<!-- Github link -->
|
| 43 |
+
<span class="link-block">
|
| 44 |
+
[<a href="https://github.com/mayuelala/FollowYourPose" target="_blank"
|
| 45 |
+
class="external-link ">
|
| 46 |
+
<span class="icon">
|
| 47 |
+
<i class="fab fa-github"></i>
|
| 48 |
+
</span>
|
| 49 |
+
<span>Code</span>
|
| 50 |
+
</a>]
|
| 51 |
+
</span>
|
| 52 |
+
|
| 53 |
+
<!-- Github link -->
|
| 54 |
+
<span class="link-block">
|
| 55 |
+
[<a href="https://follow-your-pose.github.io/" target="_blank"
|
| 56 |
+
class="external-link ">
|
| 57 |
+
<span class="icon">
|
| 58 |
+
<i class="fab fa-github"></i>
|
| 59 |
+
</span>
|
| 60 |
+
<span>Homepage</span>
|
| 61 |
+
</a>]
|
| 62 |
+
</span>
|
| 63 |
+
</h2>
|
| 64 |
+
<h2 style="font-weight: 450; font-size: 1rem; margin-top: 0.5rem; margin-bottom: 0.5rem">
|
| 65 |
+
TL;DR: We tune 2D stable-diffusion to generate the character videos from pose and text description.
|
| 66 |
+
</h2>
|
| 67 |
+
</div>
|
| 68 |
+
""")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
gr.HTML("""
|
| 72 |
+
<p>Alternatively, try our GitHub <a href=https://github.com/mayuelala/FollowYourPose> code </a> on your GPU.
|
| 73 |
+
</p>""")
|
| 74 |
+
|
| 75 |
+
with gr.Row():
|
| 76 |
+
with gr.Column():
|
| 77 |
+
with gr.Accordion('Input Video', open=True):
|
| 78 |
+
# user_input_video = gr.File(label='Input Source Video')
|
| 79 |
+
user_input_video = gr.Video(label='Input Source Video', source='upload', type='numpy', format="mp4", visible=True).style(height="auto")
|
| 80 |
+
with gr.Accordion('Temporal Crop offset and Sampling Stride', open=False):
|
| 81 |
+
n_sample_frame = gr.Slider(label='Number of Frames',
|
| 82 |
+
minimum=0,
|
| 83 |
+
maximum=32,
|
| 84 |
+
step=1,
|
| 85 |
+
value=8)
|
| 86 |
+
stride = gr.Slider(label='Temporal stride',
|
| 87 |
+
minimum=0,
|
| 88 |
+
maximum=20,
|
| 89 |
+
step=1,
|
| 90 |
+
value=1)
|
| 91 |
+
start_sample_frame = gr.Number(label='Start frame in the video',
|
| 92 |
+
value=0,
|
| 93 |
+
precision=0)
|
| 94 |
+
|
| 95 |
+
with gr.Accordion('Spatial Crop offset', open=False):
|
| 96 |
+
left_crop = gr.Number(label='Left crop',
|
| 97 |
+
value=0,
|
| 98 |
+
precision=0)
|
| 99 |
+
right_crop = gr.Number(label='Right crop',
|
| 100 |
+
value=0,
|
| 101 |
+
precision=0)
|
| 102 |
+
top_crop = gr.Number(label='Top crop',
|
| 103 |
+
value=0,
|
| 104 |
+
precision=0)
|
| 105 |
+
bottom_crop = gr.Number(label='Bottom crop',
|
| 106 |
+
value=0,
|
| 107 |
+
precision=0)
|
| 108 |
+
offset_list = [
|
| 109 |
+
left_crop,
|
| 110 |
+
right_crop,
|
| 111 |
+
top_crop,
|
| 112 |
+
bottom_crop,
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
ImageSequenceDataset_list = [
|
| 116 |
+
start_sample_frame,
|
| 117 |
+
n_sample_frame,
|
| 118 |
+
stride
|
| 119 |
+
] + offset_list
|
| 120 |
+
|
| 121 |
+
# model_id = gr.Dropdown(
|
| 122 |
+
# label='Model ID',
|
| 123 |
+
# choices=[
|
| 124 |
+
# 'CompVis/stable-diffusion-v1-4',
|
| 125 |
+
# # add shape editing ckpt here
|
| 126 |
+
# ],
|
| 127 |
+
# value='CompVis/stable-diffusion-v1-4')
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
with gr.Accordion('Text Prompt', open=True):
|
| 131 |
+
|
| 132 |
+
target_prompt = gr.Textbox(label='Target Prompt',
|
| 133 |
+
info='The simple background may achieve better results(e.g., "beach", "moon" prompt is better than "street" and "market")',
|
| 134 |
+
max_lines=1,
|
| 135 |
+
placeholder='Example: "Iron man on the beach"',
|
| 136 |
+
value='Iron man on the beach')
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
run_button = gr.Button('Generate')
|
| 143 |
+
|
| 144 |
+
with gr.Column():
|
| 145 |
+
result = gr.Video(label='Result')
|
| 146 |
+
# result.style(height=512, width=512)
|
| 147 |
+
with gr.Accordion('DDIM Parameters', open=True):
|
| 148 |
+
num_steps = gr.Slider(label='Number of Steps',
|
| 149 |
+
info='larger value has better editing capacity, but takes more time and memory.',
|
| 150 |
+
minimum=0,
|
| 151 |
+
maximum=50,
|
| 152 |
+
step=1,
|
| 153 |
+
value=50)
|
| 154 |
+
guidance_scale = gr.Slider(label='CFG Scale',
|
| 155 |
+
minimum=0,
|
| 156 |
+
maximum=50,
|
| 157 |
+
step=0.1,
|
| 158 |
+
value=12.5)
|
| 159 |
+
with gr.Row():
|
| 160 |
+
from example import style_example
|
| 161 |
+
examples = style_example
|
| 162 |
+
|
| 163 |
+
inputs = [
|
| 164 |
+
user_input_video,
|
| 165 |
+
target_prompt,
|
| 166 |
+
num_steps,
|
| 167 |
+
guidance_scale,
|
| 168 |
+
*ImageSequenceDataset_list
|
| 169 |
+
]
|
| 170 |
+
target_prompt.submit(fn=pipe.run, inputs=inputs, outputs=result)
|
| 171 |
+
run_button.click(fn=pipe.run, inputs=inputs, outputs=result)
|
| 172 |
+
|
| 173 |
+
demo.queue().launch()
|
| 174 |
+
# demo.queue().launch(share=False, server_name='0.0.0.0', server_port=7890)
|
docs/OpenSans-Regular.ttf
ADDED
|
Binary file (148 kB). View file
|
|
|
example.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
num_steps = 30
|
| 2 |
+
style_example = [
|
| 3 |
+
[
|
| 4 |
+
'CompVis/stable-diffusion-v1-4',
|
| 5 |
+
'FateZero/data/teaser_car-turn.mp4',
|
| 6 |
+
'a silver jeep driving down a curvy road in the countryside',
|
| 7 |
+
'watercolor painting of a silver jeep driving down a curvy road in the countryside',
|
| 8 |
+
0.8,
|
| 9 |
+
0.8,
|
| 10 |
+
"watercolor",
|
| 11 |
+
10,
|
| 12 |
+
num_steps,
|
| 13 |
+
7.5,
|
| 14 |
+
# input video argument
|
| 15 |
+
None, 0, 8, 1, 0,0,0,0
|
| 16 |
+
|
| 17 |
+
]
|
| 18 |
+
# [
|
| 19 |
+
# 'CompVis/stable-diffusion-v1-4',
|
| 20 |
+
# 'FateZero/data/style/sunflower.mp4',
|
| 21 |
+
# 'a yellow sunflower',
|
| 22 |
+
# 'van gogh style painting of a yellow sunflower',
|
| 23 |
+
# 0.5,
|
| 24 |
+
# 0.5,
|
| 25 |
+
# 'van gogh',
|
| 26 |
+
# 10,
|
| 27 |
+
# num_steps,
|
| 28 |
+
# 7.5,
|
| 29 |
+
# None, 0, 8, 1, 0,0,0,0
|
| 30 |
+
# ],
|
| 31 |
+
# [
|
| 32 |
+
# 'CompVis/stable-diffusion-v1-4',
|
| 33 |
+
# 'FateZero/data/style/surf.mp4',
|
| 34 |
+
# 'a man with round helmet surfing on a white wave in blue ocean with a rope',
|
| 35 |
+
# 'The Ukiyo-e style painting of a man with round helmet surfing on a white wave in blue ocean with a rope',
|
| 36 |
+
# 0.9,
|
| 37 |
+
# 0.9,
|
| 38 |
+
# 'Ukiyo-e',
|
| 39 |
+
# 10,
|
| 40 |
+
# num_steps,
|
| 41 |
+
# 7.5,
|
| 42 |
+
# None, 0, 8, 1, 0,0,0,0
|
| 43 |
+
# ],
|
| 44 |
+
# [
|
| 45 |
+
# 'CompVis/stable-diffusion-v1-4',
|
| 46 |
+
# 'FateZero/data/style/train.mp4',
|
| 47 |
+
# 'a train traveling down tracks next to a forest filled with trees and flowers and a man on the side of the track',
|
| 48 |
+
# 'a train traveling down tracks next to a forest filled with trees and flowers and a man on the side of the track Makoto Shinkai style',
|
| 49 |
+
# 0.9,
|
| 50 |
+
# 0.9,
|
| 51 |
+
# 'Makoto Shinkai',
|
| 52 |
+
# 10,
|
| 53 |
+
# num_steps,
|
| 54 |
+
# 7.5,
|
| 55 |
+
# None, 0, 8, 28, 0,0,0,0
|
| 56 |
+
# ],
|
| 57 |
+
|
| 58 |
+
# [
|
| 59 |
+
# 'CompVis/stable-diffusion-v1-4',
|
| 60 |
+
# 'FateZero/data/attribute/swan_swarov.mp4',
|
| 61 |
+
# 'a black swan with a red beak swimming in a river near a wall and bushes',
|
| 62 |
+
# 'a Swarovski crystal swan with a red beak swimming in a river near a wall and bushes',
|
| 63 |
+
# 0.8,
|
| 64 |
+
# 0.6,
|
| 65 |
+
# 'Swarovski crystal',
|
| 66 |
+
# 10,
|
| 67 |
+
# num_steps,
|
| 68 |
+
# 7.5,
|
| 69 |
+
# None, 0, 8, 1, 0,0,0,0
|
| 70 |
+
# ],
|
| 71 |
+
# [
|
| 72 |
+
# 'CompVis/stable-diffusion-v1-4',
|
| 73 |
+
# 'FateZero/data/attribute/squirrel_carrot.mp4',
|
| 74 |
+
# 'A squirrel is eating a carrot',
|
| 75 |
+
# 'A rabbit is eating a eggplant',
|
| 76 |
+
# 0.5,
|
| 77 |
+
# 0.5,
|
| 78 |
+
# 'rabbit eggplant',
|
| 79 |
+
# 10,
|
| 80 |
+
# num_steps,
|
| 81 |
+
# 7.5,
|
| 82 |
+
# None, 0, 8, 1, 0,0,0,0
|
| 83 |
+
# ],
|
| 84 |
+
|
| 85 |
+
]
|
inference_followyourpose.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from FollowYourPose.test_followyourpose import *
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from transformers import AutoTokenizer, CLIPTextModel
|
| 7 |
+
from huggingface_hub import snapshot_download
|
| 8 |
+
import sys
|
| 9 |
+
sys.path.append('FollowYourPose')
|
| 10 |
+
|
| 11 |
+
def get_time_string() -> str:
|
| 12 |
+
x = datetime.datetime.now()
|
| 13 |
+
return f"{(x.year - 2000):02d}{x.month:02d}{x.day:02d}-{x.hour:02d}{x.minute:02d}{x.second:02d}"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class merge_config_then_run():
|
| 17 |
+
def __init__(self) -> None:
|
| 18 |
+
# Load the tokenizer
|
| 19 |
+
self.tokenizer = None
|
| 20 |
+
self.text_encoder = None
|
| 21 |
+
self.vae = None
|
| 22 |
+
self.unet = None
|
| 23 |
+
self.download_model()
|
| 24 |
+
|
| 25 |
+
def download_model(self):
|
| 26 |
+
REPO_ID = 'YueMafighting/FollowYourPose_v1'
|
| 27 |
+
snapshot_download(repo_id=REPO_ID, local_dir='./FollowYourPose/checkpoints/', local_dir_use_symlinks=False)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def run(
|
| 31 |
+
self,
|
| 32 |
+
data_path,
|
| 33 |
+
target_prompt,
|
| 34 |
+
num_steps,
|
| 35 |
+
guidance_scale,
|
| 36 |
+
user_input_video=None,
|
| 37 |
+
start_sample_frame=0,
|
| 38 |
+
n_sample_frame=8,
|
| 39 |
+
stride=1,
|
| 40 |
+
left_crop=0,
|
| 41 |
+
right_crop=0,
|
| 42 |
+
top_crop=0,
|
| 43 |
+
bottom_crop=0,
|
| 44 |
+
):
|
| 45 |
+
|
| 46 |
+
default_edit_config='./FollowYourPose/configs/pose_sample.yaml'
|
| 47 |
+
Omegadict_default_edit_config = OmegaConf.load(default_edit_config)
|
| 48 |
+
|
| 49 |
+
dataset_time_string = get_time_string()
|
| 50 |
+
config_now = copy.deepcopy(Omegadict_default_edit_config)
|
| 51 |
+
|
| 52 |
+
offset_dict = {
|
| 53 |
+
"left": left_crop,
|
| 54 |
+
"right": right_crop,
|
| 55 |
+
"top": top_crop,
|
| 56 |
+
"bottom": bottom_crop,
|
| 57 |
+
}
|
| 58 |
+
ImageSequenceDataset_dict = {
|
| 59 |
+
"start_sample_frame" : start_sample_frame,
|
| 60 |
+
"n_sample_frame" : n_sample_frame,
|
| 61 |
+
"sampling_rate" : stride,
|
| 62 |
+
"offset": offset_dict,
|
| 63 |
+
}
|
| 64 |
+
config_now['validation_data'].update(ImageSequenceDataset_dict)
|
| 65 |
+
if user_input_video and data_path is None:
|
| 66 |
+
raise gr.Error('You need to upload a video or choose a provided video')
|
| 67 |
+
if user_input_video is not None:
|
| 68 |
+
if isinstance(user_input_video, str):
|
| 69 |
+
config_now['validation_data']['path'] = user_input_video
|
| 70 |
+
elif hasattr(user_input_video, 'name') and user_input_video.name is not None:
|
| 71 |
+
config_now['validation_data']['path'] = user_input_video.name
|
| 72 |
+
config_now['validation_data']['prompts'] = [target_prompt]
|
| 73 |
+
# ddim config
|
| 74 |
+
config_now['validation_data']['guidance_scale'] = guidance_scale
|
| 75 |
+
config_now['validation_data']['num_inference_steps'] = num_steps
|
| 76 |
+
config_now['skeleton_path'] = data_path
|
| 77 |
+
|
| 78 |
+
save_path = test(**config_now)
|
| 79 |
+
mp4_path = save_path.replace('_0.gif', '_0_0_0.mp4')
|
| 80 |
+
return mp4_path
|
| 81 |
+
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
requirements.txt
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
absl-py==1.4.0
|
| 2 |
+
accelerate==0.16.0
|
| 3 |
+
aiofiles==23.1.0
|
| 4 |
+
aiohttp==3.8.4
|
| 5 |
+
aiosignal==1.3.1
|
| 6 |
+
altair==4.2.2
|
| 7 |
+
antlr4-python3-runtime==4.9.3
|
| 8 |
+
anyio==3.6.2
|
| 9 |
+
async-timeout==4.0.2
|
| 10 |
+
attrs==22.2.0
|
| 11 |
+
av==10.0.0
|
| 12 |
+
bitsandbytes==0.35.4
|
| 13 |
+
cachetools==5.3.0
|
| 14 |
+
charset-normalizer==3.0.1
|
| 15 |
+
click==8.1.3
|
| 16 |
+
contourpy==1.0.7
|
| 17 |
+
cycler==0.11.0
|
| 18 |
+
decord==0.6.0
|
| 19 |
+
diffusers==0.11.1
|
| 20 |
+
einops==0.6.0
|
| 21 |
+
entrypoints==0.4
|
| 22 |
+
fastapi==0.95.0
|
| 23 |
+
ffmpeg-python==0.2.0
|
| 24 |
+
ffmpy==0.3.0
|
| 25 |
+
filelock==3.9.0
|
| 26 |
+
fonttools==4.39.3
|
| 27 |
+
frozenlist==1.3.3
|
| 28 |
+
fsspec==2023.3.0
|
| 29 |
+
ftfy==6.1.1
|
| 30 |
+
future==0.18.3
|
| 31 |
+
google-auth==2.16.1
|
| 32 |
+
google-auth-oauthlib==0.4.6
|
| 33 |
+
gradio==3.24.1
|
| 34 |
+
gradio_client==0.0.7
|
| 35 |
+
grpcio==1.51.3
|
| 36 |
+
h11==0.14.0
|
| 37 |
+
httpcore==0.16.3
|
| 38 |
+
httpx==0.23.3
|
| 39 |
+
huggingface-hub==0.13.3
|
| 40 |
+
idna==3.4
|
| 41 |
+
imageio==2.25.1
|
| 42 |
+
importlib-metadata==6.0.0
|
| 43 |
+
importlib-resources==5.12.0
|
| 44 |
+
Jinja2==3.1.2
|
| 45 |
+
jsonschema==4.17.3
|
| 46 |
+
kiwisolver==1.4.4
|
| 47 |
+
linkify-it-py==2.0.0
|
| 48 |
+
Markdown==3.4.1
|
| 49 |
+
markdown-it-py==2.2.0
|
| 50 |
+
MarkupSafe==2.1.2
|
| 51 |
+
matplotlib==3.7.1
|
| 52 |
+
mdit-py-plugins==0.3.3
|
| 53 |
+
mdurl==0.1.2
|
| 54 |
+
modelcards==0.1.6
|
| 55 |
+
multidict==6.0.4
|
| 56 |
+
mypy-extensions==1.0.0
|
| 57 |
+
numpy==1.24.2
|
| 58 |
+
nvidia-cublas-cu11==11.10.3.66
|
| 59 |
+
nvidia-cuda-nvrtc-cu11==11.7.99
|
| 60 |
+
nvidia-cuda-runtime-cu11==11.7.99
|
| 61 |
+
nvidia-cudnn-cu11==8.5.0.96
|
| 62 |
+
oauthlib==3.2.2
|
| 63 |
+
omegaconf==2.3.0
|
| 64 |
+
opencv-python==4.7.0.72
|
| 65 |
+
orjson==3.8.9
|
| 66 |
+
packaging==23.0
|
| 67 |
+
pandas==1.5.3
|
| 68 |
+
Pillow==9.4.0
|
| 69 |
+
pkgutil_resolve_name==1.3.10
|
| 70 |
+
protobuf==4.22.0
|
| 71 |
+
psutil==5.9.4
|
| 72 |
+
pyasn1==0.4.8
|
| 73 |
+
pyasn1-modules==0.2.8
|
| 74 |
+
pydantic==1.10.7
|
| 75 |
+
pydub==0.25.1
|
| 76 |
+
pyparsing==3.0.9
|
| 77 |
+
pyre-extensions==0.0.23
|
| 78 |
+
pyrsistent==0.19.3
|
| 79 |
+
python-dateutil==2.8.2
|
| 80 |
+
python-multipart==0.0.6
|
| 81 |
+
pytz==2022.7.1
|
| 82 |
+
PyYAML==6.0
|
| 83 |
+
regex==2022.10.31
|
| 84 |
+
requests==2.28.2
|
| 85 |
+
requests-oauthlib==1.3.1
|
| 86 |
+
rfc3986==1.5.0
|
| 87 |
+
rsa==4.9
|
| 88 |
+
semantic-version==2.10.0
|
| 89 |
+
six==1.16.0
|
| 90 |
+
sniffio==1.3.0
|
| 91 |
+
starlette==0.26.1
|
| 92 |
+
tensorboard==2.12.0
|
| 93 |
+
tensorboard-data-server==0.7.0
|
| 94 |
+
tensorboard-plugin-wit==1.8.1
|
| 95 |
+
tokenizers==0.13.2
|
| 96 |
+
toolz==0.12.0
|
| 97 |
+
torch==1.13.1
|
| 98 |
+
torchvision==0.14.1
|
| 99 |
+
tqdm==4.64.1
|
| 100 |
+
transformers==4.26.1
|
| 101 |
+
triton==1.1.1
|
| 102 |
+
typing-inspect==0.8.0
|
| 103 |
+
typing_extensions==4.5.0
|
| 104 |
+
uc-micro-py==1.0.1
|
| 105 |
+
urllib3==1.26.14
|
| 106 |
+
uvicorn==0.21.1
|
| 107 |
+
wcwidth==0.2.6
|
| 108 |
+
websockets==11.0
|
| 109 |
+
Werkzeug==2.2.3
|
| 110 |
+
xformers==0.0.16
|
| 111 |
+
yarl==1.8.2
|
| 112 |
+
zipp==3.14.0
|
style.css
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
h1 {
|
| 2 |
+
text-align: center;
|
| 3 |
+
}
|