Spaces:
Sleeping
Sleeping
feat: add emoji
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +10 -1
- .gitattributes.backup +35 -0
- .gitignore +38 -0
- Dockerfile +44 -0
- README.md +64 -7
- README.md.backup +16 -0
- app.py +371 -64
- assets/wechat_group.png +3 -0
- colab/follow_emoji_collab_nowebui.ipynb +0 -0
- colab/follow_emoji_collab_webui.ipynb +112 -0
- colab/infer.py +228 -0
- colab/infer.yaml +50 -0
- configs/infer.yaml +46 -0
- dataset/__init__.py +0 -0
- dataset/val_dataset.py +130 -0
- diffusers/__init__.py +748 -0
- diffusers/commands/__init__.py +27 -0
- diffusers/commands/diffusers_cli.py +43 -0
- diffusers/commands/env.py +84 -0
- diffusers/commands/fp16_safetensors.py +133 -0
- diffusers/configuration_utils.py +695 -0
- diffusers/dependency_versions_check.py +34 -0
- diffusers/dependency_versions_table.py +45 -0
- diffusers/experimental/README.md +5 -0
- diffusers/experimental/__init__.py +1 -0
- diffusers/experimental/rl/__init__.py +1 -0
- diffusers/experimental/rl/value_guided_sampling.py +154 -0
- diffusers/image_processor.py +648 -0
- diffusers/loaders/__init__.py +82 -0
- diffusers/loaders/ip_adapter.py +157 -0
- diffusers/loaders/lora.py +1415 -0
- diffusers/loaders/lora_conversion_utils.py +284 -0
- diffusers/loaders/single_file.py +631 -0
- diffusers/loaders/textual_inversion.py +459 -0
- diffusers/loaders/unet.py +735 -0
- diffusers/loaders/utils.py +59 -0
- diffusers/models/README.md +3 -0
- diffusers/models/__init__.py +88 -0
- diffusers/models/activations.py +120 -0
- diffusers/models/adapter.py +584 -0
- diffusers/models/attention.py +547 -0
- diffusers/models/attention_flax.py +494 -0
- diffusers/models/attention_processor.py +2305 -0
- diffusers/models/attention_processor_ip_face.py +0 -0
- diffusers/models/attention_processor_reference_only.py +0 -0
- diffusers/models/autoencoder_asym_kl.py +186 -0
- diffusers/models/autoencoder_kl.py +450 -0
- diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
- diffusers/models/autoencoder_tiny.py +345 -0
- diffusers/models/consistency_decoder_vae.py +437 -0
.gitattributes
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 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
|
|
@@ -33,6 +34,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
-
|
|
|
|
|
|
|
| 37 |
*.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# General LFS file types
|
| 2 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 3 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 4 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 34 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 36 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
|
| 38 |
+
# Media files
|
| 39 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 40 |
*.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
# Specific model files
|
| 43 |
+
data_process/lib/FaceVerse/v3/faceverse_v3_1.npy filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
data_process/lib/faceverse_process/BgMatting_models/rvm_resnet50_fp32.torchscript filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
data_process/lib/faceverse_process/metamodel/v3/faceverse_v3_1.npy filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.torchscript filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.task filter=lfs diff=lfs merge=lfs -text
|
.gitattributes.backup
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
nohup_out*
|
| 2 |
+
data/
|
| 3 |
+
output/
|
| 4 |
+
mlruns/
|
| 5 |
+
*.onnx
|
| 6 |
+
/utils/tencentcloud-sdk-python/TENCENT_CLOUD_SECRET.txt
|
| 7 |
+
TENCENT_CLOUD_SECRET.txt
|
| 8 |
+
|
| 9 |
+
**/__pycache__/
|
| 10 |
+
*.py[cod]
|
| 11 |
+
|
| 12 |
+
# vim swapfile
|
| 13 |
+
*.swp
|
| 14 |
+
|
| 15 |
+
# iFT
|
| 16 |
+
ft_local/
|
| 17 |
+
*.zip
|
| 18 |
+
|
| 19 |
+
.DS_Store
|
| 20 |
+
|
| 21 |
+
logs/
|
| 22 |
+
|
| 23 |
+
.ipynb_checkpoints/
|
| 24 |
+
inp_videos/
|
| 25 |
+
out_videos/
|
| 26 |
+
.idea/
|
| 27 |
+
|
| 28 |
+
# *.ipynb
|
| 29 |
+
*.safetensors
|
| 30 |
+
*.ckpt
|
| 31 |
+
|
| 32 |
+
/mmpose/ckpt/
|
| 33 |
+
mmpose
|
| 34 |
+
/venv
|
| 35 |
+
/model
|
| 36 |
+
/processed_videos
|
| 37 |
+
/temp
|
| 38 |
+
/ckpt_models
|
Dockerfile
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use an official CUDA runtime as a parent image
|
| 2 |
+
FROM nvidia/cuda:12.1.0-runtime-ubuntu22.04
|
| 3 |
+
|
| 4 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
| 5 |
+
|
| 6 |
+
# Set the working directory in the container to /app
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
# Install dependencies & python
|
| 10 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 11 |
+
git \
|
| 12 |
+
wget \
|
| 13 |
+
bzip2 \
|
| 14 |
+
ffmpeg \
|
| 15 |
+
gcc \
|
| 16 |
+
g++ \
|
| 17 |
+
software-properties-common \
|
| 18 |
+
libgl1-mesa-glx \
|
| 19 |
+
libglib2.0-0 \
|
| 20 |
+
libsm6 \
|
| 21 |
+
libxext6 \
|
| 22 |
+
libxrender-dev \
|
| 23 |
+
libgomp1 \
|
| 24 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 25 |
+
|
| 26 |
+
RUN add-apt-repository ppa:deadsnakes/ppa && apt update && apt install -y python3.10 python3-pip
|
| 27 |
+
|
| 28 |
+
# Clone the GitHub repository
|
| 29 |
+
RUN git clone https://github.com/daswer123/FollowYourEmoji-Webui .
|
| 30 |
+
|
| 31 |
+
# Run install script
|
| 32 |
+
RUN chmod +x install_no_venv.sh && ./install_no_venv.sh
|
| 33 |
+
|
| 34 |
+
RUN pip install --upgrade pip
|
| 35 |
+
|
| 36 |
+
# Expose port 7860 for the gradio app
|
| 37 |
+
EXPOSE 7860
|
| 38 |
+
|
| 39 |
+
RUN ln -s /usr/bin/python3 /usr/bin/python
|
| 40 |
+
|
| 41 |
+
RUN chmod +x start.sh
|
| 42 |
+
|
| 43 |
+
# Run start.sh when the container starts
|
| 44 |
+
CMD ["bash","start.sh"]
|
README.md
CHANGED
|
@@ -1,16 +1,73 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.42.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
hf_oauth: true
|
| 11 |
-
hf_oauth_scopes:
|
| 12 |
-
- inference-api
|
| 13 |
license: apache-2.0
|
| 14 |
---
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: FollowYourEmoji WebUI
|
| 3 |
+
emoji: 🤪
|
| 4 |
+
colorFrom: pink
|
| 5 |
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.42.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
|
|
|
|
|
|
| 10 |
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# FollowYourEmoji WebUI
|
| 14 |
+
|
| 15 |
+
This is a fork of [FollowYourEmoji-Webui](https://github.com/daswer123/FollowYourEmoji-Webui) adapted for Hugging Face Spaces.
|
| 16 |
+
|
| 17 |
+
## About this fork
|
| 18 |
+
|
| 19 |
+
This fork implements the FollowYourEmoji functionality in a web UI, modified to expose as many settings as possible for convenient use in Hugging Face Spaces.
|
| 20 |
+
|
| 21 |
+
You can see sample videos in the example folder: https://github.com/daswer123/FollowYourEmoji-Webui/tree/main/example
|
| 22 |
+
|
| 23 |
+
## Features
|
| 24 |
+
|
| 25 |
+
Here is a short list of what has been added to the web UI:
|
| 26 |
+
|
| 27 |
+
1. **Convenient Upload**: Ability to conveniently upload a reference picture and video
|
| 28 |
+
2. **Face Cropping Tool**: A tool to crop the reference picture so that it fits the video perfectly
|
| 29 |
+
3. **Crop Preview**: Ability to see a preview of the cropped picture, zoom in or shift the cropping
|
| 30 |
+
4. **Video Processing**: The ability to upload any video without the need for additional processing (the interface itself processes everything)
|
| 31 |
+
5. **NPY File Support**: Ability to upload .npy file, as well as choose from a folder. Each processed video is added to the folder, which allows you to select the same video without re-processing
|
| 32 |
+
6. **Animation Preview**: Ability to see how the animation will look like before generation
|
| 33 |
+
7. **Extensive Settings**: Many different settings, both custom and official
|
| 34 |
+
8. **Custom FPS**: Ability to specify the FPS of the output video
|
| 35 |
+
9. **Anomaly Detection**: Mechanism to remove "Anomalous frames" in automatic mode
|
| 36 |
+
10. **Frame Archive**: Possibility to get all frames in the archive in addition to video
|
| 37 |
+
|
| 38 |
+
And many more small improvements that will allow you to work conveniently in one interface.
|
| 39 |
+
|
| 40 |
+
## Screenshot
|
| 41 |
+
|
| 42 |
+

|
| 43 |
+
|
| 44 |
+
## Original Project
|
| 45 |
+
|
| 46 |
+
This is a fork of the original [Follow-Your-Emoji](https://github.com/mayuelala/FollowYourEmoji) project:
|
| 47 |
+
|
| 48 |
+
**Follow-Your-Emoji: Fine-Controllable and Expressive Freestyle Portrait Animation**
|
| 49 |
+
|
| 50 |
+
[Yue Ma*](https://mayuelala.github.io/), [Hongyu Liu*](https://kumapowerliu.github.io/), [Hongfa Wang*](https://github.com/mayuelala/FollowYourEmoji), [Heng Pan*](https://github.com/mayuelala/FollowYourEmoji), [Yingqing He](https://github.com/YingqingHe), [Junkun Yuan](https://0-scholar-google-com.brum.beds.ac.uk/citations?user=j3iFVPsAAAAJ&hl=zh-CN), [Ailing Zeng](https://ailingzeng.site/), [Chengfei Cai](https://github.com/mayuelala/FollowYourEmoji), [Heung-Yeung Shum](https://scholar.google.com.hk/citations?user=9akH-n8AAAAJ&hl=en), [Wei Liu](https://scholar.google.com/citations?user=AjxoEpIAAAAJ&hl=zh-CN) and [Qifeng Chen](https://cqf.io)
|
| 51 |
+
|
| 52 |
+
<a href='https://arxiv.org/abs/2406.01900'><img src='https://img.shields.io/badge/ArXiv-2406.01900-red'></a>
|
| 53 |
+
<a href='https://follow-your-emoji.github.io/'><img src='https://img.shields.io/badge/Project-Page-Green'></a> <a href='assets/wechat_group.png'><img src='https://badges.aleen42.com/src/wechat.svg'></a>  [](https://github.com/mayuelala/FollowYourEmoji)
|
| 54 |
+
|
| 55 |
+
## Citation
|
| 56 |
+
|
| 57 |
+
If you find Follow-Your-Emoji useful for your research, welcome to 🌟 this repo and cite our work using the following BibTeX:
|
| 58 |
+
|
| 59 |
+
```bibtex
|
| 60 |
+
@article{ma2024follow,
|
| 61 |
+
title={Follow-Your-Emoji: Fine-Controllable and Expressive Freestyle Portrait Animation},
|
| 62 |
+
author={Ma, Yue and Liu, Hongyu and Wang, Hongfa and Pan, Heng and He, Yingqing and Yuan, Junkun and Zeng, Ailing and Cai, Chengfei and Shum, Heung-Yeung and Liu, Wei and others},
|
| 63 |
+
journal={arXiv preprint arXiv:2406.01900},
|
| 64 |
+
year={2024}
|
| 65 |
+
}
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
## Follow Family
|
| 69 |
+
|
| 70 |
+
- [Follow-Your-Pose](https://github.com/mayuelala/FollowYourPose): Pose-Guided text-to-Video Generation
|
| 71 |
+
- [Follow-Your-Click](https://github.com/mayuelala/FollowYourClick): Open-domain Regional image animation via Short Prompts
|
| 72 |
+
- [Follow-Your-Handle](https://github.com/mayuelala/FollowYourHandle): Controllable Video Editing via Control Handle Transformations
|
| 73 |
+
- [Follow-Your-Emoji](https://github.com/mayuelala/FollowYourEmoji): Fine-Controllable and Expressive Freestyle Portrait Animation
|
README.md.backup
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Test Follow Emoji
|
| 3 |
+
emoji: 💬
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.42.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
hf_oauth: true
|
| 11 |
+
hf_oauth_scopes:
|
| 12 |
+
- inference-api
|
| 13 |
+
license: apache-2.0
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
|
app.py
CHANGED
|
@@ -1,70 +1,377 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
):
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
if __name__ == "__main__":
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import yaml
|
| 5 |
+
import cv2
|
| 6 |
+
import zipfile
|
| 7 |
+
from utils import process_video, get_npy_files, get_frame_count, process_image
|
| 8 |
+
from infer_script import run_inference
|
| 9 |
+
|
| 10 |
+
import time
|
| 11 |
+
import datetime
|
| 12 |
+
import shutil
|
| 13 |
+
|
| 14 |
+
import imageio
|
| 15 |
+
from media_pipe.draw_util import FaceMeshVisualizer
|
| 16 |
+
|
| 17 |
+
from download_models import download
|
| 18 |
+
|
| 19 |
+
# Download models and check for exists
|
| 20 |
+
download()
|
| 21 |
+
|
| 22 |
+
PROCESSED_VIDEO_DIR = './processed_videos'
|
| 23 |
+
TEMP_DIR = './temp'
|
| 24 |
+
INFER_CONFIG_PATH = './configs/infer.yaml'
|
| 25 |
+
MODEL_PATH = './ckpt_models/ckpts'
|
| 26 |
+
OUTPUT_PATH = './output'
|
| 27 |
+
|
| 28 |
+
def load_config():
|
| 29 |
+
with open(INFER_CONFIG_PATH, 'r') as file:
|
| 30 |
+
return yaml.safe_load(file)
|
| 31 |
+
|
| 32 |
+
def save_config(config):
|
| 33 |
+
with open(INFER_CONFIG_PATH, 'w') as file:
|
| 34 |
+
yaml.dump(config, file)
|
| 35 |
+
|
| 36 |
+
config = load_config()
|
| 37 |
+
|
| 38 |
+
def get_video_fps(video_path):
|
| 39 |
+
video = cv2.VideoCapture(video_path)
|
| 40 |
+
fps = video.get(cv2.CAP_PROP_FPS)
|
| 41 |
+
video.release()
|
| 42 |
+
return int(fps)
|
| 43 |
+
|
| 44 |
+
def update_npy_choices():
|
| 45 |
+
npy_files = get_npy_files(PROCESSED_VIDEO_DIR)
|
| 46 |
+
return gr.update(choices=["None"] + npy_files)
|
| 47 |
+
|
| 48 |
+
def create_gif_from_npy(npy_path, gif_path):
|
| 49 |
+
face_results = np.load(npy_path, allow_pickle=True)
|
| 50 |
+
vis = FaceMeshVisualizer(forehead_edge=False)
|
| 51 |
+
|
| 52 |
+
frames = []
|
| 53 |
+
for face_result in face_results:
|
| 54 |
+
width = face_result['width']
|
| 55 |
+
height = face_result['height']
|
| 56 |
+
lmks = face_result['lmks'].astype(np.float32)
|
| 57 |
+
frame = vis.draw_landmarks((width, height), lmks, normed=True)
|
| 58 |
+
frames.append(frame)
|
| 59 |
+
|
| 60 |
+
imageio.mimsave(gif_path, frames, 'GIF', duration=0.2, loop=0)
|
| 61 |
+
return gif_path
|
| 62 |
+
|
| 63 |
+
def show_gif_for_npy(npy_file, video_path):
|
| 64 |
+
if npy_file and npy_file != "None":
|
| 65 |
+
npy_path = npy_file
|
| 66 |
+
elif video_path:
|
| 67 |
+
video_name = os.path.splitext(os.path.basename(video_path))[0]
|
| 68 |
+
npy_path = os.path.join(PROCESSED_VIDEO_DIR if input_video_save.value else TEMP_DIR, video_name, f"{video_name}_mppose.npy")
|
| 69 |
+
else:
|
| 70 |
+
return None, None, "No NPY file or video selected"
|
| 71 |
+
|
| 72 |
+
if not os.path.exists(npy_path):
|
| 73 |
+
return None, None, "NPY file not found"
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
gif_path = os.path.join(os.path.dirname(npy_path), f"{os.path.splitext(os.path.basename(npy_path))[0]}_preview.gif")
|
| 77 |
+
gif_path_align = os.path.join(os.path.dirname(npy_path), f"{os.path.splitext(os.path.basename(npy_path))[0]}_aligned.gif")
|
| 78 |
+
create_gif_from_npy(npy_path, gif_path)
|
| 79 |
+
return gif_path,gif_path_align, "GIF created and displayed"
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return None, None, f"Failed to create GIF: {str(e)}"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def process_input_video(video, save_to_processed):
|
| 85 |
+
if video is None:
|
| 86 |
+
return "No video uploaded", None, gr.update(), gr.update()
|
| 87 |
+
|
| 88 |
+
video_name = os.path.splitext(os.path.basename(video))[0]
|
| 89 |
+
|
| 90 |
+
if save_to_processed:
|
| 91 |
+
save_dir = os.path.join(PROCESSED_VIDEO_DIR, video_name)
|
| 92 |
+
else:
|
| 93 |
+
save_dir = os.path.join(TEMP_DIR, video_name)
|
| 94 |
+
|
| 95 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 96 |
+
|
| 97 |
+
npy_path, frame_count = process_video(video, save_dir)
|
| 98 |
+
frame_count = frame_count - 1
|
| 99 |
+
fps = get_video_fps(video)
|
| 100 |
+
|
| 101 |
+
return (f"Video processed. NPY file saved at {npy_path}. Original FPS: {fps}",
|
| 102 |
+
npy_path,
|
| 103 |
+
gr.update(maximum=frame_count, value=frame_count),
|
| 104 |
+
gr.update(value=f"Reference video FPS: {fps}"))
|
| 105 |
+
|
| 106 |
+
def update_frame_count(npy_file):
|
| 107 |
+
if npy_file is None or npy_file == "None":
|
| 108 |
+
return gr.update()
|
| 109 |
+
frame_count = get_frame_count(npy_file)
|
| 110 |
+
return gr.update(maximum=frame_count, value=frame_count)
|
| 111 |
+
|
| 112 |
+
def update_gif_on_video_change(video):
|
| 113 |
+
if video:
|
| 114 |
+
gif_path,gif_path_align, status = show_gif_for_npy(None, video)
|
| 115 |
+
return gif_path,gif_path_align, status
|
| 116 |
+
return None, None, "No video selected"
|
| 117 |
+
|
| 118 |
+
def toggle_fps_slider(use_custom):
|
| 119 |
+
return gr.update(interactive=use_custom)
|
| 120 |
+
|
| 121 |
+
def crop_face(image_path, should_crop_face, npy_file, video_path, expand_x, expand_y, offset_x, offset_y):
|
| 122 |
+
if not should_crop_face:
|
| 123 |
+
return image_path, "Face cropping not requested"
|
| 124 |
+
|
| 125 |
+
if npy_file and npy_file != "None":
|
| 126 |
+
npy_path = npy_file
|
| 127 |
+
elif video_path:
|
| 128 |
+
video_name = os.path.splitext(os.path.basename(video_path))[0]
|
| 129 |
+
npy_path = os.path.join(PROCESSED_VIDEO_DIR, video_name, f"{video_name}_mppose.npy")
|
| 130 |
+
if not os.path.exists(npy_path):
|
| 131 |
+
npy_path = os.path.join(TEMP_DIR, video_name, f"{video_name}_mppose.npy")
|
| 132 |
+
else:
|
| 133 |
+
return image_path, "No NPY file or video selected for face cropping"
|
| 134 |
+
|
| 135 |
+
if not os.path.exists(npy_path):
|
| 136 |
+
return image_path, "NPY file not found for face cropping"
|
| 137 |
+
|
| 138 |
+
save_dir = os.path.dirname(npy_path)
|
| 139 |
+
cropped_image_path, motion_path = process_image(image_path, npy_path, save_dir, expand_x, expand_y, offset_x, offset_y)
|
| 140 |
+
|
| 141 |
+
if cropped_image_path:
|
| 142 |
+
return cropped_image_path, "Face cropped successfully"
|
| 143 |
+
else:
|
| 144 |
+
return image_path, "Face cropping failed"
|
| 145 |
+
|
| 146 |
+
def preview_crop(image_path, npy_file, video_path, expand_x, expand_y, offset_x, offset_y):
|
| 147 |
+
if not image_path:
|
| 148 |
+
return None,None, "No image uploaded"
|
| 149 |
+
|
| 150 |
+
if npy_file and npy_file != "None":
|
| 151 |
+
npy_path = npy_file
|
| 152 |
+
elif video_path:
|
| 153 |
+
video_name = os.path.splitext(os.path.basename(video_path))[0]
|
| 154 |
+
npy_path = os.path.join(PROCESSED_VIDEO_DIR, video_name, f"{video_name}_mppose.npy")
|
| 155 |
+
if not os.path.exists(npy_path):
|
| 156 |
+
npy_path = os.path.join(TEMP_DIR, video_name, f"{video_name}_mppose.npy")
|
| 157 |
+
else:
|
| 158 |
+
return None,None, "No NPY file or video selected for face cropping"
|
| 159 |
+
|
| 160 |
+
if not os.path.exists(npy_path):
|
| 161 |
+
return None,None, "NPY file not found for face cropping"
|
| 162 |
+
|
| 163 |
+
save_dir = TEMP_DIR
|
| 164 |
+
# Create if not exists
|
| 165 |
+
os.makedirs(save_dir, exist_ok=True)
|
| 166 |
+
cropped_image_path, motion_path = process_image(image_path, npy_path, save_dir, expand_x, expand_y, offset_x, offset_y)
|
| 167 |
+
|
| 168 |
+
if cropped_image_path:
|
| 169 |
+
return cropped_image_path,motion_path, "Crop preview generated"
|
| 170 |
+
else:
|
| 171 |
+
return None,None, "Failed to generate crop preview"
|
| 172 |
+
|
| 173 |
+
def generate_video(input_img, should_crop_face, expand_x, expand_y, offset_x, offset_y, input_video_type, input_video, input_npy_select, input_npy, input_video_frames,
|
| 174 |
+
settings_steps, settings_cfg_scale, settings_seed, resolution_w, resolution_h,
|
| 175 |
+
model_step, custom_output_path, use_custom_fps, output_fps, callback_steps, context_frames, context_stride, context_overlap, context_batch_size, anomaly_action,intropolate_factor):
|
| 176 |
+
config['resolution_w'] = resolution_w
|
| 177 |
+
config['resolution_h'] = resolution_h
|
| 178 |
+
config['video_length'] = input_video_frames
|
| 179 |
+
save_config(config)
|
| 180 |
+
|
| 181 |
+
if input_video_type == "video":
|
| 182 |
+
video_name = os.path.splitext(os.path.basename(input_video))[0]
|
| 183 |
+
lmk_path = os.path.join(PROCESSED_VIDEO_DIR if input_video_save.value else TEMP_DIR, video_name, f"{video_name}_mppose.npy")
|
| 184 |
+
if not use_custom_fps:
|
| 185 |
+
output_fps = 7
|
| 186 |
+
else:
|
| 187 |
+
if input_npy_select != "None":
|
| 188 |
+
lmk_path = input_npy_select
|
| 189 |
+
else:
|
| 190 |
+
lmk_path = input_npy
|
| 191 |
+
video_name = os.path.splitext(os.path.basename(lmk_path))[0]
|
| 192 |
+
if not use_custom_fps:
|
| 193 |
+
output_fps = 7 # default FPS
|
| 194 |
+
|
| 195 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 196 |
+
output_folder = f"{video_name}_{timestamp}"
|
| 197 |
+
|
| 198 |
+
if custom_output_path:
|
| 199 |
+
output_path = os.path.join(custom_output_path, output_folder)
|
| 200 |
+
else:
|
| 201 |
+
output_path = os.path.join(OUTPUT_PATH, output_folder)
|
| 202 |
+
|
| 203 |
+
os.makedirs(output_path, exist_ok=True)
|
| 204 |
+
|
| 205 |
+
if should_crop_face:
|
| 206 |
+
cropped_image_path, crop_status = crop_face(input_img, should_crop_face, input_npy_select if input_video_type == "npy" else None, input_video if input_video_type == "video" else None, expand_x, expand_y, offset_x, offset_y)
|
| 207 |
+
print(crop_status)
|
| 208 |
+
|
| 209 |
+
if cropped_image_path and os.path.exists(cropped_image_path):
|
| 210 |
+
cropped_face_in_result = os.path.join(output_path, "cropped_face.png")
|
| 211 |
+
shutil.copy(cropped_image_path, cropped_face_in_result)
|
| 212 |
+
print(f"Cropped face saved in result folder: {cropped_face_in_result}")
|
| 213 |
+
|
| 214 |
+
input_img = cropped_image_path
|
| 215 |
+
|
| 216 |
+
status, oo_video_path, all_video_path = run_inference(
|
| 217 |
+
config_path=INFER_CONFIG_PATH,
|
| 218 |
+
model_path=MODEL_PATH,
|
| 219 |
+
input_path=input_img,
|
| 220 |
+
lmk_path=lmk_path,
|
| 221 |
+
output_path=output_path,
|
| 222 |
+
model_step=model_step,
|
| 223 |
+
seed=settings_seed,
|
| 224 |
+
resolution_w=resolution_w,
|
| 225 |
+
resolution_h=resolution_h,
|
| 226 |
+
video_length=input_video_frames,
|
| 227 |
+
num_inference_steps=settings_steps,
|
| 228 |
+
guidance_scale=settings_cfg_scale,
|
| 229 |
+
output_fps=output_fps,
|
| 230 |
+
callback_steps=callback_steps,
|
| 231 |
+
context_frames=context_frames,
|
| 232 |
+
context_stride=context_stride,
|
| 233 |
+
context_overlap=context_overlap,
|
| 234 |
+
context_batch_size=context_batch_size,
|
| 235 |
+
anomaly_action=anomaly_action,
|
| 236 |
+
interpolation_factor=intropolate_factor
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
frames_archive = None
|
| 241 |
+
frames_dir = os.path.join(output_path, f"frames")
|
| 242 |
+
if os.path.exists(frames_dir):
|
| 243 |
+
archive_path = os.path.join(output_path, f"frames.zip")
|
| 244 |
+
with zipfile.ZipFile(archive_path, 'w') as zipf:
|
| 245 |
+
for root, dirs, files in os.walk(frames_dir):
|
| 246 |
+
for file in files:
|
| 247 |
+
zipf.write(os.path.join(root, file),
|
| 248 |
+
os.path.relpath(os.path.join(root, file),
|
| 249 |
+
os.path.join(frames_dir, '..')))
|
| 250 |
+
frames_archive = archive_path
|
| 251 |
+
print(f"The archive has been created: {archive_path}")
|
| 252 |
+
else:
|
| 253 |
+
print(f"Directory with frames not found: {frames_dir}")
|
| 254 |
+
|
| 255 |
+
return status, oo_video_path, all_video_path, frames_archive
|
| 256 |
|
| 257 |
with gr.Blocks() as demo:
|
| 258 |
+
gr.Markdown("# FollowYourEmoji Webui")
|
| 259 |
+
|
| 260 |
+
with gr.Row():
|
| 261 |
+
with gr.Column(scale=1):
|
| 262 |
+
input_img = gr.Image(label="Upload reference image", type="filepath", height=500)
|
| 263 |
+
|
| 264 |
+
crop_face_checkbox = gr.Checkbox(label="Crop face according to video",info="If your picture is too far away or the face doesn't fit you can use cropping, you can see a preview in the tab below", value=False)
|
| 265 |
+
with gr.Accordion("Face Cropping", open=False):
|
| 266 |
+
expand_x = gr.Slider(label="Expand X", minimum=0.5, maximum=5.0, value=1.2, step=0.01)
|
| 267 |
+
expand_y = gr.Slider(label="Expand Y", minimum=0.5, maximum=5.0, value=1.2, step=0.01)
|
| 268 |
+
offset_x = gr.Slider(label="Offset X", minimum=-1, maximum=1, value=0.0, step=0.01)
|
| 269 |
+
offset_y = gr.Slider(label="Offset Y", minimum=-1, maximum=1, value=0.0, step=0.01)
|
| 270 |
+
|
| 271 |
+
preview_crop_btn = gr.Button(value="Preview Crop")
|
| 272 |
+
with gr.Row():
|
| 273 |
+
crop_preview = gr.Image(label="Crop Preview", height=300)
|
| 274 |
+
crop_preview_motion = gr.Image(label="Preview motion Crop", height=300)
|
| 275 |
+
|
| 276 |
+
with gr.Accordion("Input Video", open=True):
|
| 277 |
+
input_video_type = gr.Radio(label="Input reference video type",info="You can either upload the video through the interface or use an already compiled npy file", choices=["video","npy"], value="video")
|
| 278 |
+
|
| 279 |
+
with gr.Group() as video_group:
|
| 280 |
+
input_video = gr.Video(label="Upload reference video", height=500)
|
| 281 |
+
input_video_save = gr.Checkbox(label="Save video to processed video folder", value=True)
|
| 282 |
|
| 283 |
+
with gr.Group(visible=False) as npy_group:
|
| 284 |
+
input_npy_select = gr.Dropdown(label="Select from processed video folder", choices=["None"], value="None")
|
| 285 |
+
input_npy_refresh = gr.Button(value="Update NPY list")
|
| 286 |
+
input_npy = gr.File(file_types=[".npy"], label="Upload preprocessed video in .npy")
|
| 287 |
+
with gr.Accordion("Animation Preview",open=False):
|
| 288 |
+
show_gif_btn = gr.Button(value="Show Animation preview")
|
| 289 |
+
with gr.Row():
|
| 290 |
+
gif_output = gr.Image(label="GIF Preview", height=300)
|
| 291 |
+
gif_output_align = gr.Image(label="Aligned GIF Preview", height=300)
|
| 292 |
+
|
| 293 |
+
with gr.Accordion("Animation Settings", open=True):
|
| 294 |
+
input_video_frames = gr.Slider(label="Video frames", minimum=1, maximum=30, value=30, step=1)
|
| 295 |
+
settings_steps = gr.Slider(label="Steps", minimum=1, maximum=200, value=30)
|
| 296 |
+
settings_cfg_scale = gr.Slider(label="CFG scale", minimum=0.1, maximum=20, value=3.5, step=0.1)
|
| 297 |
+
settings_seed = gr.Slider(minimum=0, maximum=1000, value=42, step=1, label="Seed")
|
| 298 |
+
intropolate_factor = gr.Slider(label="Intropolate Factor Frames",info="This is the number of frames to interpolate between the frames", minimum=1, maximum=50, value=1, step=1)
|
| 299 |
+
|
| 300 |
+
use_custom_fps = gr.Checkbox(label="Use custom FPS",info="By default the FPS is set to 7", value=True)
|
| 301 |
+
with gr.Row():
|
| 302 |
+
output_fps = gr.Slider(label="Output FPS",info="if you upload video fps slider updates to video fps", minimum=1, maximum=240, value=15, step=1)
|
| 303 |
+
output_fps_info = gr.Label(value="This will be the FPS information of the video you uploaded")
|
| 304 |
+
|
| 305 |
+
with gr.Accordion("Generation Settings", open=True):
|
| 306 |
+
context_frames = gr.Slider(label="Context Frames", minimum=1, maximum=50, value=24, step=1)
|
| 307 |
+
context_stride = gr.Slider(label="Context Stride", minimum=1, maximum=10, value=1, step=1)
|
| 308 |
+
context_overlap = gr.Slider(label="Context Overlap", minimum=0, maximum=10, value=4, step=1)
|
| 309 |
+
context_batch_size = gr.Slider(label="Context Batch Size", minimum=1, maximum=10, value=1, step=1)
|
| 310 |
+
callback_steps = gr.Slider(label="Callback Steps", minimum=1, maximum=50, value=1, step=1)
|
| 311 |
+
|
| 312 |
+
with gr.Accordion("Advanced Settings", open=False):
|
| 313 |
+
resolution_w = gr.Slider(label="Resolution Width", minimum=64, maximum=1024, value=config['resolution_w'], step=64)
|
| 314 |
+
resolution_h = gr.Slider(label="Resolution Height", minimum=64, maximum=1024, value=config['resolution_h'], step=64)
|
| 315 |
+
model_step = gr.Slider(label="Model Step", value=0, minimum=0, maximum=100)
|
| 316 |
+
custom_output_path = gr.Textbox(label="Custom Output Path", placeholder="Leave empty for default")
|
| 317 |
+
anomaly_action = gr.Radio(label="Anomaly Action",info="Sometimes a bad frame can slip through and this function will detect it and do what you specify", choices=["none", "remove"], value="none")
|
| 318 |
+
|
| 319 |
+
with gr.Column(scale=1):
|
| 320 |
+
result_status = gr.Label(value="Status")
|
| 321 |
+
result_video = gr.Video(label="Result Video (oo)", interactive=False, height=500)
|
| 322 |
+
result_video_2 = gr.Video(label="Result Video (all)", interactive=False, height=500)
|
| 323 |
+
result_btn = gr.Button(value="Generate Video")
|
| 324 |
+
frames_output = gr.File(label="Frames Archive ( You'll get an archive with all the frames )")
|
| 325 |
+
|
| 326 |
+
input_video_type.change(
|
| 327 |
+
fn=lambda x: (gr.update(visible=(x=="video")), gr.update(visible=(x=="npy"))),
|
| 328 |
+
inputs=[input_video_type],
|
| 329 |
+
outputs=[video_group, npy_group]
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
input_npy_refresh.click(fn=update_npy_choices, outputs=[input_npy_select])
|
| 333 |
+
|
| 334 |
+
input_video.change(
|
| 335 |
+
fn=process_input_video,
|
| 336 |
+
inputs=[input_video, input_video_save],
|
| 337 |
+
outputs=[result_status, input_npy, input_video_frames, output_fps_info]
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
input_npy_select.change(fn=update_frame_count, inputs=[input_npy_select], outputs=[input_video_frames])
|
| 341 |
+
input_npy.change(fn=update_frame_count, inputs=[input_npy], outputs=[input_video_frames])
|
| 342 |
+
|
| 343 |
+
show_gif_btn.click(fn=show_gif_for_npy, inputs=[input_npy_select, input_video], outputs=[gif_output, gif_output_align, result_status])
|
| 344 |
+
|
| 345 |
+
input_video.change(
|
| 346 |
+
fn=update_gif_on_video_change,
|
| 347 |
+
inputs=[input_video],
|
| 348 |
+
outputs=[gif_output,gif_output_align, result_status]
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
use_custom_fps.change(fn=toggle_fps_slider, inputs=[use_custom_fps], outputs=[output_fps])
|
| 352 |
+
|
| 353 |
+
preview_crop_btn.click(
|
| 354 |
+
fn=preview_crop,
|
| 355 |
+
inputs=[input_img, input_npy_select, input_video, expand_x, expand_y, offset_x, offset_y],
|
| 356 |
+
outputs=[crop_preview,crop_preview_motion, result_status]
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
result_btn.click(
|
| 360 |
+
fn=generate_video,
|
| 361 |
+
inputs=[input_img, crop_face_checkbox, expand_x, expand_y, offset_x, offset_y, input_video_type, input_video, input_npy_select, input_npy, input_video_frames,
|
| 362 |
+
settings_steps, settings_cfg_scale, settings_seed, resolution_w, resolution_h,
|
| 363 |
+
model_step, custom_output_path, use_custom_fps, output_fps, callback_steps, context_frames, context_stride, context_overlap, context_batch_size, anomaly_action,intropolate_factor],
|
| 364 |
+
outputs=[result_status, result_video, result_video_2, frames_output]
|
| 365 |
+
)
|
| 366 |
|
| 367 |
if __name__ == "__main__":
|
| 368 |
+
import argparse
|
| 369 |
+
|
| 370 |
+
parser = argparse.ArgumentParser()
|
| 371 |
+
parser.add_argument("--share", action="store_true", help="Enable sharing")
|
| 372 |
+
args = parser.parse_args()
|
| 373 |
+
|
| 374 |
+
share = args.share
|
| 375 |
+
|
| 376 |
+
demo.queue()
|
| 377 |
+
demo.launch(inbrowser=True, share=share)
|
assets/wechat_group.png
ADDED
|
Git LFS Details
|
colab/follow_emoji_collab_nowebui.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
colab/follow_emoji_collab_webui.ipynb
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"gpuType": "T4"
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "markdown",
|
| 21 |
+
"source": [
|
| 22 |
+
"# Install"
|
| 23 |
+
],
|
| 24 |
+
"metadata": {
|
| 25 |
+
"id": "kR252w8vtFWA"
|
| 26 |
+
}
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"metadata": {
|
| 32 |
+
"id": "k5B0WQVVi3cT"
|
| 33 |
+
},
|
| 34 |
+
"outputs": [],
|
| 35 |
+
"source": [
|
| 36 |
+
"!git clone https://github.com/daswer123/FollowYourEmoji-Webui\n",
|
| 37 |
+
"%cd FollowYourEmoji-Webui"
|
| 38 |
+
]
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"source": [
|
| 43 |
+
"!bash install.sh"
|
| 44 |
+
],
|
| 45 |
+
"metadata": {
|
| 46 |
+
"id": "-5hROqAYjeVb"
|
| 47 |
+
},
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "markdown",
|
| 53 |
+
"source": [
|
| 54 |
+
"# Launch"
|
| 55 |
+
],
|
| 56 |
+
"metadata": {
|
| 57 |
+
"id": "7krfhnvEtADP"
|
| 58 |
+
}
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"source": [
|
| 63 |
+
"!python app.py --share"
|
| 64 |
+
],
|
| 65 |
+
"metadata": {
|
| 66 |
+
"colab": {
|
| 67 |
+
"base_uri": "https://localhost:8080/"
|
| 68 |
+
},
|
| 69 |
+
"id": "rxriG5mamSik",
|
| 70 |
+
"outputId": "a7d6176a-7826-4ca4-d8aa-c33cb95a6cd3"
|
| 71 |
+
},
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": [
|
| 74 |
+
{
|
| 75 |
+
"output_type": "stream",
|
| 76 |
+
"name": "stdout",
|
| 77 |
+
"text": [
|
| 78 |
+
"2024-07-21 14:35:33.007177: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
|
| 79 |
+
"2024-07-21 14:35:33.007235: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
|
| 80 |
+
"2024-07-21 14:35:33.127726: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
|
| 81 |
+
"2024-07-21 14:35:33.360274: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
|
| 82 |
+
"To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
|
| 83 |
+
"2024-07-21 14:35:35.639368: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
|
| 84 |
+
"Running on local URL: http://127.0.0.1:7860\n",
|
| 85 |
+
"Running on public URL: https://5c036442439b2f60ff.gradio.live\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n",
|
| 88 |
+
"WARNING: All log messages before absl::InitializeLog() is called are written to STDERR\n",
|
| 89 |
+
"I0000 00:00:1721572771.168555 10442 task_runner.cc:85] GPU suport is not available: INTERNAL: ; RET_CHECK failure (mediapipe/gpu/gl_context_egl.cc:84) egl_initializedUnable to initialize EGL\n",
|
| 90 |
+
"W0000 00:00:1721572771.219233 10442 face_landmarker_graph.cc:174] Sets FaceBlendshapesGraph acceleration to xnnpack by default.\n",
|
| 91 |
+
"INFO: Created TensorFlow Lite XNNPACK delegate for CPU.\n",
|
| 92 |
+
"I0000 00:00:1721572771.324455 10442 task_runner.cc:85] GPU suport is not available: INTERNAL: ; RET_CHECK failure (mediapipe/gpu/gl_context_egl.cc:84) egl_initializedUnable to initialize EGL\n",
|
| 93 |
+
"/usr/lib/python3.10/subprocess.py:1796: RuntimeWarning: os.fork() was called. os.fork() is incompatible with multithreaded code, and JAX is multithreaded, so this will likely lead to a deadlock.\n",
|
| 94 |
+
" self.pid = _posixsubprocess.fork_exec(\n",
|
| 95 |
+
"/usr/local/lib/python3.10/dist-packages/google/protobuf/symbol_database.py:55: UserWarning: SymbolDatabase.GetPrototype() is deprecated. Please use message_factory.GetMessageClass() instead. SymbolDatabase.GetPrototype() will be removed soon.\n",
|
| 96 |
+
" warnings.warn('SymbolDatabase.GetPrototype() is deprecated. Please '\n",
|
| 97 |
+
" 0% 97/9223372036854775807 [00:03<101657803499837:49:52, 25.20it/s]\n",
|
| 98 |
+
"I0000 00:00:1721573091.117283 10442 task_runner.cc:85] GPU suport is not available: INTERNAL: ; RET_CHECK failure (mediapipe/gpu/gl_context_egl.cc:84) egl_initializedUnable to initialize EGL\n",
|
| 99 |
+
"W0000 00:00:1721573091.117818 10442 face_landmarker_graph.cc:174] Sets FaceBlendshapesGraph acceleration to xnnpack by default.\n",
|
| 100 |
+
"I0000 00:00:1721573091.142969 10442 task_runner.cc:85] GPU suport is not available: INTERNAL: ; RET_CHECK failure (mediapipe/gpu/gl_context_egl.cc:84) egl_initializedUnable to initialize EGL\n",
|
| 101 |
+
"/usr/local/lib/python3.10/dist-packages/google/protobuf/symbol_database.py:55: UserWarning: SymbolDatabase.GetPrototype() is deprecated. Please use message_factory.GetMessageClass() instead. SymbolDatabase.GetPrototype() will be removed soon.\n",
|
| 102 |
+
" warnings.warn('SymbolDatabase.GetPrototype() is deprecated. Please '\n",
|
| 103 |
+
"Face cropped successfully\n",
|
| 104 |
+
"Cropped face saved in result folder: ./output/test_20240721_144451/cropped_face.png\n",
|
| 105 |
+
"/usr/local/lib/python3.10/dist-packages/torch/_utils.py:831: UserWarning: TypedStorage is deprecated. It will be removed in the future and UntypedStorage will be the only storage class. This should only matter to you if you are using storages directly. To access UntypedStorage directly, use tensor.untyped_storage() instead of tensor.storage()\n",
|
| 106 |
+
" return self.fget.__get__(instance, owner)()\n"
|
| 107 |
+
]
|
| 108 |
+
}
|
| 109 |
+
]
|
| 110 |
+
}
|
| 111 |
+
]
|
| 112 |
+
}
|
colab/infer.py
ADDED
|
@@ -0,0 +1,228 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import imageio
|
| 3 |
+
import argparse
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from omegaconf import OmegaConf
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed as dist
|
| 10 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 11 |
+
from torch.utils.data import DataLoader
|
| 12 |
+
import torchvision.transforms as T
|
| 13 |
+
|
| 14 |
+
from diffusers import AutoencoderKL, DDIMScheduler
|
| 15 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 16 |
+
|
| 17 |
+
from transformers import CLIPVisionModelWithProjection
|
| 18 |
+
|
| 19 |
+
from models.guider import Guider
|
| 20 |
+
from models.referencenet import ReferenceNet2DConditionModel
|
| 21 |
+
from models.unet import UNet3DConditionModel
|
| 22 |
+
from models.video_pipeline import VideoPipeline
|
| 23 |
+
|
| 24 |
+
from dataset.val_dataset import ValDataset, val_collate_fn
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_model_state_dict(model, model_ckpt_path, name):
|
| 28 |
+
ckpt = torch.load(model_ckpt_path, map_location="cpu")
|
| 29 |
+
model_state_dict = model.state_dict()
|
| 30 |
+
model_new_sd = {}
|
| 31 |
+
count = 0
|
| 32 |
+
for k, v in ckpt.items():
|
| 33 |
+
if k in model_state_dict:
|
| 34 |
+
count += 1
|
| 35 |
+
model_new_sd[k] = v
|
| 36 |
+
miss, _ = model.load_state_dict(model_new_sd, strict=False)
|
| 37 |
+
print(f'load {name} from {model_ckpt_path}\n - load params: {count}\n - miss params: {miss}')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@torch.no_grad()
|
| 41 |
+
def visualize(dataloader, pipeline, generator, W, H, video_length, num_inference_steps, guidance_scale, output_dir, limit=1):
|
| 42 |
+
|
| 43 |
+
for i, batch in enumerate(dataloader):
|
| 44 |
+
ref_frame=batch['ref_frame'][0]
|
| 45 |
+
clip_image = batch['clip_image'][0]
|
| 46 |
+
motions=batch['motions'][0]
|
| 47 |
+
file_name = batch['file_name'][0]
|
| 48 |
+
if motions is None:
|
| 49 |
+
continue
|
| 50 |
+
if 'lmk_name' in batch:
|
| 51 |
+
lmk_name = batch['lmk_name'][0].split('.')[0]
|
| 52 |
+
else:
|
| 53 |
+
lmk_name = 'lmk'
|
| 54 |
+
print(file_name, lmk_name)
|
| 55 |
+
# tensor to pil image
|
| 56 |
+
ref_frame = torch.clamp((ref_frame + 1.0) / 2.0, min=0, max=1)
|
| 57 |
+
ref_frame = ref_frame.permute((1, 2, 3, 0)).squeeze()
|
| 58 |
+
ref_frame = (ref_frame * 255).cpu().numpy().astype(np.uint8)
|
| 59 |
+
ref_image = Image.fromarray(ref_frame)
|
| 60 |
+
# tensor to pil image
|
| 61 |
+
motions = motions.permute((1, 2, 3, 0))
|
| 62 |
+
motions = (motions * 255).cpu().numpy().astype(np.uint8)
|
| 63 |
+
lmk_images = []
|
| 64 |
+
for motion in motions:
|
| 65 |
+
lmk_images.append(Image.fromarray(motion))
|
| 66 |
+
|
| 67 |
+
preds = pipeline(ref_image=ref_image,
|
| 68 |
+
lmk_images=lmk_images,
|
| 69 |
+
width=W,
|
| 70 |
+
height=H,
|
| 71 |
+
video_length=video_length,
|
| 72 |
+
num_inference_steps=num_inference_steps,
|
| 73 |
+
guidance_scale=guidance_scale,
|
| 74 |
+
generator=generator,
|
| 75 |
+
clip_image=clip_image,
|
| 76 |
+
).videos
|
| 77 |
+
|
| 78 |
+
preds = preds.permute((0,2,3,4,1)).squeeze(0)
|
| 79 |
+
preds = (preds * 255).cpu().numpy().astype(np.uint8)
|
| 80 |
+
|
| 81 |
+
mp4_path = os.path.join(output_dir, lmk_name+'_'+file_name.split('.')[0]+'_oo.mp4')
|
| 82 |
+
mp4_writer = imageio.get_writer(mp4_path, fps=7)
|
| 83 |
+
for pred in preds:
|
| 84 |
+
mp4_writer.append_data(pred)
|
| 85 |
+
mp4_writer.close()
|
| 86 |
+
|
| 87 |
+
mp4_path = os.path.join(output_dir, lmk_name+'_'+file_name.split('.')[0]+'_all.mp4')
|
| 88 |
+
mp4_writer = imageio.get_writer(mp4_path, fps=8)
|
| 89 |
+
if 'frames' in batch:
|
| 90 |
+
frames = batch['frames'][0]
|
| 91 |
+
frames = torch.clamp((frames + 1.0) / 2.0, min=0, max=1)
|
| 92 |
+
frames = frames.permute((1, 2, 3, 0))
|
| 93 |
+
frames = (frames * 255).cpu().numpy().astype(np.uint8)
|
| 94 |
+
for frame, motion, pred in zip(frames, motions, preds):
|
| 95 |
+
out = np.concatenate((frame, motion, ref_frame, pred), axis=1)
|
| 96 |
+
mp4_writer.append_data(out)
|
| 97 |
+
else:
|
| 98 |
+
for motion, pred in zip(motions, preds):
|
| 99 |
+
out = np.concatenate((motion, ref_frame, pred), axis=1)
|
| 100 |
+
mp4_writer.append_data(out)
|
| 101 |
+
mp4_writer.close()
|
| 102 |
+
|
| 103 |
+
if i >= limit:
|
| 104 |
+
break
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main(args, config):
|
| 108 |
+
dist.init_process_group(backend='nccl')
|
| 109 |
+
|
| 110 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 111 |
+
torch.cuda.set_device(local_rank)
|
| 112 |
+
|
| 113 |
+
if dist.get_rank() == 0:
|
| 114 |
+
os.makedirs(args.output_path, exist_ok=True)
|
| 115 |
+
|
| 116 |
+
if config.weight_dtype == "fp16":
|
| 117 |
+
weight_dtype = torch.float16
|
| 118 |
+
elif config.weight_dtype == "fp32":
|
| 119 |
+
weight_dtype = torch.float32
|
| 120 |
+
else:
|
| 121 |
+
raise ValueError(f"Do not support weight dtype: {config.weight_dtype} during training")
|
| 122 |
+
|
| 123 |
+
# init model
|
| 124 |
+
print('init model')
|
| 125 |
+
vae = AutoencoderKL.from_pretrained(config.vae_model_path).to(dtype=weight_dtype, device="cuda")
|
| 126 |
+
|
| 127 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(config.image_encoder_path).to(dtype=weight_dtype, device="cuda")
|
| 128 |
+
|
| 129 |
+
referencenet = ReferenceNet2DConditionModel.from_pretrained_2d(config.base_model_path,
|
| 130 |
+
referencenet_additional_kwargs=config.model.referencenet_additional_kwargs).to(device="cuda")
|
| 131 |
+
unet = UNet3DConditionModel.from_pretrained_2d(config.base_model_path,
|
| 132 |
+
motion_module_path=config.motion_module_path,
|
| 133 |
+
unet_additional_kwargs=config.model.unet_additional_kwargs).to(device="cuda")
|
| 134 |
+
|
| 135 |
+
lmk_guider = Guider(conditioning_embedding_channels=320, block_out_channels=(16, 32, 96, 256)).to(device="cuda")
|
| 136 |
+
|
| 137 |
+
# load model
|
| 138 |
+
print('load model')
|
| 139 |
+
load_model_state_dict(referencenet, f'{config.init_checkpoint}/referencenet.pth', 'referencenet')
|
| 140 |
+
load_model_state_dict(unet, f'{config.init_checkpoint}/unet.pth', 'unet')
|
| 141 |
+
load_model_state_dict(lmk_guider, f'{config.init_checkpoint}/lmk_guider.pth', 'lmk_guider')
|
| 142 |
+
|
| 143 |
+
if config.enable_xformers_memory_efficient_attention:
|
| 144 |
+
if is_xformers_available():
|
| 145 |
+
referencenet.enable_xformers_memory_efficient_attention()
|
| 146 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 147 |
+
else:
|
| 148 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 149 |
+
|
| 150 |
+
unet.set_reentrant(use_reentrant=False)
|
| 151 |
+
referencenet.set_reentrant(use_reentrant=False)
|
| 152 |
+
|
| 153 |
+
vae.eval()
|
| 154 |
+
image_encoder.eval()
|
| 155 |
+
unet.eval()
|
| 156 |
+
referencenet.eval()
|
| 157 |
+
lmk_guider.eval()
|
| 158 |
+
|
| 159 |
+
# noise scheduler
|
| 160 |
+
print('init noise scheduler')
|
| 161 |
+
sched_kwargs = OmegaConf.to_container(config.scheduler)
|
| 162 |
+
if config.enable_zero_snr:
|
| 163 |
+
sched_kwargs.update(rescale_betas_zero_snr=True,
|
| 164 |
+
timestep_spacing="trailing",
|
| 165 |
+
prediction_type="v_prediction")
|
| 166 |
+
noise_scheduler = DDIMScheduler(**sched_kwargs)
|
| 167 |
+
|
| 168 |
+
# pipeline
|
| 169 |
+
pipeline = VideoPipeline(vae=vae,
|
| 170 |
+
image_encoder=image_encoder,
|
| 171 |
+
referencenet=referencenet,
|
| 172 |
+
unet=unet,
|
| 173 |
+
lmk_guider=lmk_guider,
|
| 174 |
+
scheduler=noise_scheduler).to(vae.device, dtype=weight_dtype)
|
| 175 |
+
|
| 176 |
+
# dataset creation
|
| 177 |
+
print('init dataset')
|
| 178 |
+
val_dataset = ValDataset(
|
| 179 |
+
input_path=args.input_path,
|
| 180 |
+
lmk_path=args.lmk_path,
|
| 181 |
+
resolution_h=config.resolution_h,
|
| 182 |
+
resolution_w=config.resolution_w
|
| 183 |
+
)
|
| 184 |
+
print(len(val_dataset))
|
| 185 |
+
sampler = DistributedSampler(val_dataset, shuffle=False)
|
| 186 |
+
# DataLoaders creation:
|
| 187 |
+
val_dataloader = DataLoader(
|
| 188 |
+
val_dataset,
|
| 189 |
+
batch_size=1,
|
| 190 |
+
num_workers=0,
|
| 191 |
+
sampler=sampler,
|
| 192 |
+
collate_fn=val_collate_fn,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
generator = torch.Generator(device=vae.device)
|
| 196 |
+
generator.manual_seed(config.seed)
|
| 197 |
+
|
| 198 |
+
# run visualize
|
| 199 |
+
print('run visualize')
|
| 200 |
+
with torch.no_grad():
|
| 201 |
+
visualize(val_dataloader,
|
| 202 |
+
pipeline,
|
| 203 |
+
generator,
|
| 204 |
+
W=config.resolution_w,
|
| 205 |
+
H=config.resolution_h,
|
| 206 |
+
video_length=config.video_length,
|
| 207 |
+
num_inference_steps=30,
|
| 208 |
+
guidance_scale=3.5,
|
| 209 |
+
output_dir=args.output_path,
|
| 210 |
+
limit=100000000)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == '__main__':
|
| 214 |
+
parser = argparse.ArgumentParser()
|
| 215 |
+
parser.add_argument('--config', type=str, required=True)
|
| 216 |
+
parser.add_argument('--model_path', type=str, required=True)
|
| 217 |
+
parser.add_argument('--model_step', type=int, required=True)
|
| 218 |
+
parser.add_argument('--output_path', type=str, required=True)
|
| 219 |
+
parser.add_argument('--input_path', type=str, required=True)
|
| 220 |
+
parser.add_argument('--lmk_path', type=str, required=True)
|
| 221 |
+
parser.add_argument('--seed', type=int, default=42)
|
| 222 |
+
args = parser.parse_args()
|
| 223 |
+
|
| 224 |
+
config = OmegaConf.load(args.config)
|
| 225 |
+
config.init_checkpoint = args.model_path
|
| 226 |
+
config.init_num = args.model_step
|
| 227 |
+
|
| 228 |
+
main(args, config)
|
colab/infer.yaml
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# train
|
| 2 |
+
resolution_w: 512
|
| 3 |
+
resolution_h: 512
|
| 4 |
+
video_length: 30
|
| 5 |
+
enable_xformers_memory_efficient_attention: True
|
| 6 |
+
seed: 12580
|
| 7 |
+
weight_dtype: 'fp16' # [fp16, fp32]
|
| 8 |
+
enable_zero_snr: True
|
| 9 |
+
# pretrained model
|
| 10 |
+
base_model_path: '/content/FollowYourEmoji/ckpt_models/base/unet'
|
| 11 |
+
vae_model_path: '/content/FollowYourEmoji/ckpt_models/base/vae'
|
| 12 |
+
image_encoder_path: '/content/FollowYourEmoji/ckpt_models/base/image_encoder'
|
| 13 |
+
motion_module_path: '/content/FollowYourEmoji/ckpt_models/base/animatediff/mm_sd_v15_v2.ckpt'
|
| 14 |
+
# for infer
|
| 15 |
+
init_checkpoint: ''
|
| 16 |
+
init_num: 0
|
| 17 |
+
# model
|
| 18 |
+
model:
|
| 19 |
+
unet_additional_kwargs:
|
| 20 |
+
use_inflated_groupnorm: True
|
| 21 |
+
unet_use_cross_frame_attention: False
|
| 22 |
+
unet_use_temporal_attention: False
|
| 23 |
+
use_motion_module: True
|
| 24 |
+
motion_module_resolutions:
|
| 25 |
+
- 1
|
| 26 |
+
- 2
|
| 27 |
+
- 4
|
| 28 |
+
- 8
|
| 29 |
+
motion_module_mid_block: True
|
| 30 |
+
motion_module_decoder_only: False
|
| 31 |
+
motion_module_type: Vanilla
|
| 32 |
+
motion_module_kwargs:
|
| 33 |
+
num_attention_heads: 8
|
| 34 |
+
num_transformer_block: 1
|
| 35 |
+
attention_block_types:
|
| 36 |
+
- Temporal_Self
|
| 37 |
+
- Temporal_Self
|
| 38 |
+
temporal_position_encoding: True
|
| 39 |
+
temporal_position_encoding_max_len: 32
|
| 40 |
+
temporal_attention_dim_div: 1
|
| 41 |
+
attention_mode: SpatialAtten # SpatialAtten/ReferOnlyAtten
|
| 42 |
+
referencenet_additional_kwargs:
|
| 43 |
+
info_mode: addRefImg
|
| 44 |
+
scheduler:
|
| 45 |
+
num_train_timesteps: 1000
|
| 46 |
+
beta_start: 0.00085
|
| 47 |
+
beta_end: 0.012
|
| 48 |
+
beta_schedule: "scaled_linear"
|
| 49 |
+
steps_offset: 1
|
| 50 |
+
clip_sample: false
|
configs/infer.yaml
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
base_model_path: ./ckpt_models/base/unet
|
| 2 |
+
enable_xformers_memory_efficient_attention: true
|
| 3 |
+
enable_zero_snr: true
|
| 4 |
+
image_encoder_path: ./ckpt_models/base/image_encoder
|
| 5 |
+
init_checkpoint: ''
|
| 6 |
+
init_num: 0
|
| 7 |
+
model:
|
| 8 |
+
referencenet_additional_kwargs:
|
| 9 |
+
info_mode: addRefImg
|
| 10 |
+
unet_additional_kwargs:
|
| 11 |
+
attention_mode: SpatialAtten
|
| 12 |
+
motion_module_decoder_only: false
|
| 13 |
+
motion_module_kwargs:
|
| 14 |
+
attention_block_types:
|
| 15 |
+
- Temporal_Self
|
| 16 |
+
- Temporal_Self
|
| 17 |
+
num_attention_heads: 8
|
| 18 |
+
num_transformer_block: 1
|
| 19 |
+
temporal_attention_dim_div: 1
|
| 20 |
+
temporal_position_encoding: true
|
| 21 |
+
temporal_position_encoding_max_len: 32
|
| 22 |
+
motion_module_mid_block: true
|
| 23 |
+
motion_module_resolutions:
|
| 24 |
+
- 1
|
| 25 |
+
- 2
|
| 26 |
+
- 4
|
| 27 |
+
- 8
|
| 28 |
+
motion_module_type: Vanilla
|
| 29 |
+
unet_use_cross_frame_attention: false
|
| 30 |
+
unet_use_temporal_attention: false
|
| 31 |
+
use_inflated_groupnorm: true
|
| 32 |
+
use_motion_module: true
|
| 33 |
+
motion_module_path: ./ckpt_models/base/animatediff/mm_sd_v15_v2.ckpt
|
| 34 |
+
resolution_h: 512
|
| 35 |
+
resolution_w: 512
|
| 36 |
+
scheduler:
|
| 37 |
+
beta_end: 0.012
|
| 38 |
+
beta_schedule: scaled_linear
|
| 39 |
+
beta_start: 0.00085
|
| 40 |
+
clip_sample: false
|
| 41 |
+
num_train_timesteps: 1000
|
| 42 |
+
steps_offset: 1
|
| 43 |
+
seed: 12580
|
| 44 |
+
vae_model_path: ./ckpt_models/base/vae
|
| 45 |
+
video_length: 97
|
| 46 |
+
weight_dtype: fp16
|
dataset/__init__.py
ADDED
|
File without changes
|
dataset/val_dataset.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from PIL import Image
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.utils.data import Dataset
|
| 7 |
+
import torchvision.transforms as T
|
| 8 |
+
|
| 9 |
+
from transformers import CLIPImageProcessor
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
sys.path.append("/path/to/FollowYourEmoji")
|
| 13 |
+
from media_pipe import FaceMeshDetector, FaceMeshAlign
|
| 14 |
+
from media_pipe.draw_util import FaceMeshVisualizer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def val_collate_fn(samples):
|
| 18 |
+
return {
|
| 19 |
+
'ref_frame': [sample['ref_frame'] for sample in samples],
|
| 20 |
+
'clip_image': [sample['clip_image'] for sample in samples],
|
| 21 |
+
'motions': [sample['motions'] for sample in samples],
|
| 22 |
+
'file_name': [sample['file_name'] for sample in samples],
|
| 23 |
+
'lmk_name': [sample['lmk_name'] for sample in samples],
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ValDataset(Dataset):
|
| 28 |
+
def __init__(self, input_path, lmk_path, resolution_w=512, resolution_h=512):
|
| 29 |
+
|
| 30 |
+
print(f'Loading dataset from {input_path} and {lmk_path}')
|
| 31 |
+
|
| 32 |
+
all_img_paths = self._get_path_files(Path(input_path), file_suffix=['.jpg', '.jpeg', '.png', '.webp'])
|
| 33 |
+
all_lmk_paths = self._get_path_files(Path(lmk_path), file_suffix=['.npy'])
|
| 34 |
+
|
| 35 |
+
print(f'Found {len(all_img_paths)} image files and {len(all_lmk_paths)} lmk files')
|
| 36 |
+
print(f"ALL IMG PATH: {all_img_paths}")
|
| 37 |
+
print(f"ALL LKM PATH: {all_lmk_paths}")
|
| 38 |
+
self.all_paths = []
|
| 39 |
+
for lmk_path in all_lmk_paths:
|
| 40 |
+
for img_path in all_img_paths:
|
| 41 |
+
self.all_paths.append((img_path, lmk_path))
|
| 42 |
+
|
| 43 |
+
self.W = resolution_w
|
| 44 |
+
self.H = resolution_h
|
| 45 |
+
self.to_tensor = T.ToTensor()
|
| 46 |
+
|
| 47 |
+
self.detector = FaceMeshDetector()
|
| 48 |
+
self.aligner = FaceMeshAlign()
|
| 49 |
+
|
| 50 |
+
self.clip_image_processor = CLIPImageProcessor()
|
| 51 |
+
self.vis = FaceMeshVisualizer(forehead_edge=False, iris_edge=False, iris_point=True)
|
| 52 |
+
|
| 53 |
+
def __len__(self):
|
| 54 |
+
return len(self.all_paths)
|
| 55 |
+
|
| 56 |
+
def _get_path_files(self, path, file_suffix):
|
| 57 |
+
all_paths = []
|
| 58 |
+
if path.is_file():
|
| 59 |
+
if path.suffix.lower() in file_suffix:
|
| 60 |
+
all_paths = [path]
|
| 61 |
+
else:
|
| 62 |
+
raise ValueError('Path is not valid image file.')
|
| 63 |
+
elif path.is_dir():
|
| 64 |
+
all_paths = sorted(
|
| 65 |
+
[
|
| 66 |
+
f
|
| 67 |
+
for f in path.iterdir()
|
| 68 |
+
if f.is_file() and f.suffix.lower() in file_suffix
|
| 69 |
+
]
|
| 70 |
+
)
|
| 71 |
+
if len(all_paths) == 0:
|
| 72 |
+
raise ValueError('Folder does not contain any images.')
|
| 73 |
+
else:
|
| 74 |
+
raise ValueError
|
| 75 |
+
|
| 76 |
+
return all_paths
|
| 77 |
+
|
| 78 |
+
def get_align_motion(self, ref_lmk, temp_lmks):
|
| 79 |
+
motions = self.aligner(ref_lmk, temp_lmks)
|
| 80 |
+
motions = [self.to_tensor(motion) for motion in motions]
|
| 81 |
+
motions = torch.stack(motions).permute((1,0,2,3))
|
| 82 |
+
return motions
|
| 83 |
+
|
| 84 |
+
def __getitem__(self, index):
|
| 85 |
+
img_path, lmk_path = self.all_paths[index]
|
| 86 |
+
W, H = self.W, self.H
|
| 87 |
+
|
| 88 |
+
image = Image.open(img_path).convert('RGB')
|
| 89 |
+
|
| 90 |
+
# resize and center crop
|
| 91 |
+
scale = min(W / image.size[0], H / image.size[1])
|
| 92 |
+
ref_image = image.resize(
|
| 93 |
+
(int(image.size[0] * scale), int(image.size[1] * scale)))
|
| 94 |
+
w, h = ref_image.size[0], ref_image.size[1]
|
| 95 |
+
ref_image = ref_image.crop((w//2-W//2, h//2-H//2, w//2+W//2, h//2+H//2))
|
| 96 |
+
ref_image = np.array(ref_image)
|
| 97 |
+
|
| 98 |
+
# reference image lmk
|
| 99 |
+
ref_lmk_image, ref_lmk = self.detector(ref_image)
|
| 100 |
+
|
| 101 |
+
# clip image
|
| 102 |
+
clip_image = Image.fromarray(np.array(ref_image))
|
| 103 |
+
clip_image = self.clip_image_processor(images=clip_image, return_tensors="pt").pixel_values[0]
|
| 104 |
+
|
| 105 |
+
# reference image
|
| 106 |
+
ref_image = self.to_tensor(ref_image).unsqueeze(1)
|
| 107 |
+
ref_image = ref_image * 2.0 - 1.0
|
| 108 |
+
|
| 109 |
+
# motion sequence
|
| 110 |
+
temp_lmks = np.load(lmk_path, allow_pickle=True)
|
| 111 |
+
# landmark align and draw motions
|
| 112 |
+
if ref_lmk is not None:
|
| 113 |
+
motions = self.get_align_motion(ref_lmk, temp_lmks)
|
| 114 |
+
else:
|
| 115 |
+
motions = [
|
| 116 |
+
self.vis.draw_landmarks((H, W), lmk['lmks'].astype(np.float32), normed=True)
|
| 117 |
+
for lmk in temp_lmks
|
| 118 |
+
]
|
| 119 |
+
motions = [self.to_tensor(motion) for motion in motions]
|
| 120 |
+
motions = torch.stack(motions).permute((1,0,2,3))
|
| 121 |
+
|
| 122 |
+
example = dict()
|
| 123 |
+
example["file_name"] = str(img_path.stem).split('/')[-1]
|
| 124 |
+
example["lmk_name"] = str(lmk_path.stem).split('/')[-1]
|
| 125 |
+
example["motions"] = motions # value in [0, 1]
|
| 126 |
+
example["ref_frame"] = ref_image # value in [-1, 1]
|
| 127 |
+
example["ref_lmk_image"] = ref_lmk_image
|
| 128 |
+
example["clip_image"] = clip_image
|
| 129 |
+
|
| 130 |
+
return example
|
diffusers/__init__.py
ADDED
|
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__version__ = "0.24.0"
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from .utils import (
|
| 6 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 7 |
+
OptionalDependencyNotAvailable,
|
| 8 |
+
_LazyModule,
|
| 9 |
+
is_flax_available,
|
| 10 |
+
is_k_diffusion_available,
|
| 11 |
+
is_librosa_available,
|
| 12 |
+
is_note_seq_available,
|
| 13 |
+
is_onnx_available,
|
| 14 |
+
is_scipy_available,
|
| 15 |
+
is_torch_available,
|
| 16 |
+
is_torchsde_available,
|
| 17 |
+
is_transformers_available,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Lazy Import based on
|
| 22 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/__init__.py
|
| 23 |
+
|
| 24 |
+
# When adding a new object to this init, please add it to `_import_structure`. The `_import_structure` is a dictionary submodule to list of object names,
|
| 25 |
+
# and is used to defer the actual importing for when the objects are requested.
|
| 26 |
+
# This way `import diffusers` provides the names in the namespace without actually importing anything (and especially none of the backends).
|
| 27 |
+
|
| 28 |
+
_import_structure = {
|
| 29 |
+
"configuration_utils": ["ConfigMixin"],
|
| 30 |
+
"models": [],
|
| 31 |
+
"pipelines": [],
|
| 32 |
+
"schedulers": [],
|
| 33 |
+
"utils": [
|
| 34 |
+
"OptionalDependencyNotAvailable",
|
| 35 |
+
"is_flax_available",
|
| 36 |
+
"is_inflect_available",
|
| 37 |
+
"is_invisible_watermark_available",
|
| 38 |
+
"is_k_diffusion_available",
|
| 39 |
+
"is_k_diffusion_version",
|
| 40 |
+
"is_librosa_available",
|
| 41 |
+
"is_note_seq_available",
|
| 42 |
+
"is_onnx_available",
|
| 43 |
+
"is_scipy_available",
|
| 44 |
+
"is_torch_available",
|
| 45 |
+
"is_torchsde_available",
|
| 46 |
+
"is_transformers_available",
|
| 47 |
+
"is_transformers_version",
|
| 48 |
+
"is_unidecode_available",
|
| 49 |
+
"logging",
|
| 50 |
+
],
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
if not is_onnx_available():
|
| 55 |
+
raise OptionalDependencyNotAvailable()
|
| 56 |
+
except OptionalDependencyNotAvailable:
|
| 57 |
+
from .utils import dummy_onnx_objects # noqa F403
|
| 58 |
+
|
| 59 |
+
_import_structure["utils.dummy_onnx_objects"] = [
|
| 60 |
+
name for name in dir(dummy_onnx_objects) if not name.startswith("_")
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
else:
|
| 64 |
+
_import_structure["pipelines"].extend(["OnnxRuntimeModel"])
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
if not is_torch_available():
|
| 68 |
+
raise OptionalDependencyNotAvailable()
|
| 69 |
+
except OptionalDependencyNotAvailable:
|
| 70 |
+
from .utils import dummy_pt_objects # noqa F403
|
| 71 |
+
|
| 72 |
+
_import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")]
|
| 73 |
+
|
| 74 |
+
else:
|
| 75 |
+
_import_structure["models"].extend(
|
| 76 |
+
[
|
| 77 |
+
"AsymmetricAutoencoderKL",
|
| 78 |
+
"AutoencoderKL",
|
| 79 |
+
"AutoencoderKLTemporalDecoder",
|
| 80 |
+
"AutoencoderTiny",
|
| 81 |
+
"ConsistencyDecoderVAE",
|
| 82 |
+
"ControlNetModel",
|
| 83 |
+
"Kandinsky3UNet",
|
| 84 |
+
"ModelMixin",
|
| 85 |
+
"MotionAdapter",
|
| 86 |
+
"MultiAdapter",
|
| 87 |
+
"PriorTransformer",
|
| 88 |
+
"T2IAdapter",
|
| 89 |
+
"T5FilmDecoder",
|
| 90 |
+
"Transformer2DModel",
|
| 91 |
+
"UNet1DModel",
|
| 92 |
+
"UNet2DConditionModel",
|
| 93 |
+
"UNet2DModel",
|
| 94 |
+
"UNet3DConditionModel",
|
| 95 |
+
"UNetMotionModel",
|
| 96 |
+
"UNetSpatioTemporalConditionModel",
|
| 97 |
+
"VQModel",
|
| 98 |
+
]
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
_import_structure["optimization"] = [
|
| 102 |
+
"get_constant_schedule",
|
| 103 |
+
"get_constant_schedule_with_warmup",
|
| 104 |
+
"get_cosine_schedule_with_warmup",
|
| 105 |
+
"get_cosine_with_hard_restarts_schedule_with_warmup",
|
| 106 |
+
"get_linear_schedule_with_warmup",
|
| 107 |
+
"get_polynomial_decay_schedule_with_warmup",
|
| 108 |
+
"get_scheduler",
|
| 109 |
+
]
|
| 110 |
+
_import_structure["pipelines"].extend(
|
| 111 |
+
[
|
| 112 |
+
"AudioPipelineOutput",
|
| 113 |
+
"AutoPipelineForImage2Image",
|
| 114 |
+
"AutoPipelineForInpainting",
|
| 115 |
+
"AutoPipelineForText2Image",
|
| 116 |
+
"ConsistencyModelPipeline",
|
| 117 |
+
"DanceDiffusionPipeline",
|
| 118 |
+
"DDIMPipeline",
|
| 119 |
+
"DDPMPipeline",
|
| 120 |
+
"DiffusionPipeline",
|
| 121 |
+
"DiTPipeline",
|
| 122 |
+
"ImagePipelineOutput",
|
| 123 |
+
"KarrasVePipeline",
|
| 124 |
+
"LDMPipeline",
|
| 125 |
+
"LDMSuperResolutionPipeline",
|
| 126 |
+
"PNDMPipeline",
|
| 127 |
+
"RePaintPipeline",
|
| 128 |
+
"ScoreSdeVePipeline",
|
| 129 |
+
]
|
| 130 |
+
)
|
| 131 |
+
_import_structure["schedulers"].extend(
|
| 132 |
+
[
|
| 133 |
+
"CMStochasticIterativeScheduler",
|
| 134 |
+
"DDIMInverseScheduler",
|
| 135 |
+
"DDIMParallelScheduler",
|
| 136 |
+
"DDIMScheduler",
|
| 137 |
+
"DDPMParallelScheduler",
|
| 138 |
+
"DDPMScheduler",
|
| 139 |
+
"DDPMWuerstchenScheduler",
|
| 140 |
+
"DEISMultistepScheduler",
|
| 141 |
+
"DPMSolverMultistepInverseScheduler",
|
| 142 |
+
"DPMSolverMultistepScheduler",
|
| 143 |
+
"DPMSolverSinglestepScheduler",
|
| 144 |
+
"EulerAncestralDiscreteScheduler",
|
| 145 |
+
"EulerDiscreteScheduler",
|
| 146 |
+
"HeunDiscreteScheduler",
|
| 147 |
+
"IPNDMScheduler",
|
| 148 |
+
"KarrasVeScheduler",
|
| 149 |
+
"KDPM2AncestralDiscreteScheduler",
|
| 150 |
+
"KDPM2DiscreteScheduler",
|
| 151 |
+
"LCMScheduler",
|
| 152 |
+
"PNDMScheduler",
|
| 153 |
+
"RePaintScheduler",
|
| 154 |
+
"SchedulerMixin",
|
| 155 |
+
"ScoreSdeVeScheduler",
|
| 156 |
+
"UnCLIPScheduler",
|
| 157 |
+
"UniPCMultistepScheduler",
|
| 158 |
+
"VQDiffusionScheduler",
|
| 159 |
+
]
|
| 160 |
+
)
|
| 161 |
+
_import_structure["training_utils"] = ["EMAModel"]
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
if not (is_torch_available() and is_scipy_available()):
|
| 165 |
+
raise OptionalDependencyNotAvailable()
|
| 166 |
+
except OptionalDependencyNotAvailable:
|
| 167 |
+
from .utils import dummy_torch_and_scipy_objects # noqa F403
|
| 168 |
+
|
| 169 |
+
_import_structure["utils.dummy_torch_and_scipy_objects"] = [
|
| 170 |
+
name for name in dir(dummy_torch_and_scipy_objects) if not name.startswith("_")
|
| 171 |
+
]
|
| 172 |
+
|
| 173 |
+
else:
|
| 174 |
+
_import_structure["schedulers"].extend(["LMSDiscreteScheduler"])
|
| 175 |
+
|
| 176 |
+
try:
|
| 177 |
+
if not (is_torch_available() and is_torchsde_available()):
|
| 178 |
+
raise OptionalDependencyNotAvailable()
|
| 179 |
+
except OptionalDependencyNotAvailable:
|
| 180 |
+
from .utils import dummy_torch_and_torchsde_objects # noqa F403
|
| 181 |
+
|
| 182 |
+
_import_structure["utils.dummy_torch_and_torchsde_objects"] = [
|
| 183 |
+
name for name in dir(dummy_torch_and_torchsde_objects) if not name.startswith("_")
|
| 184 |
+
]
|
| 185 |
+
|
| 186 |
+
else:
|
| 187 |
+
_import_structure["schedulers"].extend(["DPMSolverSDEScheduler"])
|
| 188 |
+
|
| 189 |
+
try:
|
| 190 |
+
if not (is_torch_available() and is_transformers_available()):
|
| 191 |
+
raise OptionalDependencyNotAvailable()
|
| 192 |
+
except OptionalDependencyNotAvailable:
|
| 193 |
+
from .utils import dummy_torch_and_transformers_objects # noqa F403
|
| 194 |
+
|
| 195 |
+
_import_structure["utils.dummy_torch_and_transformers_objects"] = [
|
| 196 |
+
name for name in dir(dummy_torch_and_transformers_objects) if not name.startswith("_")
|
| 197 |
+
]
|
| 198 |
+
|
| 199 |
+
else:
|
| 200 |
+
_import_structure["pipelines"].extend(
|
| 201 |
+
[
|
| 202 |
+
"AltDiffusionImg2ImgPipeline",
|
| 203 |
+
"AltDiffusionPipeline",
|
| 204 |
+
"AnimateDiffPipeline",
|
| 205 |
+
"AudioLDM2Pipeline",
|
| 206 |
+
"AudioLDM2ProjectionModel",
|
| 207 |
+
"AudioLDM2UNet2DConditionModel",
|
| 208 |
+
"AudioLDMPipeline",
|
| 209 |
+
"BlipDiffusionControlNetPipeline",
|
| 210 |
+
"BlipDiffusionPipeline",
|
| 211 |
+
"CLIPImageProjection",
|
| 212 |
+
"CycleDiffusionPipeline",
|
| 213 |
+
"IFImg2ImgPipeline",
|
| 214 |
+
"IFImg2ImgSuperResolutionPipeline",
|
| 215 |
+
"IFInpaintingPipeline",
|
| 216 |
+
"IFInpaintingSuperResolutionPipeline",
|
| 217 |
+
"IFPipeline",
|
| 218 |
+
"IFSuperResolutionPipeline",
|
| 219 |
+
"ImageTextPipelineOutput",
|
| 220 |
+
"Kandinsky3Img2ImgPipeline",
|
| 221 |
+
"Kandinsky3Pipeline",
|
| 222 |
+
"KandinskyCombinedPipeline",
|
| 223 |
+
"KandinskyImg2ImgCombinedPipeline",
|
| 224 |
+
"KandinskyImg2ImgPipeline",
|
| 225 |
+
"KandinskyInpaintCombinedPipeline",
|
| 226 |
+
"KandinskyInpaintPipeline",
|
| 227 |
+
"KandinskyPipeline",
|
| 228 |
+
"KandinskyPriorPipeline",
|
| 229 |
+
"KandinskyV22CombinedPipeline",
|
| 230 |
+
"KandinskyV22ControlnetImg2ImgPipeline",
|
| 231 |
+
"KandinskyV22ControlnetPipeline",
|
| 232 |
+
"KandinskyV22Img2ImgCombinedPipeline",
|
| 233 |
+
"KandinskyV22Img2ImgPipeline",
|
| 234 |
+
"KandinskyV22InpaintCombinedPipeline",
|
| 235 |
+
"KandinskyV22InpaintPipeline",
|
| 236 |
+
"KandinskyV22Pipeline",
|
| 237 |
+
"KandinskyV22PriorEmb2EmbPipeline",
|
| 238 |
+
"KandinskyV22PriorPipeline",
|
| 239 |
+
"LatentConsistencyModelImg2ImgPipeline",
|
| 240 |
+
"LatentConsistencyModelPipeline",
|
| 241 |
+
"LDMTextToImagePipeline",
|
| 242 |
+
"MusicLDMPipeline",
|
| 243 |
+
"PaintByExamplePipeline",
|
| 244 |
+
"PixArtAlphaPipeline",
|
| 245 |
+
"SemanticStableDiffusionPipeline",
|
| 246 |
+
"ShapEImg2ImgPipeline",
|
| 247 |
+
"ShapEPipeline",
|
| 248 |
+
"StableDiffusionAdapterPipeline",
|
| 249 |
+
"StableDiffusionAttendAndExcitePipeline",
|
| 250 |
+
"StableDiffusionControlNetImg2ImgPipeline",
|
| 251 |
+
"StableDiffusionControlNetInpaintPipeline",
|
| 252 |
+
"StableDiffusionControlNetPipeline",
|
| 253 |
+
"StableDiffusionDepth2ImgPipeline",
|
| 254 |
+
"StableDiffusionDiffEditPipeline",
|
| 255 |
+
"StableDiffusionGLIGENPipeline",
|
| 256 |
+
"StableDiffusionGLIGENTextImagePipeline",
|
| 257 |
+
"StableDiffusionImageVariationPipeline",
|
| 258 |
+
"StableDiffusionImg2ImgPipeline",
|
| 259 |
+
"StableDiffusionInpaintPipeline",
|
| 260 |
+
"StableDiffusionInpaintPipelineLegacy",
|
| 261 |
+
"StableDiffusionInstructPix2PixPipeline",
|
| 262 |
+
"StableDiffusionLatentUpscalePipeline",
|
| 263 |
+
"StableDiffusionLDM3DPipeline",
|
| 264 |
+
"StableDiffusionModelEditingPipeline",
|
| 265 |
+
"StableDiffusionPanoramaPipeline",
|
| 266 |
+
"StableDiffusionParadigmsPipeline",
|
| 267 |
+
"StableDiffusionPipeline",
|
| 268 |
+
"StableDiffusionPipelineSafe",
|
| 269 |
+
"StableDiffusionPix2PixZeroPipeline",
|
| 270 |
+
"StableDiffusionSAGPipeline",
|
| 271 |
+
"StableDiffusionUpscalePipeline",
|
| 272 |
+
"StableDiffusionXLAdapterPipeline",
|
| 273 |
+
"StableDiffusionXLControlNetImg2ImgPipeline",
|
| 274 |
+
"StableDiffusionXLControlNetInpaintPipeline",
|
| 275 |
+
"StableDiffusionXLControlNetPipeline",
|
| 276 |
+
"StableDiffusionXLImg2ImgPipeline",
|
| 277 |
+
"StableDiffusionXLInpaintPipeline",
|
| 278 |
+
"StableDiffusionXLInstructPix2PixPipeline",
|
| 279 |
+
"StableDiffusionXLPipeline",
|
| 280 |
+
"StableUnCLIPImg2ImgPipeline",
|
| 281 |
+
"StableUnCLIPPipeline",
|
| 282 |
+
"StableVideoDiffusionPipeline",
|
| 283 |
+
"TextToVideoSDPipeline",
|
| 284 |
+
"TextToVideoZeroPipeline",
|
| 285 |
+
"TextToVideoZeroSDXLPipeline",
|
| 286 |
+
"UnCLIPImageVariationPipeline",
|
| 287 |
+
"UnCLIPPipeline",
|
| 288 |
+
"UniDiffuserModel",
|
| 289 |
+
"UniDiffuserPipeline",
|
| 290 |
+
"UniDiffuserTextDecoder",
|
| 291 |
+
"VersatileDiffusionDualGuidedPipeline",
|
| 292 |
+
"VersatileDiffusionImageVariationPipeline",
|
| 293 |
+
"VersatileDiffusionPipeline",
|
| 294 |
+
"VersatileDiffusionTextToImagePipeline",
|
| 295 |
+
"VideoToVideoSDPipeline",
|
| 296 |
+
"VQDiffusionPipeline",
|
| 297 |
+
"WuerstchenCombinedPipeline",
|
| 298 |
+
"WuerstchenDecoderPipeline",
|
| 299 |
+
"WuerstchenPriorPipeline",
|
| 300 |
+
]
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
try:
|
| 304 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
| 305 |
+
raise OptionalDependencyNotAvailable()
|
| 306 |
+
except OptionalDependencyNotAvailable:
|
| 307 |
+
from .utils import dummy_torch_and_transformers_and_k_diffusion_objects # noqa F403
|
| 308 |
+
|
| 309 |
+
_import_structure["utils.dummy_torch_and_transformers_and_k_diffusion_objects"] = [
|
| 310 |
+
name for name in dir(dummy_torch_and_transformers_and_k_diffusion_objects) if not name.startswith("_")
|
| 311 |
+
]
|
| 312 |
+
|
| 313 |
+
else:
|
| 314 |
+
_import_structure["pipelines"].extend(["StableDiffusionKDiffusionPipeline"])
|
| 315 |
+
|
| 316 |
+
try:
|
| 317 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
| 318 |
+
raise OptionalDependencyNotAvailable()
|
| 319 |
+
except OptionalDependencyNotAvailable:
|
| 320 |
+
from .utils import dummy_torch_and_transformers_and_onnx_objects # noqa F403
|
| 321 |
+
|
| 322 |
+
_import_structure["utils.dummy_torch_and_transformers_and_onnx_objects"] = [
|
| 323 |
+
name for name in dir(dummy_torch_and_transformers_and_onnx_objects) if not name.startswith("_")
|
| 324 |
+
]
|
| 325 |
+
|
| 326 |
+
else:
|
| 327 |
+
_import_structure["pipelines"].extend(
|
| 328 |
+
[
|
| 329 |
+
"OnnxStableDiffusionImg2ImgPipeline",
|
| 330 |
+
"OnnxStableDiffusionInpaintPipeline",
|
| 331 |
+
"OnnxStableDiffusionInpaintPipelineLegacy",
|
| 332 |
+
"OnnxStableDiffusionPipeline",
|
| 333 |
+
"OnnxStableDiffusionUpscalePipeline",
|
| 334 |
+
"StableDiffusionOnnxPipeline",
|
| 335 |
+
]
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
try:
|
| 339 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 340 |
+
raise OptionalDependencyNotAvailable()
|
| 341 |
+
except OptionalDependencyNotAvailable:
|
| 342 |
+
from .utils import dummy_torch_and_librosa_objects # noqa F403
|
| 343 |
+
|
| 344 |
+
_import_structure["utils.dummy_torch_and_librosa_objects"] = [
|
| 345 |
+
name for name in dir(dummy_torch_and_librosa_objects) if not name.startswith("_")
|
| 346 |
+
]
|
| 347 |
+
|
| 348 |
+
else:
|
| 349 |
+
_import_structure["pipelines"].extend(["AudioDiffusionPipeline", "Mel"])
|
| 350 |
+
|
| 351 |
+
try:
|
| 352 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 353 |
+
raise OptionalDependencyNotAvailable()
|
| 354 |
+
except OptionalDependencyNotAvailable:
|
| 355 |
+
from .utils import dummy_transformers_and_torch_and_note_seq_objects # noqa F403
|
| 356 |
+
|
| 357 |
+
_import_structure["utils.dummy_transformers_and_torch_and_note_seq_objects"] = [
|
| 358 |
+
name for name in dir(dummy_transformers_and_torch_and_note_seq_objects) if not name.startswith("_")
|
| 359 |
+
]
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
else:
|
| 363 |
+
_import_structure["pipelines"].extend(["SpectrogramDiffusionPipeline"])
|
| 364 |
+
|
| 365 |
+
try:
|
| 366 |
+
if not is_flax_available():
|
| 367 |
+
raise OptionalDependencyNotAvailable()
|
| 368 |
+
except OptionalDependencyNotAvailable:
|
| 369 |
+
from .utils import dummy_flax_objects # noqa F403
|
| 370 |
+
|
| 371 |
+
_import_structure["utils.dummy_flax_objects"] = [
|
| 372 |
+
name for name in dir(dummy_flax_objects) if not name.startswith("_")
|
| 373 |
+
]
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
else:
|
| 377 |
+
_import_structure["models.controlnet_flax"] = ["FlaxControlNetModel"]
|
| 378 |
+
_import_structure["models.modeling_flax_utils"] = ["FlaxModelMixin"]
|
| 379 |
+
_import_structure["models.unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
|
| 380 |
+
_import_structure["models.vae_flax"] = ["FlaxAutoencoderKL"]
|
| 381 |
+
_import_structure["pipelines"].extend(["FlaxDiffusionPipeline"])
|
| 382 |
+
_import_structure["schedulers"].extend(
|
| 383 |
+
[
|
| 384 |
+
"FlaxDDIMScheduler",
|
| 385 |
+
"FlaxDDPMScheduler",
|
| 386 |
+
"FlaxDPMSolverMultistepScheduler",
|
| 387 |
+
"FlaxEulerDiscreteScheduler",
|
| 388 |
+
"FlaxKarrasVeScheduler",
|
| 389 |
+
"FlaxLMSDiscreteScheduler",
|
| 390 |
+
"FlaxPNDMScheduler",
|
| 391 |
+
"FlaxSchedulerMixin",
|
| 392 |
+
"FlaxScoreSdeVeScheduler",
|
| 393 |
+
]
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
try:
|
| 398 |
+
if not (is_flax_available() and is_transformers_available()):
|
| 399 |
+
raise OptionalDependencyNotAvailable()
|
| 400 |
+
except OptionalDependencyNotAvailable:
|
| 401 |
+
from .utils import dummy_flax_and_transformers_objects # noqa F403
|
| 402 |
+
|
| 403 |
+
_import_structure["utils.dummy_flax_and_transformers_objects"] = [
|
| 404 |
+
name for name in dir(dummy_flax_and_transformers_objects) if not name.startswith("_")
|
| 405 |
+
]
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
else:
|
| 409 |
+
_import_structure["pipelines"].extend(
|
| 410 |
+
[
|
| 411 |
+
"FlaxStableDiffusionControlNetPipeline",
|
| 412 |
+
"FlaxStableDiffusionImg2ImgPipeline",
|
| 413 |
+
"FlaxStableDiffusionInpaintPipeline",
|
| 414 |
+
"FlaxStableDiffusionPipeline",
|
| 415 |
+
"FlaxStableDiffusionXLPipeline",
|
| 416 |
+
]
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
try:
|
| 420 |
+
if not (is_note_seq_available()):
|
| 421 |
+
raise OptionalDependencyNotAvailable()
|
| 422 |
+
except OptionalDependencyNotAvailable:
|
| 423 |
+
from .utils import dummy_note_seq_objects # noqa F403
|
| 424 |
+
|
| 425 |
+
_import_structure["utils.dummy_note_seq_objects"] = [
|
| 426 |
+
name for name in dir(dummy_note_seq_objects) if not name.startswith("_")
|
| 427 |
+
]
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
else:
|
| 431 |
+
_import_structure["pipelines"].extend(["MidiProcessor"])
|
| 432 |
+
|
| 433 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 434 |
+
from .configuration_utils import ConfigMixin
|
| 435 |
+
|
| 436 |
+
try:
|
| 437 |
+
if not is_onnx_available():
|
| 438 |
+
raise OptionalDependencyNotAvailable()
|
| 439 |
+
except OptionalDependencyNotAvailable:
|
| 440 |
+
from .utils.dummy_onnx_objects import * # noqa F403
|
| 441 |
+
else:
|
| 442 |
+
from .pipelines import OnnxRuntimeModel
|
| 443 |
+
|
| 444 |
+
try:
|
| 445 |
+
if not is_torch_available():
|
| 446 |
+
raise OptionalDependencyNotAvailable()
|
| 447 |
+
except OptionalDependencyNotAvailable:
|
| 448 |
+
from .utils.dummy_pt_objects import * # noqa F403
|
| 449 |
+
else:
|
| 450 |
+
from .models import (
|
| 451 |
+
AsymmetricAutoencoderKL,
|
| 452 |
+
AutoencoderKL,
|
| 453 |
+
AutoencoderKLTemporalDecoder,
|
| 454 |
+
AutoencoderTiny,
|
| 455 |
+
ConsistencyDecoderVAE,
|
| 456 |
+
ControlNetModel,
|
| 457 |
+
Kandinsky3UNet,
|
| 458 |
+
ModelMixin,
|
| 459 |
+
MotionAdapter,
|
| 460 |
+
MultiAdapter,
|
| 461 |
+
PriorTransformer,
|
| 462 |
+
T2IAdapter,
|
| 463 |
+
T5FilmDecoder,
|
| 464 |
+
Transformer2DModel,
|
| 465 |
+
UNet1DModel,
|
| 466 |
+
UNet2DConditionModel,
|
| 467 |
+
UNet2DModel,
|
| 468 |
+
UNet3DConditionModel,
|
| 469 |
+
UNetMotionModel,
|
| 470 |
+
UNetSpatioTemporalConditionModel,
|
| 471 |
+
VQModel,
|
| 472 |
+
)
|
| 473 |
+
from .optimization import (
|
| 474 |
+
get_constant_schedule,
|
| 475 |
+
get_constant_schedule_with_warmup,
|
| 476 |
+
get_cosine_schedule_with_warmup,
|
| 477 |
+
get_cosine_with_hard_restarts_schedule_with_warmup,
|
| 478 |
+
get_linear_schedule_with_warmup,
|
| 479 |
+
get_polynomial_decay_schedule_with_warmup,
|
| 480 |
+
get_scheduler,
|
| 481 |
+
)
|
| 482 |
+
from .pipelines import (
|
| 483 |
+
AudioPipelineOutput,
|
| 484 |
+
AutoPipelineForImage2Image,
|
| 485 |
+
AutoPipelineForInpainting,
|
| 486 |
+
AutoPipelineForText2Image,
|
| 487 |
+
BlipDiffusionControlNetPipeline,
|
| 488 |
+
BlipDiffusionPipeline,
|
| 489 |
+
CLIPImageProjection,
|
| 490 |
+
ConsistencyModelPipeline,
|
| 491 |
+
DanceDiffusionPipeline,
|
| 492 |
+
DDIMPipeline,
|
| 493 |
+
DDPMPipeline,
|
| 494 |
+
DiffusionPipeline,
|
| 495 |
+
DiTPipeline,
|
| 496 |
+
ImagePipelineOutput,
|
| 497 |
+
KarrasVePipeline,
|
| 498 |
+
LDMPipeline,
|
| 499 |
+
LDMSuperResolutionPipeline,
|
| 500 |
+
PNDMPipeline,
|
| 501 |
+
RePaintPipeline,
|
| 502 |
+
ScoreSdeVePipeline,
|
| 503 |
+
)
|
| 504 |
+
from .schedulers import (
|
| 505 |
+
CMStochasticIterativeScheduler,
|
| 506 |
+
DDIMInverseScheduler,
|
| 507 |
+
DDIMParallelScheduler,
|
| 508 |
+
DDIMScheduler,
|
| 509 |
+
DDPMParallelScheduler,
|
| 510 |
+
DDPMScheduler,
|
| 511 |
+
DDPMWuerstchenScheduler,
|
| 512 |
+
DEISMultistepScheduler,
|
| 513 |
+
DPMSolverMultistepInverseScheduler,
|
| 514 |
+
DPMSolverMultistepScheduler,
|
| 515 |
+
DPMSolverSinglestepScheduler,
|
| 516 |
+
EulerAncestralDiscreteScheduler,
|
| 517 |
+
EulerDiscreteScheduler,
|
| 518 |
+
HeunDiscreteScheduler,
|
| 519 |
+
IPNDMScheduler,
|
| 520 |
+
KarrasVeScheduler,
|
| 521 |
+
KDPM2AncestralDiscreteScheduler,
|
| 522 |
+
KDPM2DiscreteScheduler,
|
| 523 |
+
LCMScheduler,
|
| 524 |
+
PNDMScheduler,
|
| 525 |
+
RePaintScheduler,
|
| 526 |
+
SchedulerMixin,
|
| 527 |
+
ScoreSdeVeScheduler,
|
| 528 |
+
UnCLIPScheduler,
|
| 529 |
+
UniPCMultistepScheduler,
|
| 530 |
+
VQDiffusionScheduler,
|
| 531 |
+
)
|
| 532 |
+
from .training_utils import EMAModel
|
| 533 |
+
|
| 534 |
+
try:
|
| 535 |
+
if not (is_torch_available() and is_scipy_available()):
|
| 536 |
+
raise OptionalDependencyNotAvailable()
|
| 537 |
+
except OptionalDependencyNotAvailable:
|
| 538 |
+
from .utils.dummy_torch_and_scipy_objects import * # noqa F403
|
| 539 |
+
else:
|
| 540 |
+
from .schedulers import LMSDiscreteScheduler
|
| 541 |
+
|
| 542 |
+
try:
|
| 543 |
+
if not (is_torch_available() and is_torchsde_available()):
|
| 544 |
+
raise OptionalDependencyNotAvailable()
|
| 545 |
+
except OptionalDependencyNotAvailable:
|
| 546 |
+
from .utils.dummy_torch_and_torchsde_objects import * # noqa F403
|
| 547 |
+
else:
|
| 548 |
+
from .schedulers import DPMSolverSDEScheduler
|
| 549 |
+
|
| 550 |
+
try:
|
| 551 |
+
if not (is_torch_available() and is_transformers_available()):
|
| 552 |
+
raise OptionalDependencyNotAvailable()
|
| 553 |
+
except OptionalDependencyNotAvailable:
|
| 554 |
+
from .utils.dummy_torch_and_transformers_objects import * # noqa F403
|
| 555 |
+
else:
|
| 556 |
+
from .pipelines import (
|
| 557 |
+
AltDiffusionImg2ImgPipeline,
|
| 558 |
+
AltDiffusionPipeline,
|
| 559 |
+
AnimateDiffPipeline,
|
| 560 |
+
AudioLDM2Pipeline,
|
| 561 |
+
AudioLDM2ProjectionModel,
|
| 562 |
+
AudioLDM2UNet2DConditionModel,
|
| 563 |
+
AudioLDMPipeline,
|
| 564 |
+
CLIPImageProjection,
|
| 565 |
+
CycleDiffusionPipeline,
|
| 566 |
+
IFImg2ImgPipeline,
|
| 567 |
+
IFImg2ImgSuperResolutionPipeline,
|
| 568 |
+
IFInpaintingPipeline,
|
| 569 |
+
IFInpaintingSuperResolutionPipeline,
|
| 570 |
+
IFPipeline,
|
| 571 |
+
IFSuperResolutionPipeline,
|
| 572 |
+
ImageTextPipelineOutput,
|
| 573 |
+
Kandinsky3Img2ImgPipeline,
|
| 574 |
+
Kandinsky3Pipeline,
|
| 575 |
+
KandinskyCombinedPipeline,
|
| 576 |
+
KandinskyImg2ImgCombinedPipeline,
|
| 577 |
+
KandinskyImg2ImgPipeline,
|
| 578 |
+
KandinskyInpaintCombinedPipeline,
|
| 579 |
+
KandinskyInpaintPipeline,
|
| 580 |
+
KandinskyPipeline,
|
| 581 |
+
KandinskyPriorPipeline,
|
| 582 |
+
KandinskyV22CombinedPipeline,
|
| 583 |
+
KandinskyV22ControlnetImg2ImgPipeline,
|
| 584 |
+
KandinskyV22ControlnetPipeline,
|
| 585 |
+
KandinskyV22Img2ImgCombinedPipeline,
|
| 586 |
+
KandinskyV22Img2ImgPipeline,
|
| 587 |
+
KandinskyV22InpaintCombinedPipeline,
|
| 588 |
+
KandinskyV22InpaintPipeline,
|
| 589 |
+
KandinskyV22Pipeline,
|
| 590 |
+
KandinskyV22PriorEmb2EmbPipeline,
|
| 591 |
+
KandinskyV22PriorPipeline,
|
| 592 |
+
LatentConsistencyModelImg2ImgPipeline,
|
| 593 |
+
LatentConsistencyModelPipeline,
|
| 594 |
+
LDMTextToImagePipeline,
|
| 595 |
+
MusicLDMPipeline,
|
| 596 |
+
PaintByExamplePipeline,
|
| 597 |
+
PixArtAlphaPipeline,
|
| 598 |
+
SemanticStableDiffusionPipeline,
|
| 599 |
+
ShapEImg2ImgPipeline,
|
| 600 |
+
ShapEPipeline,
|
| 601 |
+
StableDiffusionAdapterPipeline,
|
| 602 |
+
StableDiffusionAttendAndExcitePipeline,
|
| 603 |
+
StableDiffusionControlNetImg2ImgPipeline,
|
| 604 |
+
StableDiffusionControlNetInpaintPipeline,
|
| 605 |
+
StableDiffusionControlNetPipeline,
|
| 606 |
+
StableDiffusionDepth2ImgPipeline,
|
| 607 |
+
StableDiffusionDiffEditPipeline,
|
| 608 |
+
StableDiffusionGLIGENPipeline,
|
| 609 |
+
StableDiffusionGLIGENTextImagePipeline,
|
| 610 |
+
StableDiffusionImageVariationPipeline,
|
| 611 |
+
StableDiffusionImg2ImgPipeline,
|
| 612 |
+
StableDiffusionInpaintPipeline,
|
| 613 |
+
StableDiffusionInpaintPipelineLegacy,
|
| 614 |
+
StableDiffusionInstructPix2PixPipeline,
|
| 615 |
+
StableDiffusionLatentUpscalePipeline,
|
| 616 |
+
StableDiffusionLDM3DPipeline,
|
| 617 |
+
StableDiffusionModelEditingPipeline,
|
| 618 |
+
StableDiffusionPanoramaPipeline,
|
| 619 |
+
StableDiffusionParadigmsPipeline,
|
| 620 |
+
StableDiffusionPipeline,
|
| 621 |
+
StableDiffusionPipelineSafe,
|
| 622 |
+
StableDiffusionPix2PixZeroPipeline,
|
| 623 |
+
StableDiffusionSAGPipeline,
|
| 624 |
+
StableDiffusionUpscalePipeline,
|
| 625 |
+
StableDiffusionXLAdapterPipeline,
|
| 626 |
+
StableDiffusionXLControlNetImg2ImgPipeline,
|
| 627 |
+
StableDiffusionXLControlNetInpaintPipeline,
|
| 628 |
+
StableDiffusionXLControlNetPipeline,
|
| 629 |
+
StableDiffusionXLImg2ImgPipeline,
|
| 630 |
+
StableDiffusionXLInpaintPipeline,
|
| 631 |
+
StableDiffusionXLInstructPix2PixPipeline,
|
| 632 |
+
StableDiffusionXLPipeline,
|
| 633 |
+
StableUnCLIPImg2ImgPipeline,
|
| 634 |
+
StableUnCLIPPipeline,
|
| 635 |
+
StableVideoDiffusionPipeline,
|
| 636 |
+
TextToVideoSDPipeline,
|
| 637 |
+
TextToVideoZeroPipeline,
|
| 638 |
+
TextToVideoZeroSDXLPipeline,
|
| 639 |
+
UnCLIPImageVariationPipeline,
|
| 640 |
+
UnCLIPPipeline,
|
| 641 |
+
UniDiffuserModel,
|
| 642 |
+
UniDiffuserPipeline,
|
| 643 |
+
UniDiffuserTextDecoder,
|
| 644 |
+
VersatileDiffusionDualGuidedPipeline,
|
| 645 |
+
VersatileDiffusionImageVariationPipeline,
|
| 646 |
+
VersatileDiffusionPipeline,
|
| 647 |
+
VersatileDiffusionTextToImagePipeline,
|
| 648 |
+
VideoToVideoSDPipeline,
|
| 649 |
+
VQDiffusionPipeline,
|
| 650 |
+
WuerstchenCombinedPipeline,
|
| 651 |
+
WuerstchenDecoderPipeline,
|
| 652 |
+
WuerstchenPriorPipeline,
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
try:
|
| 656 |
+
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
|
| 657 |
+
raise OptionalDependencyNotAvailable()
|
| 658 |
+
except OptionalDependencyNotAvailable:
|
| 659 |
+
from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403
|
| 660 |
+
else:
|
| 661 |
+
from .pipelines import StableDiffusionKDiffusionPipeline
|
| 662 |
+
|
| 663 |
+
try:
|
| 664 |
+
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
|
| 665 |
+
raise OptionalDependencyNotAvailable()
|
| 666 |
+
except OptionalDependencyNotAvailable:
|
| 667 |
+
from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403
|
| 668 |
+
else:
|
| 669 |
+
from .pipelines import (
|
| 670 |
+
OnnxStableDiffusionImg2ImgPipeline,
|
| 671 |
+
OnnxStableDiffusionInpaintPipeline,
|
| 672 |
+
OnnxStableDiffusionInpaintPipelineLegacy,
|
| 673 |
+
OnnxStableDiffusionPipeline,
|
| 674 |
+
OnnxStableDiffusionUpscalePipeline,
|
| 675 |
+
StableDiffusionOnnxPipeline,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
try:
|
| 679 |
+
if not (is_torch_available() and is_librosa_available()):
|
| 680 |
+
raise OptionalDependencyNotAvailable()
|
| 681 |
+
except OptionalDependencyNotAvailable:
|
| 682 |
+
from .utils.dummy_torch_and_librosa_objects import * # noqa F403
|
| 683 |
+
else:
|
| 684 |
+
from .pipelines import AudioDiffusionPipeline, Mel
|
| 685 |
+
|
| 686 |
+
try:
|
| 687 |
+
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
|
| 688 |
+
raise OptionalDependencyNotAvailable()
|
| 689 |
+
except OptionalDependencyNotAvailable:
|
| 690 |
+
from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
|
| 691 |
+
else:
|
| 692 |
+
from .pipelines import SpectrogramDiffusionPipeline
|
| 693 |
+
|
| 694 |
+
try:
|
| 695 |
+
if not is_flax_available():
|
| 696 |
+
raise OptionalDependencyNotAvailable()
|
| 697 |
+
except OptionalDependencyNotAvailable:
|
| 698 |
+
from .utils.dummy_flax_objects import * # noqa F403
|
| 699 |
+
else:
|
| 700 |
+
from .models.controlnet_flax import FlaxControlNetModel
|
| 701 |
+
from .models.modeling_flax_utils import FlaxModelMixin
|
| 702 |
+
from .models.unet_2d_condition_flax import FlaxUNet2DConditionModel
|
| 703 |
+
from .models.vae_flax import FlaxAutoencoderKL
|
| 704 |
+
from .pipelines import FlaxDiffusionPipeline
|
| 705 |
+
from .schedulers import (
|
| 706 |
+
FlaxDDIMScheduler,
|
| 707 |
+
FlaxDDPMScheduler,
|
| 708 |
+
FlaxDPMSolverMultistepScheduler,
|
| 709 |
+
FlaxEulerDiscreteScheduler,
|
| 710 |
+
FlaxKarrasVeScheduler,
|
| 711 |
+
FlaxLMSDiscreteScheduler,
|
| 712 |
+
FlaxPNDMScheduler,
|
| 713 |
+
FlaxSchedulerMixin,
|
| 714 |
+
FlaxScoreSdeVeScheduler,
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
try:
|
| 718 |
+
if not (is_flax_available() and is_transformers_available()):
|
| 719 |
+
raise OptionalDependencyNotAvailable()
|
| 720 |
+
except OptionalDependencyNotAvailable:
|
| 721 |
+
from .utils.dummy_flax_and_transformers_objects import * # noqa F403
|
| 722 |
+
else:
|
| 723 |
+
from .pipelines import (
|
| 724 |
+
FlaxStableDiffusionControlNetPipeline,
|
| 725 |
+
FlaxStableDiffusionImg2ImgPipeline,
|
| 726 |
+
FlaxStableDiffusionInpaintPipeline,
|
| 727 |
+
FlaxStableDiffusionPipeline,
|
| 728 |
+
FlaxStableDiffusionXLPipeline,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
try:
|
| 732 |
+
if not (is_note_seq_available()):
|
| 733 |
+
raise OptionalDependencyNotAvailable()
|
| 734 |
+
except OptionalDependencyNotAvailable:
|
| 735 |
+
from .utils.dummy_note_seq_objects import * # noqa F403
|
| 736 |
+
else:
|
| 737 |
+
from .pipelines import MidiProcessor
|
| 738 |
+
|
| 739 |
+
else:
|
| 740 |
+
import sys
|
| 741 |
+
|
| 742 |
+
sys.modules[__name__] = _LazyModule(
|
| 743 |
+
__name__,
|
| 744 |
+
globals()["__file__"],
|
| 745 |
+
_import_structure,
|
| 746 |
+
module_spec=__spec__,
|
| 747 |
+
extra_objects={"__version__": __version__},
|
| 748 |
+
)
|
diffusers/commands/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from abc import ABC, abstractmethod
|
| 16 |
+
from argparse import ArgumentParser
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class BaseDiffusersCLICommand(ABC):
|
| 20 |
+
@staticmethod
|
| 21 |
+
@abstractmethod
|
| 22 |
+
def register_subcommand(parser: ArgumentParser):
|
| 23 |
+
raise NotImplementedError()
|
| 24 |
+
|
| 25 |
+
@abstractmethod
|
| 26 |
+
def run(self):
|
| 27 |
+
raise NotImplementedError()
|
diffusers/commands/diffusers_cli.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from argparse import ArgumentParser
|
| 17 |
+
|
| 18 |
+
from .env import EnvironmentCommand
|
| 19 |
+
from .fp16_safetensors import FP16SafetensorsCommand
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
parser = ArgumentParser("Diffusers CLI tool", usage="diffusers-cli <command> [<args>]")
|
| 24 |
+
commands_parser = parser.add_subparsers(help="diffusers-cli command helpers")
|
| 25 |
+
|
| 26 |
+
# Register commands
|
| 27 |
+
EnvironmentCommand.register_subcommand(commands_parser)
|
| 28 |
+
FP16SafetensorsCommand.register_subcommand(commands_parser)
|
| 29 |
+
|
| 30 |
+
# Let's go
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
|
| 33 |
+
if not hasattr(args, "func"):
|
| 34 |
+
parser.print_help()
|
| 35 |
+
exit(1)
|
| 36 |
+
|
| 37 |
+
# Run
|
| 38 |
+
service = args.func(args)
|
| 39 |
+
service.run()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
main()
|
diffusers/commands/env.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import platform
|
| 16 |
+
from argparse import ArgumentParser
|
| 17 |
+
|
| 18 |
+
import huggingface_hub
|
| 19 |
+
|
| 20 |
+
from .. import __version__ as version
|
| 21 |
+
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
|
| 22 |
+
from . import BaseDiffusersCLICommand
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def info_command_factory(_):
|
| 26 |
+
return EnvironmentCommand()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class EnvironmentCommand(BaseDiffusersCLICommand):
|
| 30 |
+
@staticmethod
|
| 31 |
+
def register_subcommand(parser: ArgumentParser):
|
| 32 |
+
download_parser = parser.add_parser("env")
|
| 33 |
+
download_parser.set_defaults(func=info_command_factory)
|
| 34 |
+
|
| 35 |
+
def run(self):
|
| 36 |
+
hub_version = huggingface_hub.__version__
|
| 37 |
+
|
| 38 |
+
pt_version = "not installed"
|
| 39 |
+
pt_cuda_available = "NA"
|
| 40 |
+
if is_torch_available():
|
| 41 |
+
import torch
|
| 42 |
+
|
| 43 |
+
pt_version = torch.__version__
|
| 44 |
+
pt_cuda_available = torch.cuda.is_available()
|
| 45 |
+
|
| 46 |
+
transformers_version = "not installed"
|
| 47 |
+
if is_transformers_available():
|
| 48 |
+
import transformers
|
| 49 |
+
|
| 50 |
+
transformers_version = transformers.__version__
|
| 51 |
+
|
| 52 |
+
accelerate_version = "not installed"
|
| 53 |
+
if is_accelerate_available():
|
| 54 |
+
import accelerate
|
| 55 |
+
|
| 56 |
+
accelerate_version = accelerate.__version__
|
| 57 |
+
|
| 58 |
+
xformers_version = "not installed"
|
| 59 |
+
if is_xformers_available():
|
| 60 |
+
import xformers
|
| 61 |
+
|
| 62 |
+
xformers_version = xformers.__version__
|
| 63 |
+
|
| 64 |
+
info = {
|
| 65 |
+
"`diffusers` version": version,
|
| 66 |
+
"Platform": platform.platform(),
|
| 67 |
+
"Python version": platform.python_version(),
|
| 68 |
+
"PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
|
| 69 |
+
"Huggingface_hub version": hub_version,
|
| 70 |
+
"Transformers version": transformers_version,
|
| 71 |
+
"Accelerate version": accelerate_version,
|
| 72 |
+
"xFormers version": xformers_version,
|
| 73 |
+
"Using GPU in script?": "<fill in>",
|
| 74 |
+
"Using distributed or parallel set-up in script?": "<fill in>",
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n")
|
| 78 |
+
print(self.format_dict(info))
|
| 79 |
+
|
| 80 |
+
return info
|
| 81 |
+
|
| 82 |
+
@staticmethod
|
| 83 |
+
def format_dict(d):
|
| 84 |
+
return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"
|
diffusers/commands/fp16_safetensors.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
Usage example:
|
| 17 |
+
diffusers-cli fp16_safetensors --ckpt_id=openai/shap-e --fp16 --use_safetensors
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import glob
|
| 21 |
+
import json
|
| 22 |
+
from argparse import ArgumentParser, Namespace
|
| 23 |
+
from importlib import import_module
|
| 24 |
+
|
| 25 |
+
import huggingface_hub
|
| 26 |
+
import torch
|
| 27 |
+
from huggingface_hub import hf_hub_download
|
| 28 |
+
from packaging import version
|
| 29 |
+
|
| 30 |
+
from ..utils import logging
|
| 31 |
+
from . import BaseDiffusersCLICommand
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def conversion_command_factory(args: Namespace):
|
| 35 |
+
return FP16SafetensorsCommand(
|
| 36 |
+
args.ckpt_id,
|
| 37 |
+
args.fp16,
|
| 38 |
+
args.use_safetensors,
|
| 39 |
+
args.use_auth_token,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class FP16SafetensorsCommand(BaseDiffusersCLICommand):
|
| 44 |
+
@staticmethod
|
| 45 |
+
def register_subcommand(parser: ArgumentParser):
|
| 46 |
+
conversion_parser = parser.add_parser("fp16_safetensors")
|
| 47 |
+
conversion_parser.add_argument(
|
| 48 |
+
"--ckpt_id",
|
| 49 |
+
type=str,
|
| 50 |
+
help="Repo id of the checkpoints on which to run the conversion. Example: 'openai/shap-e'.",
|
| 51 |
+
)
|
| 52 |
+
conversion_parser.add_argument(
|
| 53 |
+
"--fp16", action="store_true", help="If serializing the variables in FP16 precision."
|
| 54 |
+
)
|
| 55 |
+
conversion_parser.add_argument(
|
| 56 |
+
"--use_safetensors", action="store_true", help="If serializing in the safetensors format."
|
| 57 |
+
)
|
| 58 |
+
conversion_parser.add_argument(
|
| 59 |
+
"--use_auth_token",
|
| 60 |
+
action="store_true",
|
| 61 |
+
help="When working with checkpoints having private visibility. When used `huggingface-cli login` needs to be run beforehand.",
|
| 62 |
+
)
|
| 63 |
+
conversion_parser.set_defaults(func=conversion_command_factory)
|
| 64 |
+
|
| 65 |
+
def __init__(self, ckpt_id: str, fp16: bool, use_safetensors: bool, use_auth_token: bool):
|
| 66 |
+
self.logger = logging.get_logger("diffusers-cli/fp16_safetensors")
|
| 67 |
+
self.ckpt_id = ckpt_id
|
| 68 |
+
self.local_ckpt_dir = f"/tmp/{ckpt_id}"
|
| 69 |
+
self.fp16 = fp16
|
| 70 |
+
|
| 71 |
+
self.use_safetensors = use_safetensors
|
| 72 |
+
|
| 73 |
+
if not self.use_safetensors and not self.fp16:
|
| 74 |
+
raise NotImplementedError(
|
| 75 |
+
"When `use_safetensors` and `fp16` both are False, then this command is of no use."
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
self.use_auth_token = use_auth_token
|
| 79 |
+
|
| 80 |
+
def run(self):
|
| 81 |
+
if version.parse(huggingface_hub.__version__) < version.parse("0.9.0"):
|
| 82 |
+
raise ImportError(
|
| 83 |
+
"The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub"
|
| 84 |
+
" installation."
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
from huggingface_hub import create_commit
|
| 88 |
+
from huggingface_hub._commit_api import CommitOperationAdd
|
| 89 |
+
|
| 90 |
+
model_index = hf_hub_download(repo_id=self.ckpt_id, filename="model_index.json", token=self.use_auth_token)
|
| 91 |
+
with open(model_index, "r") as f:
|
| 92 |
+
pipeline_class_name = json.load(f)["_class_name"]
|
| 93 |
+
pipeline_class = getattr(import_module("diffusers"), pipeline_class_name)
|
| 94 |
+
self.logger.info(f"Pipeline class imported: {pipeline_class_name}.")
|
| 95 |
+
|
| 96 |
+
# Load the appropriate pipeline. We could have use `DiffusionPipeline`
|
| 97 |
+
# here, but just to avoid any rough edge cases.
|
| 98 |
+
pipeline = pipeline_class.from_pretrained(
|
| 99 |
+
self.ckpt_id, torch_dtype=torch.float16 if self.fp16 else torch.float32, use_auth_token=self.use_auth_token
|
| 100 |
+
)
|
| 101 |
+
pipeline.save_pretrained(
|
| 102 |
+
self.local_ckpt_dir,
|
| 103 |
+
safe_serialization=True if self.use_safetensors else False,
|
| 104 |
+
variant="fp16" if self.fp16 else None,
|
| 105 |
+
)
|
| 106 |
+
self.logger.info(f"Pipeline locally saved to {self.local_ckpt_dir}.")
|
| 107 |
+
|
| 108 |
+
# Fetch all the paths.
|
| 109 |
+
if self.fp16:
|
| 110 |
+
modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.fp16.*")
|
| 111 |
+
elif self.use_safetensors:
|
| 112 |
+
modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.safetensors")
|
| 113 |
+
|
| 114 |
+
# Prepare for the PR.
|
| 115 |
+
commit_message = f"Serialize variables with FP16: {self.fp16} and safetensors: {self.use_safetensors}."
|
| 116 |
+
operations = []
|
| 117 |
+
for path in modified_paths:
|
| 118 |
+
operations.append(CommitOperationAdd(path_in_repo="/".join(path.split("/")[4:]), path_or_fileobj=path))
|
| 119 |
+
|
| 120 |
+
# Open the PR.
|
| 121 |
+
commit_description = (
|
| 122 |
+
"Variables converted by the [`diffusers`' `fp16_safetensors`"
|
| 123 |
+
" CLI](https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/fp16_safetensors.py)."
|
| 124 |
+
)
|
| 125 |
+
hub_pr_url = create_commit(
|
| 126 |
+
repo_id=self.ckpt_id,
|
| 127 |
+
operations=operations,
|
| 128 |
+
commit_message=commit_message,
|
| 129 |
+
commit_description=commit_description,
|
| 130 |
+
repo_type="model",
|
| 131 |
+
create_pr=True,
|
| 132 |
+
).pr_url
|
| 133 |
+
self.logger.info(f"PR created here: {hub_pr_url}.")
|
diffusers/configuration_utils.py
ADDED
|
@@ -0,0 +1,695 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team.
|
| 3 |
+
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
""" ConfigMixin base class and utilities."""
|
| 17 |
+
import dataclasses
|
| 18 |
+
import functools
|
| 19 |
+
import importlib
|
| 20 |
+
import inspect
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
from collections import OrderedDict
|
| 25 |
+
from pathlib import PosixPath
|
| 26 |
+
from typing import Any, Dict, Tuple, Union
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
from huggingface_hub import create_repo, hf_hub_download
|
| 30 |
+
from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
|
| 31 |
+
from requests import HTTPError
|
| 32 |
+
|
| 33 |
+
from . import __version__
|
| 34 |
+
from .utils import (
|
| 35 |
+
DIFFUSERS_CACHE,
|
| 36 |
+
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
|
| 37 |
+
DummyObject,
|
| 38 |
+
deprecate,
|
| 39 |
+
extract_commit_hash,
|
| 40 |
+
http_user_agent,
|
| 41 |
+
logging,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
_re_configuration_file = re.compile(r"config\.(.*)\.json")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class FrozenDict(OrderedDict):
|
| 51 |
+
def __init__(self, *args, **kwargs):
|
| 52 |
+
super().__init__(*args, **kwargs)
|
| 53 |
+
|
| 54 |
+
for key, value in self.items():
|
| 55 |
+
setattr(self, key, value)
|
| 56 |
+
|
| 57 |
+
self.__frozen = True
|
| 58 |
+
|
| 59 |
+
def __delitem__(self, *args, **kwargs):
|
| 60 |
+
raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
|
| 61 |
+
|
| 62 |
+
def setdefault(self, *args, **kwargs):
|
| 63 |
+
raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
|
| 64 |
+
|
| 65 |
+
def pop(self, *args, **kwargs):
|
| 66 |
+
raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
|
| 67 |
+
|
| 68 |
+
def update(self, *args, **kwargs):
|
| 69 |
+
raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
|
| 70 |
+
|
| 71 |
+
def __setattr__(self, name, value):
|
| 72 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
| 73 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
| 74 |
+
super().__setattr__(name, value)
|
| 75 |
+
|
| 76 |
+
def __setitem__(self, name, value):
|
| 77 |
+
if hasattr(self, "__frozen") and self.__frozen:
|
| 78 |
+
raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
|
| 79 |
+
super().__setitem__(name, value)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ConfigMixin:
|
| 83 |
+
r"""
|
| 84 |
+
Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
|
| 85 |
+
provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
|
| 86 |
+
saving classes that inherit from [`ConfigMixin`].
|
| 87 |
+
|
| 88 |
+
Class attributes:
|
| 89 |
+
- **config_name** (`str`) -- A filename under which the config should stored when calling
|
| 90 |
+
[`~ConfigMixin.save_config`] (should be overridden by parent class).
|
| 91 |
+
- **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
|
| 92 |
+
overridden by subclass).
|
| 93 |
+
- **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
|
| 94 |
+
- **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
|
| 95 |
+
should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
|
| 96 |
+
subclass).
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
config_name = None
|
| 100 |
+
ignore_for_config = []
|
| 101 |
+
has_compatibles = False
|
| 102 |
+
|
| 103 |
+
_deprecated_kwargs = []
|
| 104 |
+
|
| 105 |
+
def register_to_config(self, **kwargs):
|
| 106 |
+
if self.config_name is None:
|
| 107 |
+
raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
|
| 108 |
+
# Special case for `kwargs` used in deprecation warning added to schedulers
|
| 109 |
+
# TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,
|
| 110 |
+
# or solve in a more general way.
|
| 111 |
+
kwargs.pop("kwargs", None)
|
| 112 |
+
|
| 113 |
+
if not hasattr(self, "_internal_dict"):
|
| 114 |
+
internal_dict = kwargs
|
| 115 |
+
else:
|
| 116 |
+
previous_dict = dict(self._internal_dict)
|
| 117 |
+
internal_dict = {**self._internal_dict, **kwargs}
|
| 118 |
+
logger.debug(f"Updating config from {previous_dict} to {internal_dict}")
|
| 119 |
+
|
| 120 |
+
self._internal_dict = FrozenDict(internal_dict)
|
| 121 |
+
|
| 122 |
+
def __getattr__(self, name: str) -> Any:
|
| 123 |
+
"""The only reason we overwrite `getattr` here is to gracefully deprecate accessing
|
| 124 |
+
config attributes directly. See https://github.com/huggingface/diffusers/pull/3129
|
| 125 |
+
|
| 126 |
+
Tihs funtion is mostly copied from PyTorch's __getattr__ overwrite:
|
| 127 |
+
https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
|
| 131 |
+
is_attribute = name in self.__dict__
|
| 132 |
+
|
| 133 |
+
if is_in_config and not is_attribute:
|
| 134 |
+
deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'."
|
| 135 |
+
deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False)
|
| 136 |
+
return self._internal_dict[name]
|
| 137 |
+
|
| 138 |
+
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
|
| 139 |
+
|
| 140 |
+
def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
|
| 141 |
+
"""
|
| 142 |
+
Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
|
| 143 |
+
[`~ConfigMixin.from_config`] class method.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
save_directory (`str` or `os.PathLike`):
|
| 147 |
+
Directory where the configuration JSON file is saved (will be created if it does not exist).
|
| 148 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 149 |
+
Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
|
| 150 |
+
repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
|
| 151 |
+
namespace).
|
| 152 |
+
kwargs (`Dict[str, Any]`, *optional*):
|
| 153 |
+
Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
|
| 154 |
+
"""
|
| 155 |
+
if os.path.isfile(save_directory):
|
| 156 |
+
raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
|
| 157 |
+
|
| 158 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 159 |
+
|
| 160 |
+
# If we save using the predefined names, we can load using `from_config`
|
| 161 |
+
output_config_file = os.path.join(save_directory, self.config_name)
|
| 162 |
+
|
| 163 |
+
self.to_json_file(output_config_file)
|
| 164 |
+
logger.info(f"Configuration saved in {output_config_file}")
|
| 165 |
+
|
| 166 |
+
if push_to_hub:
|
| 167 |
+
commit_message = kwargs.pop("commit_message", None)
|
| 168 |
+
private = kwargs.pop("private", False)
|
| 169 |
+
create_pr = kwargs.pop("create_pr", False)
|
| 170 |
+
token = kwargs.pop("token", None)
|
| 171 |
+
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
|
| 172 |
+
repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
|
| 173 |
+
|
| 174 |
+
self._upload_folder(
|
| 175 |
+
save_directory,
|
| 176 |
+
repo_id,
|
| 177 |
+
token=token,
|
| 178 |
+
commit_message=commit_message,
|
| 179 |
+
create_pr=create_pr,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
@classmethod
|
| 183 |
+
def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
|
| 184 |
+
r"""
|
| 185 |
+
Instantiate a Python class from a config dictionary.
|
| 186 |
+
|
| 187 |
+
Parameters:
|
| 188 |
+
config (`Dict[str, Any]`):
|
| 189 |
+
A config dictionary from which the Python class is instantiated. Make sure to only load configuration
|
| 190 |
+
files of compatible classes.
|
| 191 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
|
| 192 |
+
Whether kwargs that are not consumed by the Python class should be returned or not.
|
| 193 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 194 |
+
Can be used to update the configuration object (after it is loaded) and initiate the Python class.
|
| 195 |
+
`**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
|
| 196 |
+
overwrite the same named arguments in `config`.
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
[`ModelMixin`] or [`SchedulerMixin`]:
|
| 200 |
+
A model or scheduler object instantiated from a config dictionary.
|
| 201 |
+
|
| 202 |
+
Examples:
|
| 203 |
+
|
| 204 |
+
```python
|
| 205 |
+
>>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
|
| 206 |
+
|
| 207 |
+
>>> # Download scheduler from huggingface.co and cache.
|
| 208 |
+
>>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")
|
| 209 |
+
|
| 210 |
+
>>> # Instantiate DDIM scheduler class with same config as DDPM
|
| 211 |
+
>>> scheduler = DDIMScheduler.from_config(scheduler.config)
|
| 212 |
+
|
| 213 |
+
>>> # Instantiate PNDM scheduler class with same config as DDPM
|
| 214 |
+
>>> scheduler = PNDMScheduler.from_config(scheduler.config)
|
| 215 |
+
```
|
| 216 |
+
"""
|
| 217 |
+
# <===== TO BE REMOVED WITH DEPRECATION
|
| 218 |
+
# TODO(Patrick) - make sure to remove the following lines when config=="model_path" is deprecated
|
| 219 |
+
if "pretrained_model_name_or_path" in kwargs:
|
| 220 |
+
config = kwargs.pop("pretrained_model_name_or_path")
|
| 221 |
+
|
| 222 |
+
if config is None:
|
| 223 |
+
raise ValueError("Please make sure to provide a config as the first positional argument.")
|
| 224 |
+
# ======>
|
| 225 |
+
|
| 226 |
+
if not isinstance(config, dict):
|
| 227 |
+
deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
|
| 228 |
+
if "Scheduler" in cls.__name__:
|
| 229 |
+
deprecation_message += (
|
| 230 |
+
f"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead."
|
| 231 |
+
" Otherwise, please make sure to pass a configuration dictionary instead. This functionality will"
|
| 232 |
+
" be removed in v1.0.0."
|
| 233 |
+
)
|
| 234 |
+
elif "Model" in cls.__name__:
|
| 235 |
+
deprecation_message += (
|
| 236 |
+
f"If you were trying to load a model, please use {cls}.load_config(...) followed by"
|
| 237 |
+
f" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary"
|
| 238 |
+
" instead. This functionality will be removed in v1.0.0."
|
| 239 |
+
)
|
| 240 |
+
deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
|
| 241 |
+
config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)
|
| 242 |
+
|
| 243 |
+
init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
|
| 244 |
+
|
| 245 |
+
# Allow dtype to be specified on initialization
|
| 246 |
+
if "dtype" in unused_kwargs:
|
| 247 |
+
init_dict["dtype"] = unused_kwargs.pop("dtype")
|
| 248 |
+
|
| 249 |
+
# add possible deprecated kwargs
|
| 250 |
+
for deprecated_kwarg in cls._deprecated_kwargs:
|
| 251 |
+
if deprecated_kwarg in unused_kwargs:
|
| 252 |
+
init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)
|
| 253 |
+
|
| 254 |
+
# Return model and optionally state and/or unused_kwargs
|
| 255 |
+
model = cls(**init_dict)
|
| 256 |
+
|
| 257 |
+
# make sure to also save config parameters that might be used for compatible classes
|
| 258 |
+
model.register_to_config(**hidden_dict)
|
| 259 |
+
|
| 260 |
+
# add hidden kwargs of compatible classes to unused_kwargs
|
| 261 |
+
unused_kwargs = {**unused_kwargs, **hidden_dict}
|
| 262 |
+
|
| 263 |
+
if return_unused_kwargs:
|
| 264 |
+
return (model, unused_kwargs)
|
| 265 |
+
else:
|
| 266 |
+
return model
|
| 267 |
+
|
| 268 |
+
@classmethod
|
| 269 |
+
def get_config_dict(cls, *args, **kwargs):
|
| 270 |
+
deprecation_message = (
|
| 271 |
+
f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be"
|
| 272 |
+
" removed in version v1.0.0"
|
| 273 |
+
)
|
| 274 |
+
deprecate("get_config_dict", "1.0.0", deprecation_message, standard_warn=False)
|
| 275 |
+
return cls.load_config(*args, **kwargs)
|
| 276 |
+
|
| 277 |
+
@classmethod
|
| 278 |
+
def load_config(
|
| 279 |
+
cls,
|
| 280 |
+
pretrained_model_name_or_path: Union[str, os.PathLike],
|
| 281 |
+
return_unused_kwargs=False,
|
| 282 |
+
return_commit_hash=False,
|
| 283 |
+
**kwargs,
|
| 284 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
| 285 |
+
r"""
|
| 286 |
+
Load a model or scheduler configuration.
|
| 287 |
+
|
| 288 |
+
Parameters:
|
| 289 |
+
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
|
| 290 |
+
Can be either:
|
| 291 |
+
|
| 292 |
+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
| 293 |
+
the Hub.
|
| 294 |
+
- A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
|
| 295 |
+
[`~ConfigMixin.save_config`].
|
| 296 |
+
|
| 297 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 298 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 299 |
+
is not used.
|
| 300 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 301 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 302 |
+
cached versions if they exist.
|
| 303 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 304 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 305 |
+
incompletely downloaded files are deleted.
|
| 306 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 307 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 308 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 309 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 310 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 311 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 312 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 313 |
+
won't be downloaded from the Hub.
|
| 314 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 315 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 316 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 317 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 318 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 319 |
+
allowed by Git.
|
| 320 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 321 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
| 322 |
+
return_unused_kwargs (`bool`, *optional*, defaults to `False):
|
| 323 |
+
Whether unused keyword arguments of the config are returned.
|
| 324 |
+
return_commit_hash (`bool`, *optional*, defaults to `False):
|
| 325 |
+
Whether the `commit_hash` of the loaded configuration are returned.
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
`dict`:
|
| 329 |
+
A dictionary of all the parameters stored in a JSON configuration file.
|
| 330 |
+
|
| 331 |
+
"""
|
| 332 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 333 |
+
force_download = kwargs.pop("force_download", False)
|
| 334 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 335 |
+
proxies = kwargs.pop("proxies", None)
|
| 336 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 337 |
+
local_files_only = kwargs.pop("local_files_only", False)
|
| 338 |
+
revision = kwargs.pop("revision", None)
|
| 339 |
+
_ = kwargs.pop("mirror", None)
|
| 340 |
+
subfolder = kwargs.pop("subfolder", None)
|
| 341 |
+
user_agent = kwargs.pop("user_agent", {})
|
| 342 |
+
|
| 343 |
+
user_agent = {**user_agent, "file_type": "config"}
|
| 344 |
+
user_agent = http_user_agent(user_agent)
|
| 345 |
+
|
| 346 |
+
pretrained_model_name_or_path = str(pretrained_model_name_or_path)
|
| 347 |
+
|
| 348 |
+
if cls.config_name is None:
|
| 349 |
+
raise ValueError(
|
| 350 |
+
"`self.config_name` is not defined. Note that one should not load a config from "
|
| 351 |
+
"`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
if os.path.isfile(pretrained_model_name_or_path):
|
| 355 |
+
config_file = pretrained_model_name_or_path
|
| 356 |
+
elif os.path.isdir(pretrained_model_name_or_path):
|
| 357 |
+
if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
|
| 358 |
+
# Load from a PyTorch checkpoint
|
| 359 |
+
config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
|
| 360 |
+
elif subfolder is not None and os.path.isfile(
|
| 361 |
+
os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
| 362 |
+
):
|
| 363 |
+
config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
|
| 364 |
+
else:
|
| 365 |
+
raise EnvironmentError(
|
| 366 |
+
f"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}."
|
| 367 |
+
)
|
| 368 |
+
else:
|
| 369 |
+
try:
|
| 370 |
+
# Load from URL or cache if already cached
|
| 371 |
+
config_file = hf_hub_download(
|
| 372 |
+
pretrained_model_name_or_path,
|
| 373 |
+
filename=cls.config_name,
|
| 374 |
+
cache_dir=cache_dir,
|
| 375 |
+
force_download=force_download,
|
| 376 |
+
proxies=proxies,
|
| 377 |
+
resume_download=resume_download,
|
| 378 |
+
local_files_only=local_files_only,
|
| 379 |
+
use_auth_token=use_auth_token,
|
| 380 |
+
user_agent=user_agent,
|
| 381 |
+
subfolder=subfolder,
|
| 382 |
+
revision=revision,
|
| 383 |
+
)
|
| 384 |
+
except RepositoryNotFoundError:
|
| 385 |
+
raise EnvironmentError(
|
| 386 |
+
f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
|
| 387 |
+
" listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
|
| 388 |
+
" token having permission to this repo with `use_auth_token` or log in with `huggingface-cli"
|
| 389 |
+
" login`."
|
| 390 |
+
)
|
| 391 |
+
except RevisionNotFoundError:
|
| 392 |
+
raise EnvironmentError(
|
| 393 |
+
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
|
| 394 |
+
" this model name. Check the model page at"
|
| 395 |
+
f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
|
| 396 |
+
)
|
| 397 |
+
except EntryNotFoundError:
|
| 398 |
+
raise EnvironmentError(
|
| 399 |
+
f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
|
| 400 |
+
)
|
| 401 |
+
except HTTPError as err:
|
| 402 |
+
raise EnvironmentError(
|
| 403 |
+
"There was a specific connection error when trying to load"
|
| 404 |
+
f" {pretrained_model_name_or_path}:\n{err}"
|
| 405 |
+
)
|
| 406 |
+
except ValueError:
|
| 407 |
+
raise EnvironmentError(
|
| 408 |
+
f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
|
| 409 |
+
f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
|
| 410 |
+
f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
|
| 411 |
+
" run the library in offline mode at"
|
| 412 |
+
" 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
|
| 413 |
+
)
|
| 414 |
+
except EnvironmentError:
|
| 415 |
+
raise EnvironmentError(
|
| 416 |
+
f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
|
| 417 |
+
"'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
|
| 418 |
+
f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
|
| 419 |
+
f"containing a {cls.config_name} file"
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
try:
|
| 423 |
+
# Load config dict
|
| 424 |
+
config_dict = cls._dict_from_json_file(config_file)
|
| 425 |
+
|
| 426 |
+
commit_hash = extract_commit_hash(config_file)
|
| 427 |
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
| 428 |
+
raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
|
| 429 |
+
|
| 430 |
+
if not (return_unused_kwargs or return_commit_hash):
|
| 431 |
+
return config_dict
|
| 432 |
+
|
| 433 |
+
outputs = (config_dict,)
|
| 434 |
+
|
| 435 |
+
if return_unused_kwargs:
|
| 436 |
+
outputs += (kwargs,)
|
| 437 |
+
|
| 438 |
+
if return_commit_hash:
|
| 439 |
+
outputs += (commit_hash,)
|
| 440 |
+
|
| 441 |
+
return outputs
|
| 442 |
+
|
| 443 |
+
@staticmethod
|
| 444 |
+
def _get_init_keys(cls):
|
| 445 |
+
return set(dict(inspect.signature(cls.__init__).parameters).keys())
|
| 446 |
+
|
| 447 |
+
@classmethod
|
| 448 |
+
def extract_init_dict(cls, config_dict, **kwargs):
|
| 449 |
+
# Skip keys that were not present in the original config, so default __init__ values were used
|
| 450 |
+
used_defaults = config_dict.get("_use_default_values", [])
|
| 451 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != "_use_default_values"}
|
| 452 |
+
|
| 453 |
+
# 0. Copy origin config dict
|
| 454 |
+
original_dict = dict(config_dict.items())
|
| 455 |
+
|
| 456 |
+
# 1. Retrieve expected config attributes from __init__ signature
|
| 457 |
+
expected_keys = cls._get_init_keys(cls)
|
| 458 |
+
expected_keys.remove("self")
|
| 459 |
+
# remove general kwargs if present in dict
|
| 460 |
+
if "kwargs" in expected_keys:
|
| 461 |
+
expected_keys.remove("kwargs")
|
| 462 |
+
# remove flax internal keys
|
| 463 |
+
if hasattr(cls, "_flax_internal_args"):
|
| 464 |
+
for arg in cls._flax_internal_args:
|
| 465 |
+
expected_keys.remove(arg)
|
| 466 |
+
|
| 467 |
+
# 2. Remove attributes that cannot be expected from expected config attributes
|
| 468 |
+
# remove keys to be ignored
|
| 469 |
+
if len(cls.ignore_for_config) > 0:
|
| 470 |
+
expected_keys = expected_keys - set(cls.ignore_for_config)
|
| 471 |
+
|
| 472 |
+
# load diffusers library to import compatible and original scheduler
|
| 473 |
+
diffusers_library = importlib.import_module(__name__.split(".")[0])
|
| 474 |
+
|
| 475 |
+
if cls.has_compatibles:
|
| 476 |
+
compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
|
| 477 |
+
else:
|
| 478 |
+
compatible_classes = []
|
| 479 |
+
|
| 480 |
+
expected_keys_comp_cls = set()
|
| 481 |
+
for c in compatible_classes:
|
| 482 |
+
expected_keys_c = cls._get_init_keys(c)
|
| 483 |
+
expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)
|
| 484 |
+
expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)
|
| 485 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}
|
| 486 |
+
|
| 487 |
+
# remove attributes from orig class that cannot be expected
|
| 488 |
+
orig_cls_name = config_dict.pop("_class_name", cls.__name__)
|
| 489 |
+
if (
|
| 490 |
+
isinstance(orig_cls_name, str)
|
| 491 |
+
and orig_cls_name != cls.__name__
|
| 492 |
+
and hasattr(diffusers_library, orig_cls_name)
|
| 493 |
+
):
|
| 494 |
+
orig_cls = getattr(diffusers_library, orig_cls_name)
|
| 495 |
+
unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys
|
| 496 |
+
config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}
|
| 497 |
+
elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):
|
| 498 |
+
raise ValueError(
|
| 499 |
+
"Make sure that the `_class_name` is of type string or list of string (for custom pipelines)."
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
# remove private attributes
|
| 503 |
+
config_dict = {k: v for k, v in config_dict.items() if not k.startswith("_")}
|
| 504 |
+
|
| 505 |
+
# 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
|
| 506 |
+
init_dict = {}
|
| 507 |
+
for key in expected_keys:
|
| 508 |
+
# if config param is passed to kwarg and is present in config dict
|
| 509 |
+
# it should overwrite existing config dict key
|
| 510 |
+
if key in kwargs and key in config_dict:
|
| 511 |
+
config_dict[key] = kwargs.pop(key)
|
| 512 |
+
|
| 513 |
+
if key in kwargs:
|
| 514 |
+
# overwrite key
|
| 515 |
+
init_dict[key] = kwargs.pop(key)
|
| 516 |
+
elif key in config_dict:
|
| 517 |
+
# use value from config dict
|
| 518 |
+
init_dict[key] = config_dict.pop(key)
|
| 519 |
+
|
| 520 |
+
# 4. Give nice warning if unexpected values have been passed
|
| 521 |
+
if len(config_dict) > 0:
|
| 522 |
+
logger.warning(
|
| 523 |
+
f"The config attributes {config_dict} were passed to {cls.__name__}, "
|
| 524 |
+
"but are not expected and will be ignored. Please verify your "
|
| 525 |
+
f"{cls.config_name} configuration file."
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
# 5. Give nice info if config attributes are initiliazed to default because they have not been passed
|
| 529 |
+
passed_keys = set(init_dict.keys())
|
| 530 |
+
if len(expected_keys - passed_keys) > 0:
|
| 531 |
+
logger.info(
|
| 532 |
+
f"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values."
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
# 6. Define unused keyword arguments
|
| 536 |
+
unused_kwargs = {**config_dict, **kwargs}
|
| 537 |
+
|
| 538 |
+
# 7. Define "hidden" config parameters that were saved for compatible classes
|
| 539 |
+
hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}
|
| 540 |
+
|
| 541 |
+
return init_dict, unused_kwargs, hidden_config_dict
|
| 542 |
+
|
| 543 |
+
@classmethod
|
| 544 |
+
def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
|
| 545 |
+
with open(json_file, "r", encoding="utf-8") as reader:
|
| 546 |
+
text = reader.read()
|
| 547 |
+
return json.loads(text)
|
| 548 |
+
|
| 549 |
+
def __repr__(self):
|
| 550 |
+
return f"{self.__class__.__name__} {self.to_json_string()}"
|
| 551 |
+
|
| 552 |
+
@property
|
| 553 |
+
def config(self) -> Dict[str, Any]:
|
| 554 |
+
"""
|
| 555 |
+
Returns the config of the class as a frozen dictionary
|
| 556 |
+
|
| 557 |
+
Returns:
|
| 558 |
+
`Dict[str, Any]`: Config of the class.
|
| 559 |
+
"""
|
| 560 |
+
return self._internal_dict
|
| 561 |
+
|
| 562 |
+
def to_json_string(self) -> str:
|
| 563 |
+
"""
|
| 564 |
+
Serializes the configuration instance to a JSON string.
|
| 565 |
+
|
| 566 |
+
Returns:
|
| 567 |
+
`str`:
|
| 568 |
+
String containing all the attributes that make up the configuration instance in JSON format.
|
| 569 |
+
"""
|
| 570 |
+
config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
|
| 571 |
+
config_dict["_class_name"] = self.__class__.__name__
|
| 572 |
+
config_dict["_diffusers_version"] = __version__
|
| 573 |
+
|
| 574 |
+
def to_json_saveable(value):
|
| 575 |
+
if isinstance(value, np.ndarray):
|
| 576 |
+
value = value.tolist()
|
| 577 |
+
elif isinstance(value, PosixPath):
|
| 578 |
+
value = str(value)
|
| 579 |
+
return value
|
| 580 |
+
|
| 581 |
+
config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
|
| 582 |
+
# Don't save "_ignore_files" or "_use_default_values"
|
| 583 |
+
config_dict.pop("_ignore_files", None)
|
| 584 |
+
config_dict.pop("_use_default_values", None)
|
| 585 |
+
|
| 586 |
+
return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
|
| 587 |
+
|
| 588 |
+
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
|
| 589 |
+
"""
|
| 590 |
+
Save the configuration instance's parameters to a JSON file.
|
| 591 |
+
|
| 592 |
+
Args:
|
| 593 |
+
json_file_path (`str` or `os.PathLike`):
|
| 594 |
+
Path to the JSON file to save a configuration instance's parameters.
|
| 595 |
+
"""
|
| 596 |
+
with open(json_file_path, "w", encoding="utf-8") as writer:
|
| 597 |
+
writer.write(self.to_json_string())
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def register_to_config(init):
|
| 601 |
+
r"""
|
| 602 |
+
Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
|
| 603 |
+
automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
|
| 604 |
+
shouldn't be registered in the config, use the `ignore_for_config` class variable
|
| 605 |
+
|
| 606 |
+
Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
|
| 607 |
+
"""
|
| 608 |
+
|
| 609 |
+
@functools.wraps(init)
|
| 610 |
+
def inner_init(self, *args, **kwargs):
|
| 611 |
+
# Ignore private kwargs in the init.
|
| 612 |
+
init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
|
| 613 |
+
config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")}
|
| 614 |
+
if not isinstance(self, ConfigMixin):
|
| 615 |
+
raise RuntimeError(
|
| 616 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
| 617 |
+
"not inherit from `ConfigMixin`."
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
ignore = getattr(self, "ignore_for_config", [])
|
| 621 |
+
# Get positional arguments aligned with kwargs
|
| 622 |
+
new_kwargs = {}
|
| 623 |
+
signature = inspect.signature(init)
|
| 624 |
+
parameters = {
|
| 625 |
+
name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore
|
| 626 |
+
}
|
| 627 |
+
for arg, name in zip(args, parameters.keys()):
|
| 628 |
+
new_kwargs[name] = arg
|
| 629 |
+
|
| 630 |
+
# Then add all kwargs
|
| 631 |
+
new_kwargs.update(
|
| 632 |
+
{
|
| 633 |
+
k: init_kwargs.get(k, default)
|
| 634 |
+
for k, default in parameters.items()
|
| 635 |
+
if k not in ignore and k not in new_kwargs
|
| 636 |
+
}
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
# Take note of the parameters that were not present in the loaded config
|
| 640 |
+
if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
|
| 641 |
+
new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
|
| 642 |
+
|
| 643 |
+
new_kwargs = {**config_init_kwargs, **new_kwargs}
|
| 644 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
| 645 |
+
init(self, *args, **init_kwargs)
|
| 646 |
+
|
| 647 |
+
return inner_init
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def flax_register_to_config(cls):
|
| 651 |
+
original_init = cls.__init__
|
| 652 |
+
|
| 653 |
+
@functools.wraps(original_init)
|
| 654 |
+
def init(self, *args, **kwargs):
|
| 655 |
+
if not isinstance(self, ConfigMixin):
|
| 656 |
+
raise RuntimeError(
|
| 657 |
+
f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
|
| 658 |
+
"not inherit from `ConfigMixin`."
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
# Ignore private kwargs in the init. Retrieve all passed attributes
|
| 662 |
+
init_kwargs = dict(kwargs.items())
|
| 663 |
+
|
| 664 |
+
# Retrieve default values
|
| 665 |
+
fields = dataclasses.fields(self)
|
| 666 |
+
default_kwargs = {}
|
| 667 |
+
for field in fields:
|
| 668 |
+
# ignore flax specific attributes
|
| 669 |
+
if field.name in self._flax_internal_args:
|
| 670 |
+
continue
|
| 671 |
+
if type(field.default) == dataclasses._MISSING_TYPE:
|
| 672 |
+
default_kwargs[field.name] = None
|
| 673 |
+
else:
|
| 674 |
+
default_kwargs[field.name] = getattr(self, field.name)
|
| 675 |
+
|
| 676 |
+
# Make sure init_kwargs override default kwargs
|
| 677 |
+
new_kwargs = {**default_kwargs, **init_kwargs}
|
| 678 |
+
# dtype should be part of `init_kwargs`, but not `new_kwargs`
|
| 679 |
+
if "dtype" in new_kwargs:
|
| 680 |
+
new_kwargs.pop("dtype")
|
| 681 |
+
|
| 682 |
+
# Get positional arguments aligned with kwargs
|
| 683 |
+
for i, arg in enumerate(args):
|
| 684 |
+
name = fields[i].name
|
| 685 |
+
new_kwargs[name] = arg
|
| 686 |
+
|
| 687 |
+
# Take note of the parameters that were not present in the loaded config
|
| 688 |
+
if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
|
| 689 |
+
new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
|
| 690 |
+
|
| 691 |
+
getattr(self, "register_to_config")(**new_kwargs)
|
| 692 |
+
original_init(self, *args, **kwargs)
|
| 693 |
+
|
| 694 |
+
cls.__init__ = init
|
| 695 |
+
return cls
|
diffusers/dependency_versions_check.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .dependency_versions_table import deps
|
| 16 |
+
from .utils.versions import require_version, require_version_core
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# define which module versions we always want to check at run time
|
| 20 |
+
# (usually the ones defined in `install_requires` in setup.py)
|
| 21 |
+
#
|
| 22 |
+
# order specific notes:
|
| 23 |
+
# - tqdm must be checked before tokenizers
|
| 24 |
+
|
| 25 |
+
pkgs_to_check_at_runtime = "python requests filelock numpy".split()
|
| 26 |
+
for pkg in pkgs_to_check_at_runtime:
|
| 27 |
+
if pkg in deps:
|
| 28 |
+
require_version_core(deps[pkg])
|
| 29 |
+
else:
|
| 30 |
+
raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def dep_version_check(pkg, hint=None):
|
| 34 |
+
require_version(deps[pkg], hint)
|
diffusers/dependency_versions_table.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# THIS FILE HAS BEEN AUTOGENERATED. To update:
|
| 2 |
+
# 1. modify the `_deps` dict in setup.py
|
| 3 |
+
# 2. run `make deps_table_update`
|
| 4 |
+
deps = {
|
| 5 |
+
"Pillow": "Pillow",
|
| 6 |
+
"accelerate": "accelerate>=0.11.0",
|
| 7 |
+
"compel": "compel==0.1.8",
|
| 8 |
+
"datasets": "datasets",
|
| 9 |
+
"filelock": "filelock",
|
| 10 |
+
"flax": "flax>=0.4.1",
|
| 11 |
+
"hf-doc-builder": "hf-doc-builder>=0.3.0",
|
| 12 |
+
"huggingface-hub": "huggingface-hub>=0.19.4",
|
| 13 |
+
"requests-mock": "requests-mock==1.10.0",
|
| 14 |
+
"importlib_metadata": "importlib_metadata",
|
| 15 |
+
"invisible-watermark": "invisible-watermark>=0.2.0",
|
| 16 |
+
"isort": "isort>=5.5.4",
|
| 17 |
+
"jax": "jax>=0.4.1",
|
| 18 |
+
"jaxlib": "jaxlib>=0.4.1",
|
| 19 |
+
"Jinja2": "Jinja2",
|
| 20 |
+
"k-diffusion": "k-diffusion>=0.0.12",
|
| 21 |
+
"torchsde": "torchsde",
|
| 22 |
+
"note_seq": "note_seq",
|
| 23 |
+
"librosa": "librosa",
|
| 24 |
+
"numpy": "numpy",
|
| 25 |
+
"omegaconf": "omegaconf",
|
| 26 |
+
"parameterized": "parameterized",
|
| 27 |
+
"peft": "peft>=0.6.0",
|
| 28 |
+
"protobuf": "protobuf>=3.20.3,<4",
|
| 29 |
+
"pytest": "pytest",
|
| 30 |
+
"pytest-timeout": "pytest-timeout",
|
| 31 |
+
"pytest-xdist": "pytest-xdist",
|
| 32 |
+
"python": "python>=3.8.0",
|
| 33 |
+
"ruff": "ruff>=0.1.5,<=0.2",
|
| 34 |
+
"safetensors": "safetensors>=0.3.1",
|
| 35 |
+
"sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
|
| 36 |
+
"scipy": "scipy",
|
| 37 |
+
"onnx": "onnx",
|
| 38 |
+
"regex": "regex!=2019.12.17",
|
| 39 |
+
"requests": "requests",
|
| 40 |
+
"tensorboard": "tensorboard",
|
| 41 |
+
"torch": "torch>=1.4",
|
| 42 |
+
"torchvision": "torchvision",
|
| 43 |
+
"transformers": "transformers>=4.25.1",
|
| 44 |
+
"urllib3": "urllib3<=2.0.0",
|
| 45 |
+
}
|
diffusers/experimental/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🧨 Diffusers Experimental
|
| 2 |
+
|
| 3 |
+
We are adding experimental code to support novel applications and usages of the Diffusers library.
|
| 4 |
+
Currently, the following experiments are supported:
|
| 5 |
+
* Reinforcement learning via an implementation of the [Diffuser](https://arxiv.org/abs/2205.09991) model.
|
diffusers/experimental/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .rl import ValueGuidedRLPipeline
|
diffusers/experimental/rl/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .value_guided_sampling import ValueGuidedRLPipeline
|
diffusers/experimental/rl/value_guided_sampling.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
import tqdm
|
| 18 |
+
|
| 19 |
+
from ...models.unet_1d import UNet1DModel
|
| 20 |
+
from ...pipelines import DiffusionPipeline
|
| 21 |
+
from ...utils.dummy_pt_objects import DDPMScheduler
|
| 22 |
+
from ...utils.torch_utils import randn_tensor
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ValueGuidedRLPipeline(DiffusionPipeline):
|
| 26 |
+
r"""
|
| 27 |
+
Pipeline for value-guided sampling from a diffusion model trained to predict sequences of states.
|
| 28 |
+
|
| 29 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 30 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 31 |
+
|
| 32 |
+
Parameters:
|
| 33 |
+
value_function ([`UNet1DModel`]):
|
| 34 |
+
A specialized UNet for fine-tuning trajectories base on reward.
|
| 35 |
+
unet ([`UNet1DModel`]):
|
| 36 |
+
UNet architecture to denoise the encoded trajectories.
|
| 37 |
+
scheduler ([`SchedulerMixin`]):
|
| 38 |
+
A scheduler to be used in combination with `unet` to denoise the encoded trajectories. Default for this
|
| 39 |
+
application is [`DDPMScheduler`].
|
| 40 |
+
env ():
|
| 41 |
+
An environment following the OpenAI gym API to act in. For now only Hopper has pretrained models.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
value_function: UNet1DModel,
|
| 47 |
+
unet: UNet1DModel,
|
| 48 |
+
scheduler: DDPMScheduler,
|
| 49 |
+
env,
|
| 50 |
+
):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.value_function = value_function
|
| 53 |
+
self.unet = unet
|
| 54 |
+
self.scheduler = scheduler
|
| 55 |
+
self.env = env
|
| 56 |
+
self.data = env.get_dataset()
|
| 57 |
+
self.means = {}
|
| 58 |
+
for key in self.data.keys():
|
| 59 |
+
try:
|
| 60 |
+
self.means[key] = self.data[key].mean()
|
| 61 |
+
except: # noqa: E722
|
| 62 |
+
pass
|
| 63 |
+
self.stds = {}
|
| 64 |
+
for key in self.data.keys():
|
| 65 |
+
try:
|
| 66 |
+
self.stds[key] = self.data[key].std()
|
| 67 |
+
except: # noqa: E722
|
| 68 |
+
pass
|
| 69 |
+
self.state_dim = env.observation_space.shape[0]
|
| 70 |
+
self.action_dim = env.action_space.shape[0]
|
| 71 |
+
|
| 72 |
+
def normalize(self, x_in, key):
|
| 73 |
+
return (x_in - self.means[key]) / self.stds[key]
|
| 74 |
+
|
| 75 |
+
def de_normalize(self, x_in, key):
|
| 76 |
+
return x_in * self.stds[key] + self.means[key]
|
| 77 |
+
|
| 78 |
+
def to_torch(self, x_in):
|
| 79 |
+
if isinstance(x_in, dict):
|
| 80 |
+
return {k: self.to_torch(v) for k, v in x_in.items()}
|
| 81 |
+
elif torch.is_tensor(x_in):
|
| 82 |
+
return x_in.to(self.unet.device)
|
| 83 |
+
return torch.tensor(x_in, device=self.unet.device)
|
| 84 |
+
|
| 85 |
+
def reset_x0(self, x_in, cond, act_dim):
|
| 86 |
+
for key, val in cond.items():
|
| 87 |
+
x_in[:, key, act_dim:] = val.clone()
|
| 88 |
+
return x_in
|
| 89 |
+
|
| 90 |
+
def run_diffusion(self, x, conditions, n_guide_steps, scale):
|
| 91 |
+
batch_size = x.shape[0]
|
| 92 |
+
y = None
|
| 93 |
+
for i in tqdm.tqdm(self.scheduler.timesteps):
|
| 94 |
+
# create batch of timesteps to pass into model
|
| 95 |
+
timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
|
| 96 |
+
for _ in range(n_guide_steps):
|
| 97 |
+
with torch.enable_grad():
|
| 98 |
+
x.requires_grad_()
|
| 99 |
+
|
| 100 |
+
# permute to match dimension for pre-trained models
|
| 101 |
+
y = self.value_function(x.permute(0, 2, 1), timesteps).sample
|
| 102 |
+
grad = torch.autograd.grad([y.sum()], [x])[0]
|
| 103 |
+
|
| 104 |
+
posterior_variance = self.scheduler._get_variance(i)
|
| 105 |
+
model_std = torch.exp(0.5 * posterior_variance)
|
| 106 |
+
grad = model_std * grad
|
| 107 |
+
|
| 108 |
+
grad[timesteps < 2] = 0
|
| 109 |
+
x = x.detach()
|
| 110 |
+
x = x + scale * grad
|
| 111 |
+
x = self.reset_x0(x, conditions, self.action_dim)
|
| 112 |
+
|
| 113 |
+
prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
|
| 114 |
+
|
| 115 |
+
# TODO: verify deprecation of this kwarg
|
| 116 |
+
x = self.scheduler.step(prev_x, i, x, predict_epsilon=False)["prev_sample"]
|
| 117 |
+
|
| 118 |
+
# apply conditions to the trajectory (set the initial state)
|
| 119 |
+
x = self.reset_x0(x, conditions, self.action_dim)
|
| 120 |
+
x = self.to_torch(x)
|
| 121 |
+
return x, y
|
| 122 |
+
|
| 123 |
+
def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
|
| 124 |
+
# normalize the observations and create batch dimension
|
| 125 |
+
obs = self.normalize(obs, "observations")
|
| 126 |
+
obs = obs[None].repeat(batch_size, axis=0)
|
| 127 |
+
|
| 128 |
+
conditions = {0: self.to_torch(obs)}
|
| 129 |
+
shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
|
| 130 |
+
|
| 131 |
+
# generate initial noise and apply our conditions (to make the trajectories start at current state)
|
| 132 |
+
x1 = randn_tensor(shape, device=self.unet.device)
|
| 133 |
+
x = self.reset_x0(x1, conditions, self.action_dim)
|
| 134 |
+
x = self.to_torch(x)
|
| 135 |
+
|
| 136 |
+
# run the diffusion process
|
| 137 |
+
x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
|
| 138 |
+
|
| 139 |
+
# sort output trajectories by value
|
| 140 |
+
sorted_idx = y.argsort(0, descending=True).squeeze()
|
| 141 |
+
sorted_values = x[sorted_idx]
|
| 142 |
+
actions = sorted_values[:, :, : self.action_dim]
|
| 143 |
+
actions = actions.detach().cpu().numpy()
|
| 144 |
+
denorm_actions = self.de_normalize(actions, key="actions")
|
| 145 |
+
|
| 146 |
+
# select the action with the highest value
|
| 147 |
+
if y is not None:
|
| 148 |
+
selected_index = 0
|
| 149 |
+
else:
|
| 150 |
+
# if we didn't run value guiding, select a random action
|
| 151 |
+
selected_index = np.random.randint(0, batch_size)
|
| 152 |
+
|
| 153 |
+
denorm_actions = denorm_actions[selected_index, 0]
|
| 154 |
+
return denorm_actions
|
diffusers/image_processor.py
ADDED
|
@@ -0,0 +1,648 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import warnings
|
| 16 |
+
from typing import List, Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import PIL.Image
|
| 20 |
+
import torch
|
| 21 |
+
from PIL import Image
|
| 22 |
+
|
| 23 |
+
from .configuration_utils import ConfigMixin, register_to_config
|
| 24 |
+
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
PipelineImageInput = Union[
|
| 28 |
+
PIL.Image.Image,
|
| 29 |
+
np.ndarray,
|
| 30 |
+
torch.FloatTensor,
|
| 31 |
+
List[PIL.Image.Image],
|
| 32 |
+
List[np.ndarray],
|
| 33 |
+
List[torch.FloatTensor],
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
PipelineDepthInput = Union[
|
| 37 |
+
PIL.Image.Image,
|
| 38 |
+
np.ndarray,
|
| 39 |
+
torch.FloatTensor,
|
| 40 |
+
List[PIL.Image.Image],
|
| 41 |
+
List[np.ndarray],
|
| 42 |
+
List[torch.FloatTensor],
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class VaeImageProcessor(ConfigMixin):
|
| 47 |
+
"""
|
| 48 |
+
Image processor for VAE.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
|
| 53 |
+
`height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
|
| 54 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
| 55 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
| 56 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
| 57 |
+
Resampling filter to use when resizing the image.
|
| 58 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 59 |
+
Whether to normalize the image to [-1,1].
|
| 60 |
+
do_binarize (`bool`, *optional*, defaults to `False`):
|
| 61 |
+
Whether to binarize the image to 0/1.
|
| 62 |
+
do_convert_rgb (`bool`, *optional*, defaults to be `False`):
|
| 63 |
+
Whether to convert the images to RGB format.
|
| 64 |
+
do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
|
| 65 |
+
Whether to convert the images to grayscale format.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
config_name = CONFIG_NAME
|
| 69 |
+
|
| 70 |
+
@register_to_config
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
do_resize: bool = True,
|
| 74 |
+
vae_scale_factor: int = 8,
|
| 75 |
+
resample: str = "lanczos",
|
| 76 |
+
do_normalize: bool = True,
|
| 77 |
+
do_binarize: bool = False,
|
| 78 |
+
do_convert_rgb: bool = False,
|
| 79 |
+
do_convert_grayscale: bool = False,
|
| 80 |
+
):
|
| 81 |
+
super().__init__()
|
| 82 |
+
if do_convert_rgb and do_convert_grayscale:
|
| 83 |
+
raise ValueError(
|
| 84 |
+
"`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
|
| 85 |
+
" if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
|
| 86 |
+
" if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
|
| 87 |
+
)
|
| 88 |
+
self.config.do_convert_rgb = False
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def numpy_to_pil(images: np.ndarray) -> PIL.Image.Image:
|
| 92 |
+
"""
|
| 93 |
+
Convert a numpy image or a batch of images to a PIL image.
|
| 94 |
+
"""
|
| 95 |
+
if images.ndim == 3:
|
| 96 |
+
images = images[None, ...]
|
| 97 |
+
images = (images * 255).round().astype("uint8")
|
| 98 |
+
if images.shape[-1] == 1:
|
| 99 |
+
# special case for grayscale (single channel) images
|
| 100 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
| 101 |
+
else:
|
| 102 |
+
pil_images = [Image.fromarray(image) for image in images]
|
| 103 |
+
|
| 104 |
+
return pil_images
|
| 105 |
+
|
| 106 |
+
@staticmethod
|
| 107 |
+
def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
|
| 108 |
+
"""
|
| 109 |
+
Convert a PIL image or a list of PIL images to NumPy arrays.
|
| 110 |
+
"""
|
| 111 |
+
if not isinstance(images, list):
|
| 112 |
+
images = [images]
|
| 113 |
+
images = [np.array(image).astype(np.float32) / 255.0 for image in images]
|
| 114 |
+
images = np.stack(images, axis=0)
|
| 115 |
+
|
| 116 |
+
return images
|
| 117 |
+
|
| 118 |
+
@staticmethod
|
| 119 |
+
def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
|
| 120 |
+
"""
|
| 121 |
+
Convert a NumPy image to a PyTorch tensor.
|
| 122 |
+
"""
|
| 123 |
+
if images.ndim == 3:
|
| 124 |
+
images = images[..., None]
|
| 125 |
+
|
| 126 |
+
images = torch.from_numpy(images.transpose(0, 3, 1, 2))
|
| 127 |
+
return images
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
|
| 131 |
+
"""
|
| 132 |
+
Convert a PyTorch tensor to a NumPy image.
|
| 133 |
+
"""
|
| 134 |
+
images = images.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 135 |
+
return images
|
| 136 |
+
|
| 137 |
+
@staticmethod
|
| 138 |
+
def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
| 139 |
+
"""
|
| 140 |
+
Normalize an image array to [-1,1].
|
| 141 |
+
"""
|
| 142 |
+
return 2.0 * images - 1.0
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
| 146 |
+
"""
|
| 147 |
+
Denormalize an image array to [0,1].
|
| 148 |
+
"""
|
| 149 |
+
return (images / 2 + 0.5).clamp(0, 1)
|
| 150 |
+
|
| 151 |
+
@staticmethod
|
| 152 |
+
def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
|
| 153 |
+
"""
|
| 154 |
+
Converts a PIL image to RGB format.
|
| 155 |
+
"""
|
| 156 |
+
image = image.convert("RGB")
|
| 157 |
+
|
| 158 |
+
return image
|
| 159 |
+
|
| 160 |
+
@staticmethod
|
| 161 |
+
def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
|
| 162 |
+
"""
|
| 163 |
+
Converts a PIL image to grayscale format.
|
| 164 |
+
"""
|
| 165 |
+
image = image.convert("L")
|
| 166 |
+
|
| 167 |
+
return image
|
| 168 |
+
|
| 169 |
+
def get_default_height_width(
|
| 170 |
+
self,
|
| 171 |
+
image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
|
| 172 |
+
height: Optional[int] = None,
|
| 173 |
+
width: Optional[int] = None,
|
| 174 |
+
) -> Tuple[int, int]:
|
| 175 |
+
"""
|
| 176 |
+
This function return the height and width that are downscaled to the next integer multiple of
|
| 177 |
+
`vae_scale_factor`.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
|
| 181 |
+
The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
|
| 182 |
+
shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
|
| 183 |
+
have shape `[batch, channel, height, width]`.
|
| 184 |
+
height (`int`, *optional*, defaults to `None`):
|
| 185 |
+
The height in preprocessed image. If `None`, will use the height of `image` input.
|
| 186 |
+
width (`int`, *optional*`, defaults to `None`):
|
| 187 |
+
The width in preprocessed. If `None`, will use the width of the `image` input.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
if height is None:
|
| 191 |
+
if isinstance(image, PIL.Image.Image):
|
| 192 |
+
height = image.height
|
| 193 |
+
elif isinstance(image, torch.Tensor):
|
| 194 |
+
height = image.shape[2]
|
| 195 |
+
else:
|
| 196 |
+
height = image.shape[1]
|
| 197 |
+
|
| 198 |
+
if width is None:
|
| 199 |
+
if isinstance(image, PIL.Image.Image):
|
| 200 |
+
width = image.width
|
| 201 |
+
elif isinstance(image, torch.Tensor):
|
| 202 |
+
width = image.shape[3]
|
| 203 |
+
else:
|
| 204 |
+
width = image.shape[2]
|
| 205 |
+
|
| 206 |
+
width, height = (
|
| 207 |
+
x - x % self.config.vae_scale_factor for x in (width, height)
|
| 208 |
+
) # resize to integer multiple of vae_scale_factor
|
| 209 |
+
|
| 210 |
+
return height, width
|
| 211 |
+
|
| 212 |
+
def resize(
|
| 213 |
+
self,
|
| 214 |
+
image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
|
| 215 |
+
height: Optional[int] = None,
|
| 216 |
+
width: Optional[int] = None,
|
| 217 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
|
| 218 |
+
"""
|
| 219 |
+
Resize image.
|
| 220 |
+
|
| 221 |
+
Args:
|
| 222 |
+
image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
|
| 223 |
+
The image input, can be a PIL image, numpy array or pytorch tensor.
|
| 224 |
+
height (`int`, *optional*, defaults to `None`):
|
| 225 |
+
The height to resize to.
|
| 226 |
+
width (`int`, *optional*`, defaults to `None`):
|
| 227 |
+
The width to resize to.
|
| 228 |
+
|
| 229 |
+
Returns:
|
| 230 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
|
| 231 |
+
The resized image.
|
| 232 |
+
"""
|
| 233 |
+
if isinstance(image, PIL.Image.Image):
|
| 234 |
+
image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
|
| 235 |
+
elif isinstance(image, torch.Tensor):
|
| 236 |
+
image = torch.nn.functional.interpolate(
|
| 237 |
+
image,
|
| 238 |
+
size=(height, width),
|
| 239 |
+
)
|
| 240 |
+
elif isinstance(image, np.ndarray):
|
| 241 |
+
image = self.numpy_to_pt(image)
|
| 242 |
+
image = torch.nn.functional.interpolate(
|
| 243 |
+
image,
|
| 244 |
+
size=(height, width),
|
| 245 |
+
)
|
| 246 |
+
image = self.pt_to_numpy(image)
|
| 247 |
+
return image
|
| 248 |
+
|
| 249 |
+
def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
|
| 250 |
+
"""
|
| 251 |
+
Create a mask.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
image (`PIL.Image.Image`):
|
| 255 |
+
The image input, should be a PIL image.
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
`PIL.Image.Image`:
|
| 259 |
+
The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
|
| 260 |
+
"""
|
| 261 |
+
image[image < 0.5] = 0
|
| 262 |
+
image[image >= 0.5] = 1
|
| 263 |
+
return image
|
| 264 |
+
|
| 265 |
+
def preprocess(
|
| 266 |
+
self,
|
| 267 |
+
image: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
|
| 268 |
+
height: Optional[int] = None,
|
| 269 |
+
width: Optional[int] = None,
|
| 270 |
+
) -> torch.Tensor:
|
| 271 |
+
"""
|
| 272 |
+
Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
|
| 273 |
+
"""
|
| 274 |
+
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
|
| 275 |
+
|
| 276 |
+
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
|
| 277 |
+
if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
|
| 278 |
+
if isinstance(image, torch.Tensor):
|
| 279 |
+
# if image is a pytorch tensor could have 2 possible shapes:
|
| 280 |
+
# 1. batch x height x width: we should insert the channel dimension at position 1
|
| 281 |
+
# 2. channnel x height x width: we should insert batch dimension at position 0,
|
| 282 |
+
# however, since both channel and batch dimension has same size 1, it is same to insert at position 1
|
| 283 |
+
# for simplicity, we insert a dimension of size 1 at position 1 for both cases
|
| 284 |
+
image = image.unsqueeze(1)
|
| 285 |
+
else:
|
| 286 |
+
# if it is a numpy array, it could have 2 possible shapes:
|
| 287 |
+
# 1. batch x height x width: insert channel dimension on last position
|
| 288 |
+
# 2. height x width x channel: insert batch dimension on first position
|
| 289 |
+
if image.shape[-1] == 1:
|
| 290 |
+
image = np.expand_dims(image, axis=0)
|
| 291 |
+
else:
|
| 292 |
+
image = np.expand_dims(image, axis=-1)
|
| 293 |
+
|
| 294 |
+
if isinstance(image, supported_formats):
|
| 295 |
+
image = [image]
|
| 296 |
+
elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
|
| 297 |
+
raise ValueError(
|
| 298 |
+
f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
if isinstance(image[0], PIL.Image.Image):
|
| 302 |
+
if self.config.do_convert_rgb:
|
| 303 |
+
image = [self.convert_to_rgb(i) for i in image]
|
| 304 |
+
elif self.config.do_convert_grayscale:
|
| 305 |
+
image = [self.convert_to_grayscale(i) for i in image]
|
| 306 |
+
if self.config.do_resize:
|
| 307 |
+
height, width = self.get_default_height_width(image[0], height, width)
|
| 308 |
+
image = [self.resize(i, height, width) for i in image]
|
| 309 |
+
image = self.pil_to_numpy(image) # to np
|
| 310 |
+
image = self.numpy_to_pt(image) # to pt
|
| 311 |
+
|
| 312 |
+
elif isinstance(image[0], np.ndarray):
|
| 313 |
+
image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
|
| 314 |
+
|
| 315 |
+
image = self.numpy_to_pt(image)
|
| 316 |
+
|
| 317 |
+
height, width = self.get_default_height_width(image, height, width)
|
| 318 |
+
if self.config.do_resize:
|
| 319 |
+
image = self.resize(image, height, width)
|
| 320 |
+
|
| 321 |
+
elif isinstance(image[0], torch.Tensor):
|
| 322 |
+
image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
|
| 323 |
+
|
| 324 |
+
if self.config.do_convert_grayscale and image.ndim == 3:
|
| 325 |
+
image = image.unsqueeze(1)
|
| 326 |
+
|
| 327 |
+
channel = image.shape[1]
|
| 328 |
+
# don't need any preprocess if the image is latents
|
| 329 |
+
if channel == 4:
|
| 330 |
+
return image
|
| 331 |
+
|
| 332 |
+
height, width = self.get_default_height_width(image, height, width)
|
| 333 |
+
if self.config.do_resize:
|
| 334 |
+
image = self.resize(image, height, width)
|
| 335 |
+
|
| 336 |
+
# expected range [0,1], normalize to [-1,1]
|
| 337 |
+
do_normalize = self.config.do_normalize
|
| 338 |
+
if do_normalize and image.min() < 0:
|
| 339 |
+
warnings.warn(
|
| 340 |
+
"Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
|
| 341 |
+
f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
|
| 342 |
+
FutureWarning,
|
| 343 |
+
)
|
| 344 |
+
do_normalize = False
|
| 345 |
+
|
| 346 |
+
if do_normalize:
|
| 347 |
+
image = self.normalize(image)
|
| 348 |
+
|
| 349 |
+
if self.config.do_binarize:
|
| 350 |
+
image = self.binarize(image)
|
| 351 |
+
|
| 352 |
+
return image
|
| 353 |
+
|
| 354 |
+
def postprocess(
|
| 355 |
+
self,
|
| 356 |
+
image: torch.FloatTensor,
|
| 357 |
+
output_type: str = "pil",
|
| 358 |
+
do_denormalize: Optional[List[bool]] = None,
|
| 359 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
|
| 360 |
+
"""
|
| 361 |
+
Postprocess the image output from tensor to `output_type`.
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
image (`torch.FloatTensor`):
|
| 365 |
+
The image input, should be a pytorch tensor with shape `B x C x H x W`.
|
| 366 |
+
output_type (`str`, *optional*, defaults to `pil`):
|
| 367 |
+
The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
|
| 368 |
+
do_denormalize (`List[bool]`, *optional*, defaults to `None`):
|
| 369 |
+
Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
|
| 370 |
+
`VaeImageProcessor` config.
|
| 371 |
+
|
| 372 |
+
Returns:
|
| 373 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
|
| 374 |
+
The postprocessed image.
|
| 375 |
+
"""
|
| 376 |
+
if not isinstance(image, torch.Tensor):
|
| 377 |
+
raise ValueError(
|
| 378 |
+
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
|
| 379 |
+
)
|
| 380 |
+
if output_type not in ["latent", "pt", "np", "pil"]:
|
| 381 |
+
deprecation_message = (
|
| 382 |
+
f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
|
| 383 |
+
"`pil`, `np`, `pt`, `latent`"
|
| 384 |
+
)
|
| 385 |
+
deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
|
| 386 |
+
output_type = "np"
|
| 387 |
+
|
| 388 |
+
if output_type == "latent":
|
| 389 |
+
return image
|
| 390 |
+
|
| 391 |
+
if do_denormalize is None:
|
| 392 |
+
do_denormalize = [self.config.do_normalize] * image.shape[0]
|
| 393 |
+
|
| 394 |
+
image = torch.stack(
|
| 395 |
+
[self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
if output_type == "pt":
|
| 399 |
+
return image
|
| 400 |
+
|
| 401 |
+
image = self.pt_to_numpy(image)
|
| 402 |
+
|
| 403 |
+
if output_type == "np":
|
| 404 |
+
return image
|
| 405 |
+
|
| 406 |
+
if output_type == "pil":
|
| 407 |
+
return self.numpy_to_pil(image)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class VaeImageProcessorLDM3D(VaeImageProcessor):
|
| 411 |
+
"""
|
| 412 |
+
Image processor for VAE LDM3D.
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 416 |
+
Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
|
| 417 |
+
vae_scale_factor (`int`, *optional*, defaults to `8`):
|
| 418 |
+
VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
|
| 419 |
+
resample (`str`, *optional*, defaults to `lanczos`):
|
| 420 |
+
Resampling filter to use when resizing the image.
|
| 421 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 422 |
+
Whether to normalize the image to [-1,1].
|
| 423 |
+
"""
|
| 424 |
+
|
| 425 |
+
config_name = CONFIG_NAME
|
| 426 |
+
|
| 427 |
+
@register_to_config
|
| 428 |
+
def __init__(
|
| 429 |
+
self,
|
| 430 |
+
do_resize: bool = True,
|
| 431 |
+
vae_scale_factor: int = 8,
|
| 432 |
+
resample: str = "lanczos",
|
| 433 |
+
do_normalize: bool = True,
|
| 434 |
+
):
|
| 435 |
+
super().__init__()
|
| 436 |
+
|
| 437 |
+
@staticmethod
|
| 438 |
+
def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
|
| 439 |
+
"""
|
| 440 |
+
Convert a NumPy image or a batch of images to a PIL image.
|
| 441 |
+
"""
|
| 442 |
+
if images.ndim == 3:
|
| 443 |
+
images = images[None, ...]
|
| 444 |
+
images = (images * 255).round().astype("uint8")
|
| 445 |
+
if images.shape[-1] == 1:
|
| 446 |
+
# special case for grayscale (single channel) images
|
| 447 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
| 448 |
+
else:
|
| 449 |
+
pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
|
| 450 |
+
|
| 451 |
+
return pil_images
|
| 452 |
+
|
| 453 |
+
@staticmethod
|
| 454 |
+
def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
|
| 455 |
+
"""
|
| 456 |
+
Convert a PIL image or a list of PIL images to NumPy arrays.
|
| 457 |
+
"""
|
| 458 |
+
if not isinstance(images, list):
|
| 459 |
+
images = [images]
|
| 460 |
+
|
| 461 |
+
images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
|
| 462 |
+
images = np.stack(images, axis=0)
|
| 463 |
+
return images
|
| 464 |
+
|
| 465 |
+
@staticmethod
|
| 466 |
+
def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
|
| 467 |
+
"""
|
| 468 |
+
Args:
|
| 469 |
+
image: RGB-like depth image
|
| 470 |
+
|
| 471 |
+
Returns: depth map
|
| 472 |
+
|
| 473 |
+
"""
|
| 474 |
+
return image[:, :, 1] * 2**8 + image[:, :, 2]
|
| 475 |
+
|
| 476 |
+
def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
|
| 477 |
+
"""
|
| 478 |
+
Convert a NumPy depth image or a batch of images to a PIL image.
|
| 479 |
+
"""
|
| 480 |
+
if images.ndim == 3:
|
| 481 |
+
images = images[None, ...]
|
| 482 |
+
images_depth = images[:, :, :, 3:]
|
| 483 |
+
if images.shape[-1] == 6:
|
| 484 |
+
images_depth = (images_depth * 255).round().astype("uint8")
|
| 485 |
+
pil_images = [
|
| 486 |
+
Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
|
| 487 |
+
]
|
| 488 |
+
elif images.shape[-1] == 4:
|
| 489 |
+
images_depth = (images_depth * 65535.0).astype(np.uint16)
|
| 490 |
+
pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
|
| 491 |
+
else:
|
| 492 |
+
raise Exception("Not supported")
|
| 493 |
+
|
| 494 |
+
return pil_images
|
| 495 |
+
|
| 496 |
+
def postprocess(
|
| 497 |
+
self,
|
| 498 |
+
image: torch.FloatTensor,
|
| 499 |
+
output_type: str = "pil",
|
| 500 |
+
do_denormalize: Optional[List[bool]] = None,
|
| 501 |
+
) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
|
| 502 |
+
"""
|
| 503 |
+
Postprocess the image output from tensor to `output_type`.
|
| 504 |
+
|
| 505 |
+
Args:
|
| 506 |
+
image (`torch.FloatTensor`):
|
| 507 |
+
The image input, should be a pytorch tensor with shape `B x C x H x W`.
|
| 508 |
+
output_type (`str`, *optional*, defaults to `pil`):
|
| 509 |
+
The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
|
| 510 |
+
do_denormalize (`List[bool]`, *optional*, defaults to `None`):
|
| 511 |
+
Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
|
| 512 |
+
`VaeImageProcessor` config.
|
| 513 |
+
|
| 514 |
+
Returns:
|
| 515 |
+
`PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
|
| 516 |
+
The postprocessed image.
|
| 517 |
+
"""
|
| 518 |
+
if not isinstance(image, torch.Tensor):
|
| 519 |
+
raise ValueError(
|
| 520 |
+
f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
|
| 521 |
+
)
|
| 522 |
+
if output_type not in ["latent", "pt", "np", "pil"]:
|
| 523 |
+
deprecation_message = (
|
| 524 |
+
f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
|
| 525 |
+
"`pil`, `np`, `pt`, `latent`"
|
| 526 |
+
)
|
| 527 |
+
deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
|
| 528 |
+
output_type = "np"
|
| 529 |
+
|
| 530 |
+
if do_denormalize is None:
|
| 531 |
+
do_denormalize = [self.config.do_normalize] * image.shape[0]
|
| 532 |
+
|
| 533 |
+
image = torch.stack(
|
| 534 |
+
[self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
image = self.pt_to_numpy(image)
|
| 538 |
+
|
| 539 |
+
if output_type == "np":
|
| 540 |
+
if image.shape[-1] == 6:
|
| 541 |
+
image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
|
| 542 |
+
else:
|
| 543 |
+
image_depth = image[:, :, :, 3:]
|
| 544 |
+
return image[:, :, :, :3], image_depth
|
| 545 |
+
|
| 546 |
+
if output_type == "pil":
|
| 547 |
+
return self.numpy_to_pil(image), self.numpy_to_depth(image)
|
| 548 |
+
else:
|
| 549 |
+
raise Exception(f"This type {output_type} is not supported")
|
| 550 |
+
|
| 551 |
+
def preprocess(
|
| 552 |
+
self,
|
| 553 |
+
rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
|
| 554 |
+
depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
|
| 555 |
+
height: Optional[int] = None,
|
| 556 |
+
width: Optional[int] = None,
|
| 557 |
+
target_res: Optional[int] = None,
|
| 558 |
+
) -> torch.Tensor:
|
| 559 |
+
"""
|
| 560 |
+
Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
|
| 561 |
+
"""
|
| 562 |
+
supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
|
| 563 |
+
|
| 564 |
+
# Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
|
| 565 |
+
if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
|
| 566 |
+
raise Exception("This is not yet supported")
|
| 567 |
+
|
| 568 |
+
if isinstance(rgb, supported_formats):
|
| 569 |
+
rgb = [rgb]
|
| 570 |
+
depth = [depth]
|
| 571 |
+
elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
|
| 572 |
+
raise ValueError(
|
| 573 |
+
f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
if isinstance(rgb[0], PIL.Image.Image):
|
| 577 |
+
if self.config.do_convert_rgb:
|
| 578 |
+
raise Exception("This is not yet supported")
|
| 579 |
+
# rgb = [self.convert_to_rgb(i) for i in rgb]
|
| 580 |
+
# depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
|
| 581 |
+
if self.config.do_resize or target_res:
|
| 582 |
+
height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
|
| 583 |
+
rgb = [self.resize(i, height, width) for i in rgb]
|
| 584 |
+
depth = [self.resize(i, height, width) for i in depth]
|
| 585 |
+
rgb = self.pil_to_numpy(rgb) # to np
|
| 586 |
+
rgb = self.numpy_to_pt(rgb) # to pt
|
| 587 |
+
|
| 588 |
+
depth = self.depth_pil_to_numpy(depth) # to np
|
| 589 |
+
depth = self.numpy_to_pt(depth) # to pt
|
| 590 |
+
|
| 591 |
+
elif isinstance(rgb[0], np.ndarray):
|
| 592 |
+
rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
|
| 593 |
+
rgb = self.numpy_to_pt(rgb)
|
| 594 |
+
height, width = self.get_default_height_width(rgb, height, width)
|
| 595 |
+
if self.config.do_resize:
|
| 596 |
+
rgb = self.resize(rgb, height, width)
|
| 597 |
+
|
| 598 |
+
depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
|
| 599 |
+
depth = self.numpy_to_pt(depth)
|
| 600 |
+
height, width = self.get_default_height_width(depth, height, width)
|
| 601 |
+
if self.config.do_resize:
|
| 602 |
+
depth = self.resize(depth, height, width)
|
| 603 |
+
|
| 604 |
+
elif isinstance(rgb[0], torch.Tensor):
|
| 605 |
+
raise Exception("This is not yet supported")
|
| 606 |
+
# rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
|
| 607 |
+
|
| 608 |
+
# if self.config.do_convert_grayscale and rgb.ndim == 3:
|
| 609 |
+
# rgb = rgb.unsqueeze(1)
|
| 610 |
+
|
| 611 |
+
# channel = rgb.shape[1]
|
| 612 |
+
|
| 613 |
+
# height, width = self.get_default_height_width(rgb, height, width)
|
| 614 |
+
# if self.config.do_resize:
|
| 615 |
+
# rgb = self.resize(rgb, height, width)
|
| 616 |
+
|
| 617 |
+
# depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
|
| 618 |
+
|
| 619 |
+
# if self.config.do_convert_grayscale and depth.ndim == 3:
|
| 620 |
+
# depth = depth.unsqueeze(1)
|
| 621 |
+
|
| 622 |
+
# channel = depth.shape[1]
|
| 623 |
+
# # don't need any preprocess if the image is latents
|
| 624 |
+
# if depth == 4:
|
| 625 |
+
# return rgb, depth
|
| 626 |
+
|
| 627 |
+
# height, width = self.get_default_height_width(depth, height, width)
|
| 628 |
+
# if self.config.do_resize:
|
| 629 |
+
# depth = self.resize(depth, height, width)
|
| 630 |
+
# expected range [0,1], normalize to [-1,1]
|
| 631 |
+
do_normalize = self.config.do_normalize
|
| 632 |
+
if rgb.min() < 0 and do_normalize:
|
| 633 |
+
warnings.warn(
|
| 634 |
+
"Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
|
| 635 |
+
f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
|
| 636 |
+
FutureWarning,
|
| 637 |
+
)
|
| 638 |
+
do_normalize = False
|
| 639 |
+
|
| 640 |
+
if do_normalize:
|
| 641 |
+
rgb = self.normalize(rgb)
|
| 642 |
+
depth = self.normalize(depth)
|
| 643 |
+
|
| 644 |
+
if self.config.do_binarize:
|
| 645 |
+
rgb = self.binarize(rgb)
|
| 646 |
+
depth = self.binarize(depth)
|
| 647 |
+
|
| 648 |
+
return rgb, depth
|
diffusers/loaders/__init__.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ..utils import DIFFUSERS_SLOW_IMPORT, _LazyModule, deprecate
|
| 4 |
+
from ..utils.import_utils import is_torch_available, is_transformers_available
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def text_encoder_lora_state_dict(text_encoder):
|
| 8 |
+
deprecate(
|
| 9 |
+
"text_encoder_load_state_dict in `models`",
|
| 10 |
+
"0.27.0",
|
| 11 |
+
"`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
|
| 12 |
+
)
|
| 13 |
+
state_dict = {}
|
| 14 |
+
|
| 15 |
+
for name, module in text_encoder_attn_modules(text_encoder):
|
| 16 |
+
for k, v in module.q_proj.lora_linear_layer.state_dict().items():
|
| 17 |
+
state_dict[f"{name}.q_proj.lora_linear_layer.{k}"] = v
|
| 18 |
+
|
| 19 |
+
for k, v in module.k_proj.lora_linear_layer.state_dict().items():
|
| 20 |
+
state_dict[f"{name}.k_proj.lora_linear_layer.{k}"] = v
|
| 21 |
+
|
| 22 |
+
for k, v in module.v_proj.lora_linear_layer.state_dict().items():
|
| 23 |
+
state_dict[f"{name}.v_proj.lora_linear_layer.{k}"] = v
|
| 24 |
+
|
| 25 |
+
for k, v in module.out_proj.lora_linear_layer.state_dict().items():
|
| 26 |
+
state_dict[f"{name}.out_proj.lora_linear_layer.{k}"] = v
|
| 27 |
+
|
| 28 |
+
return state_dict
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if is_transformers_available():
|
| 32 |
+
|
| 33 |
+
def text_encoder_attn_modules(text_encoder):
|
| 34 |
+
deprecate(
|
| 35 |
+
"text_encoder_attn_modules in `models`",
|
| 36 |
+
"0.27.0",
|
| 37 |
+
"`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
|
| 38 |
+
)
|
| 39 |
+
from transformers import CLIPTextModel, CLIPTextModelWithProjection
|
| 40 |
+
|
| 41 |
+
attn_modules = []
|
| 42 |
+
|
| 43 |
+
if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
|
| 44 |
+
for i, layer in enumerate(text_encoder.text_model.encoder.layers):
|
| 45 |
+
name = f"text_model.encoder.layers.{i}.self_attn"
|
| 46 |
+
mod = layer.self_attn
|
| 47 |
+
attn_modules.append((name, mod))
|
| 48 |
+
else:
|
| 49 |
+
raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
|
| 50 |
+
|
| 51 |
+
return attn_modules
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
_import_structure = {}
|
| 55 |
+
|
| 56 |
+
if is_torch_available():
|
| 57 |
+
_import_structure["single_file"] = ["FromOriginalControlnetMixin", "FromOriginalVAEMixin"]
|
| 58 |
+
_import_structure["unet"] = ["UNet2DConditionLoadersMixin"]
|
| 59 |
+
_import_structure["utils"] = ["AttnProcsLayers"]
|
| 60 |
+
|
| 61 |
+
if is_transformers_available():
|
| 62 |
+
_import_structure["single_file"].extend(["FromSingleFileMixin"])
|
| 63 |
+
_import_structure["lora"] = ["LoraLoaderMixin", "StableDiffusionXLLoraLoaderMixin"]
|
| 64 |
+
_import_structure["textual_inversion"] = ["TextualInversionLoaderMixin"]
|
| 65 |
+
_import_structure["ip_adapter"] = ["IPAdapterMixin"]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 69 |
+
if is_torch_available():
|
| 70 |
+
from .single_file import FromOriginalControlnetMixin, FromOriginalVAEMixin
|
| 71 |
+
from .unet import UNet2DConditionLoadersMixin
|
| 72 |
+
from .utils import AttnProcsLayers
|
| 73 |
+
|
| 74 |
+
if is_transformers_available():
|
| 75 |
+
from .ip_adapter import IPAdapterMixin
|
| 76 |
+
from .lora import LoraLoaderMixin, StableDiffusionXLLoraLoaderMixin
|
| 77 |
+
from .single_file import FromSingleFileMixin
|
| 78 |
+
from .textual_inversion import TextualInversionLoaderMixin
|
| 79 |
+
else:
|
| 80 |
+
import sys
|
| 81 |
+
|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|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import os
|
| 15 |
+
from typing import Dict, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from safetensors import safe_open
|
| 19 |
+
|
| 20 |
+
from ..utils import (
|
| 21 |
+
DIFFUSERS_CACHE,
|
| 22 |
+
HF_HUB_OFFLINE,
|
| 23 |
+
_get_model_file,
|
| 24 |
+
is_transformers_available,
|
| 25 |
+
logging,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_transformers_available():
|
| 30 |
+
from transformers import (
|
| 31 |
+
CLIPImageProcessor,
|
| 32 |
+
CLIPVisionModelWithProjection,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
from ..models.attention_processor import (
|
| 36 |
+
IPAdapterAttnProcessor,
|
| 37 |
+
IPAdapterAttnProcessor2_0,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class IPAdapterMixin:
|
| 44 |
+
"""Mixin for handling IP Adapters."""
|
| 45 |
+
|
| 46 |
+
def load_ip_adapter(
|
| 47 |
+
self,
|
| 48 |
+
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
| 49 |
+
subfolder: str,
|
| 50 |
+
weight_name: str,
|
| 51 |
+
**kwargs,
|
| 52 |
+
):
|
| 53 |
+
"""
|
| 54 |
+
Parameters:
|
| 55 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
| 56 |
+
Can be either:
|
| 57 |
+
|
| 58 |
+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
| 59 |
+
the Hub.
|
| 60 |
+
- A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
|
| 61 |
+
with [`ModelMixin.save_pretrained`].
|
| 62 |
+
- A [torch state
|
| 63 |
+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
| 64 |
+
|
| 65 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 66 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 67 |
+
is not used.
|
| 68 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 69 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 70 |
+
cached versions if they exist.
|
| 71 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 72 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 73 |
+
incompletely downloaded files are deleted.
|
| 74 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 75 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 76 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 77 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 78 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 79 |
+
won't be downloaded from the Hub.
|
| 80 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 81 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 82 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 83 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 84 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 85 |
+
allowed by Git.
|
| 86 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 87 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
# Load the main state dict first.
|
| 91 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 92 |
+
force_download = kwargs.pop("force_download", False)
|
| 93 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 94 |
+
proxies = kwargs.pop("proxies", None)
|
| 95 |
+
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
| 96 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 97 |
+
revision = kwargs.pop("revision", None)
|
| 98 |
+
|
| 99 |
+
user_agent = {
|
| 100 |
+
"file_type": "attn_procs_weights",
|
| 101 |
+
"framework": "pytorch",
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
| 105 |
+
model_file = _get_model_file(
|
| 106 |
+
pretrained_model_name_or_path_or_dict,
|
| 107 |
+
weights_name=weight_name,
|
| 108 |
+
cache_dir=cache_dir,
|
| 109 |
+
force_download=force_download,
|
| 110 |
+
resume_download=resume_download,
|
| 111 |
+
proxies=proxies,
|
| 112 |
+
local_files_only=local_files_only,
|
| 113 |
+
use_auth_token=use_auth_token,
|
| 114 |
+
revision=revision,
|
| 115 |
+
subfolder=subfolder,
|
| 116 |
+
user_agent=user_agent,
|
| 117 |
+
)
|
| 118 |
+
if weight_name.endswith(".safetensors"):
|
| 119 |
+
state_dict = {"image_proj": {}, "ip_adapter": {}}
|
| 120 |
+
with safe_open(model_file, framework="pt", device="cpu") as f:
|
| 121 |
+
for key in f.keys():
|
| 122 |
+
if key.startswith("image_proj."):
|
| 123 |
+
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
|
| 124 |
+
elif key.startswith("ip_adapter."):
|
| 125 |
+
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
|
| 126 |
+
else:
|
| 127 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 128 |
+
else:
|
| 129 |
+
state_dict = pretrained_model_name_or_path_or_dict
|
| 130 |
+
|
| 131 |
+
keys = list(state_dict.keys())
|
| 132 |
+
if keys != ["image_proj", "ip_adapter"]:
|
| 133 |
+
raise ValueError("Required keys are (`image_proj` and `ip_adapter`) missing from the state dict.")
|
| 134 |
+
|
| 135 |
+
# load CLIP image encoer here if it has not been registered to the pipeline yet
|
| 136 |
+
if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is None:
|
| 137 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
| 138 |
+
logger.info(f"loading image_encoder from {pretrained_model_name_or_path_or_dict}")
|
| 139 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(
|
| 140 |
+
pretrained_model_name_or_path_or_dict,
|
| 141 |
+
subfolder=os.path.join(subfolder, "image_encoder"),
|
| 142 |
+
).to(self.device, dtype=self.dtype)
|
| 143 |
+
self.image_encoder = image_encoder
|
| 144 |
+
else:
|
| 145 |
+
raise ValueError("`image_encoder` cannot be None when using IP Adapters.")
|
| 146 |
+
|
| 147 |
+
# create feature extractor if it has not been registered to the pipeline yet
|
| 148 |
+
if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is None:
|
| 149 |
+
self.feature_extractor = CLIPImageProcessor()
|
| 150 |
+
|
| 151 |
+
# load ip-adapter into unet
|
| 152 |
+
self.unet._load_ip_adapter_weights(state_dict)
|
| 153 |
+
|
| 154 |
+
def set_ip_adapter_scale(self, scale):
|
| 155 |
+
for attn_processor in self.unet.attn_processors.values():
|
| 156 |
+
if isinstance(attn_processor, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0)):
|
| 157 |
+
attn_processor.scale = scale
|
diffusers/loaders/lora.py
ADDED
|
@@ -0,0 +1,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import os
|
| 15 |
+
from contextlib import nullcontext
|
| 16 |
+
from typing import Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import safetensors
|
| 19 |
+
import torch
|
| 20 |
+
from huggingface_hub import model_info
|
| 21 |
+
from packaging import version
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from .. import __version__
|
| 25 |
+
from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
|
| 26 |
+
from ..utils import (
|
| 27 |
+
DIFFUSERS_CACHE,
|
| 28 |
+
HF_HUB_OFFLINE,
|
| 29 |
+
USE_PEFT_BACKEND,
|
| 30 |
+
_get_model_file,
|
| 31 |
+
convert_state_dict_to_diffusers,
|
| 32 |
+
convert_state_dict_to_peft,
|
| 33 |
+
convert_unet_state_dict_to_peft,
|
| 34 |
+
delete_adapter_layers,
|
| 35 |
+
deprecate,
|
| 36 |
+
get_adapter_name,
|
| 37 |
+
get_peft_kwargs,
|
| 38 |
+
is_accelerate_available,
|
| 39 |
+
is_transformers_available,
|
| 40 |
+
logging,
|
| 41 |
+
recurse_remove_peft_layers,
|
| 42 |
+
scale_lora_layers,
|
| 43 |
+
set_adapter_layers,
|
| 44 |
+
set_weights_and_activate_adapters,
|
| 45 |
+
)
|
| 46 |
+
from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if is_transformers_available():
|
| 50 |
+
from transformers import PreTrainedModel
|
| 51 |
+
|
| 52 |
+
from ..models.lora import PatchedLoraProjection, text_encoder_attn_modules, text_encoder_mlp_modules
|
| 53 |
+
|
| 54 |
+
if is_accelerate_available():
|
| 55 |
+
from accelerate import init_empty_weights
|
| 56 |
+
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
| 57 |
+
|
| 58 |
+
logger = logging.get_logger(__name__)
|
| 59 |
+
|
| 60 |
+
TEXT_ENCODER_NAME = "text_encoder"
|
| 61 |
+
UNET_NAME = "unet"
|
| 62 |
+
|
| 63 |
+
LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
|
| 64 |
+
LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
|
| 65 |
+
|
| 66 |
+
LORA_DEPRECATION_MESSAGE = "You are using an old version of LoRA backend. This will be deprecated in the next releases in favor of PEFT make sure to install the latest PEFT and transformers packages in the future."
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class LoraLoaderMixin:
|
| 70 |
+
r"""
|
| 71 |
+
Load LoRA layers into [`UNet2DConditionModel`] and
|
| 72 |
+
[`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
text_encoder_name = TEXT_ENCODER_NAME
|
| 76 |
+
unet_name = UNET_NAME
|
| 77 |
+
num_fused_loras = 0
|
| 78 |
+
|
| 79 |
+
def load_lora_weights(
|
| 80 |
+
self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
|
| 81 |
+
):
|
| 82 |
+
"""
|
| 83 |
+
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
|
| 84 |
+
`self.text_encoder`.
|
| 85 |
+
|
| 86 |
+
All kwargs are forwarded to `self.lora_state_dict`.
|
| 87 |
+
|
| 88 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
|
| 89 |
+
|
| 90 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
|
| 91 |
+
`self.unet`.
|
| 92 |
+
|
| 93 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
|
| 94 |
+
into `self.text_encoder`.
|
| 95 |
+
|
| 96 |
+
Parameters:
|
| 97 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
| 98 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
| 99 |
+
kwargs (`dict`, *optional*):
|
| 100 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
| 101 |
+
adapter_name (`str`, *optional*):
|
| 102 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
| 103 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
| 104 |
+
"""
|
| 105 |
+
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
|
| 106 |
+
state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
|
| 107 |
+
|
| 108 |
+
is_correct_format = all("lora" in key for key in state_dict.keys())
|
| 109 |
+
if not is_correct_format:
|
| 110 |
+
raise ValueError("Invalid LoRA checkpoint.")
|
| 111 |
+
|
| 112 |
+
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
| 113 |
+
|
| 114 |
+
self.load_lora_into_unet(
|
| 115 |
+
state_dict,
|
| 116 |
+
network_alphas=network_alphas,
|
| 117 |
+
unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
|
| 118 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
| 119 |
+
adapter_name=adapter_name,
|
| 120 |
+
_pipeline=self,
|
| 121 |
+
)
|
| 122 |
+
self.load_lora_into_text_encoder(
|
| 123 |
+
state_dict,
|
| 124 |
+
network_alphas=network_alphas,
|
| 125 |
+
text_encoder=getattr(self, self.text_encoder_name)
|
| 126 |
+
if not hasattr(self, "text_encoder")
|
| 127 |
+
else self.text_encoder,
|
| 128 |
+
lora_scale=self.lora_scale,
|
| 129 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
| 130 |
+
adapter_name=adapter_name,
|
| 131 |
+
_pipeline=self,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
@classmethod
|
| 135 |
+
def lora_state_dict(
|
| 136 |
+
cls,
|
| 137 |
+
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
| 138 |
+
**kwargs,
|
| 139 |
+
):
|
| 140 |
+
r"""
|
| 141 |
+
Return state dict for lora weights and the network alphas.
|
| 142 |
+
|
| 143 |
+
<Tip warning={true}>
|
| 144 |
+
|
| 145 |
+
We support loading A1111 formatted LoRA checkpoints in a limited capacity.
|
| 146 |
+
|
| 147 |
+
This function is experimental and might change in the future.
|
| 148 |
+
|
| 149 |
+
</Tip>
|
| 150 |
+
|
| 151 |
+
Parameters:
|
| 152 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
| 153 |
+
Can be either:
|
| 154 |
+
|
| 155 |
+
- A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
| 156 |
+
the Hub.
|
| 157 |
+
- A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
|
| 158 |
+
with [`ModelMixin.save_pretrained`].
|
| 159 |
+
- A [torch state
|
| 160 |
+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
| 161 |
+
|
| 162 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 163 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 164 |
+
is not used.
|
| 165 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 166 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 167 |
+
cached versions if they exist.
|
| 168 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 169 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 170 |
+
incompletely downloaded files are deleted.
|
| 171 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 172 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 173 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 174 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 175 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 176 |
+
won't be downloaded from the Hub.
|
| 177 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 178 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 179 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 180 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 181 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 182 |
+
allowed by Git.
|
| 183 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 184 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
| 185 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 186 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
| 187 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
| 188 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
| 189 |
+
argument to `True` will raise an error.
|
| 190 |
+
mirror (`str`, *optional*):
|
| 191 |
+
Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
|
| 192 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
| 193 |
+
information.
|
| 194 |
+
|
| 195 |
+
"""
|
| 196 |
+
# Load the main state dict first which has the LoRA layers for either of
|
| 197 |
+
# UNet and text encoder or both.
|
| 198 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 199 |
+
force_download = kwargs.pop("force_download", False)
|
| 200 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 201 |
+
proxies = kwargs.pop("proxies", None)
|
| 202 |
+
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
| 203 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 204 |
+
revision = kwargs.pop("revision", None)
|
| 205 |
+
subfolder = kwargs.pop("subfolder", None)
|
| 206 |
+
weight_name = kwargs.pop("weight_name", None)
|
| 207 |
+
unet_config = kwargs.pop("unet_config", None)
|
| 208 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
| 209 |
+
|
| 210 |
+
allow_pickle = False
|
| 211 |
+
if use_safetensors is None:
|
| 212 |
+
use_safetensors = True
|
| 213 |
+
allow_pickle = True
|
| 214 |
+
|
| 215 |
+
user_agent = {
|
| 216 |
+
"file_type": "attn_procs_weights",
|
| 217 |
+
"framework": "pytorch",
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
model_file = None
|
| 221 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
| 222 |
+
# Let's first try to load .safetensors weights
|
| 223 |
+
if (use_safetensors and weight_name is None) or (
|
| 224 |
+
weight_name is not None and weight_name.endswith(".safetensors")
|
| 225 |
+
):
|
| 226 |
+
try:
|
| 227 |
+
# Here we're relaxing the loading check to enable more Inference API
|
| 228 |
+
# friendliness where sometimes, it's not at all possible to automatically
|
| 229 |
+
# determine `weight_name`.
|
| 230 |
+
if weight_name is None:
|
| 231 |
+
weight_name = cls._best_guess_weight_name(
|
| 232 |
+
pretrained_model_name_or_path_or_dict, file_extension=".safetensors"
|
| 233 |
+
)
|
| 234 |
+
model_file = _get_model_file(
|
| 235 |
+
pretrained_model_name_or_path_or_dict,
|
| 236 |
+
weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
|
| 237 |
+
cache_dir=cache_dir,
|
| 238 |
+
force_download=force_download,
|
| 239 |
+
resume_download=resume_download,
|
| 240 |
+
proxies=proxies,
|
| 241 |
+
local_files_only=local_files_only,
|
| 242 |
+
use_auth_token=use_auth_token,
|
| 243 |
+
revision=revision,
|
| 244 |
+
subfolder=subfolder,
|
| 245 |
+
user_agent=user_agent,
|
| 246 |
+
)
|
| 247 |
+
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
| 248 |
+
except (IOError, safetensors.SafetensorError) as e:
|
| 249 |
+
if not allow_pickle:
|
| 250 |
+
raise e
|
| 251 |
+
# try loading non-safetensors weights
|
| 252 |
+
model_file = None
|
| 253 |
+
pass
|
| 254 |
+
|
| 255 |
+
if model_file is None:
|
| 256 |
+
if weight_name is None:
|
| 257 |
+
weight_name = cls._best_guess_weight_name(
|
| 258 |
+
pretrained_model_name_or_path_or_dict, file_extension=".bin"
|
| 259 |
+
)
|
| 260 |
+
model_file = _get_model_file(
|
| 261 |
+
pretrained_model_name_or_path_or_dict,
|
| 262 |
+
weights_name=weight_name or LORA_WEIGHT_NAME,
|
| 263 |
+
cache_dir=cache_dir,
|
| 264 |
+
force_download=force_download,
|
| 265 |
+
resume_download=resume_download,
|
| 266 |
+
proxies=proxies,
|
| 267 |
+
local_files_only=local_files_only,
|
| 268 |
+
use_auth_token=use_auth_token,
|
| 269 |
+
revision=revision,
|
| 270 |
+
subfolder=subfolder,
|
| 271 |
+
user_agent=user_agent,
|
| 272 |
+
)
|
| 273 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 274 |
+
else:
|
| 275 |
+
state_dict = pretrained_model_name_or_path_or_dict
|
| 276 |
+
|
| 277 |
+
network_alphas = None
|
| 278 |
+
# TODO: replace it with a method from `state_dict_utils`
|
| 279 |
+
if all(
|
| 280 |
+
(
|
| 281 |
+
k.startswith("lora_te_")
|
| 282 |
+
or k.startswith("lora_unet_")
|
| 283 |
+
or k.startswith("lora_te1_")
|
| 284 |
+
or k.startswith("lora_te2_")
|
| 285 |
+
)
|
| 286 |
+
for k in state_dict.keys()
|
| 287 |
+
):
|
| 288 |
+
# Map SDXL blocks correctly.
|
| 289 |
+
if unet_config is not None:
|
| 290 |
+
# use unet config to remap block numbers
|
| 291 |
+
state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
|
| 292 |
+
state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
|
| 293 |
+
|
| 294 |
+
return state_dict, network_alphas
|
| 295 |
+
|
| 296 |
+
@classmethod
|
| 297 |
+
def _best_guess_weight_name(cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors"):
|
| 298 |
+
targeted_files = []
|
| 299 |
+
|
| 300 |
+
if os.path.isfile(pretrained_model_name_or_path_or_dict):
|
| 301 |
+
return
|
| 302 |
+
elif os.path.isdir(pretrained_model_name_or_path_or_dict):
|
| 303 |
+
targeted_files = [
|
| 304 |
+
f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
|
| 305 |
+
]
|
| 306 |
+
else:
|
| 307 |
+
files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
|
| 308 |
+
targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
|
| 309 |
+
if len(targeted_files) == 0:
|
| 310 |
+
return
|
| 311 |
+
|
| 312 |
+
# "scheduler" does not correspond to a LoRA checkpoint.
|
| 313 |
+
# "optimizer" does not correspond to a LoRA checkpoint
|
| 314 |
+
# only top-level checkpoints are considered and not the other ones, hence "checkpoint".
|
| 315 |
+
unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
|
| 316 |
+
targeted_files = list(
|
| 317 |
+
filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
|
| 321 |
+
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
|
| 322 |
+
elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
|
| 323 |
+
targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
|
| 324 |
+
|
| 325 |
+
if len(targeted_files) > 1:
|
| 326 |
+
raise ValueError(
|
| 327 |
+
f"Provided path contains more than one weights file in the {file_extension} format. Either specify `weight_name` in `load_lora_weights` or make sure there's only one `.safetensors` or `.bin` file in {pretrained_model_name_or_path_or_dict}."
|
| 328 |
+
)
|
| 329 |
+
weight_name = targeted_files[0]
|
| 330 |
+
return weight_name
|
| 331 |
+
|
| 332 |
+
@classmethod
|
| 333 |
+
def _optionally_disable_offloading(cls, _pipeline):
|
| 334 |
+
"""
|
| 335 |
+
Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
_pipeline (`DiffusionPipeline`):
|
| 339 |
+
The pipeline to disable offloading for.
|
| 340 |
+
|
| 341 |
+
Returns:
|
| 342 |
+
tuple:
|
| 343 |
+
A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
|
| 344 |
+
"""
|
| 345 |
+
is_model_cpu_offload = False
|
| 346 |
+
is_sequential_cpu_offload = False
|
| 347 |
+
|
| 348 |
+
if _pipeline is not None:
|
| 349 |
+
for _, component in _pipeline.components.items():
|
| 350 |
+
if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
|
| 351 |
+
if not is_model_cpu_offload:
|
| 352 |
+
is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
|
| 353 |
+
if not is_sequential_cpu_offload:
|
| 354 |
+
is_sequential_cpu_offload = isinstance(component._hf_hook, AlignDevicesHook)
|
| 355 |
+
|
| 356 |
+
logger.info(
|
| 357 |
+
"Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
|
| 358 |
+
)
|
| 359 |
+
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
| 360 |
+
|
| 361 |
+
return (is_model_cpu_offload, is_sequential_cpu_offload)
|
| 362 |
+
|
| 363 |
+
@classmethod
|
| 364 |
+
def load_lora_into_unet(
|
| 365 |
+
cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
|
| 366 |
+
):
|
| 367 |
+
"""
|
| 368 |
+
This will load the LoRA layers specified in `state_dict` into `unet`.
|
| 369 |
+
|
| 370 |
+
Parameters:
|
| 371 |
+
state_dict (`dict`):
|
| 372 |
+
A standard state dict containing the lora layer parameters. The keys can either be indexed directly
|
| 373 |
+
into the unet or prefixed with an additional `unet` which can be used to distinguish between text
|
| 374 |
+
encoder lora layers.
|
| 375 |
+
network_alphas (`Dict[str, float]`):
|
| 376 |
+
See `LoRALinearLayer` for more details.
|
| 377 |
+
unet (`UNet2DConditionModel`):
|
| 378 |
+
The UNet model to load the LoRA layers into.
|
| 379 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 380 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
| 381 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
| 382 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
| 383 |
+
argument to `True` will raise an error.
|
| 384 |
+
adapter_name (`str`, *optional*):
|
| 385 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
| 386 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
| 387 |
+
"""
|
| 388 |
+
low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
|
| 389 |
+
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
|
| 390 |
+
# then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
|
| 391 |
+
# their prefixes.
|
| 392 |
+
keys = list(state_dict.keys())
|
| 393 |
+
|
| 394 |
+
if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
|
| 395 |
+
# Load the layers corresponding to UNet.
|
| 396 |
+
logger.info(f"Loading {cls.unet_name}.")
|
| 397 |
+
|
| 398 |
+
unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
|
| 399 |
+
state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
|
| 400 |
+
|
| 401 |
+
if network_alphas is not None:
|
| 402 |
+
alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
|
| 403 |
+
network_alphas = {
|
| 404 |
+
k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
else:
|
| 408 |
+
# Otherwise, we're dealing with the old format. This means the `state_dict` should only
|
| 409 |
+
# contain the module names of the `unet` as its keys WITHOUT any prefix.
|
| 410 |
+
warn_message = "You have saved the LoRA weights using the old format. To convert the old LoRA weights to the new format, you can first load them in a dictionary and then create a new dictionary like the following: `new_state_dict = {f'unet.{module_name}': params for module_name, params in old_state_dict.items()}`."
|
| 411 |
+
logger.warn(warn_message)
|
| 412 |
+
|
| 413 |
+
if USE_PEFT_BACKEND and len(state_dict.keys()) > 0:
|
| 414 |
+
from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
|
| 415 |
+
|
| 416 |
+
if adapter_name in getattr(unet, "peft_config", {}):
|
| 417 |
+
raise ValueError(
|
| 418 |
+
f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
state_dict = convert_unet_state_dict_to_peft(state_dict)
|
| 422 |
+
|
| 423 |
+
if network_alphas is not None:
|
| 424 |
+
# The alphas state dict have the same structure as Unet, thus we convert it to peft format using
|
| 425 |
+
# `convert_unet_state_dict_to_peft` method.
|
| 426 |
+
network_alphas = convert_unet_state_dict_to_peft(network_alphas)
|
| 427 |
+
|
| 428 |
+
rank = {}
|
| 429 |
+
for key, val in state_dict.items():
|
| 430 |
+
if "lora_B" in key:
|
| 431 |
+
rank[key] = val.shape[1]
|
| 432 |
+
|
| 433 |
+
lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
|
| 434 |
+
lora_config = LoraConfig(**lora_config_kwargs)
|
| 435 |
+
|
| 436 |
+
# adapter_name
|
| 437 |
+
if adapter_name is None:
|
| 438 |
+
adapter_name = get_adapter_name(unet)
|
| 439 |
+
|
| 440 |
+
# In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
|
| 441 |
+
# otherwise loading LoRA weights will lead to an error
|
| 442 |
+
is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
|
| 443 |
+
|
| 444 |
+
inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
|
| 445 |
+
incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
|
| 446 |
+
|
| 447 |
+
if incompatible_keys is not None:
|
| 448 |
+
# check only for unexpected keys
|
| 449 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
| 450 |
+
if unexpected_keys:
|
| 451 |
+
logger.warning(
|
| 452 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
| 453 |
+
f" {unexpected_keys}. "
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
# Offload back.
|
| 457 |
+
if is_model_cpu_offload:
|
| 458 |
+
_pipeline.enable_model_cpu_offload()
|
| 459 |
+
elif is_sequential_cpu_offload:
|
| 460 |
+
_pipeline.enable_sequential_cpu_offload()
|
| 461 |
+
# Unsafe code />
|
| 462 |
+
|
| 463 |
+
unet.load_attn_procs(
|
| 464 |
+
state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
@classmethod
|
| 468 |
+
def load_lora_into_text_encoder(
|
| 469 |
+
cls,
|
| 470 |
+
state_dict,
|
| 471 |
+
network_alphas,
|
| 472 |
+
text_encoder,
|
| 473 |
+
prefix=None,
|
| 474 |
+
lora_scale=1.0,
|
| 475 |
+
low_cpu_mem_usage=None,
|
| 476 |
+
adapter_name=None,
|
| 477 |
+
_pipeline=None,
|
| 478 |
+
):
|
| 479 |
+
"""
|
| 480 |
+
This will load the LoRA layers specified in `state_dict` into `text_encoder`
|
| 481 |
+
|
| 482 |
+
Parameters:
|
| 483 |
+
state_dict (`dict`):
|
| 484 |
+
A standard state dict containing the lora layer parameters. The key should be prefixed with an
|
| 485 |
+
additional `text_encoder` to distinguish between unet lora layers.
|
| 486 |
+
network_alphas (`Dict[str, float]`):
|
| 487 |
+
See `LoRALinearLayer` for more details.
|
| 488 |
+
text_encoder (`CLIPTextModel`):
|
| 489 |
+
The text encoder model to load the LoRA layers into.
|
| 490 |
+
prefix (`str`):
|
| 491 |
+
Expected prefix of the `text_encoder` in the `state_dict`.
|
| 492 |
+
lora_scale (`float`):
|
| 493 |
+
How much to scale the output of the lora linear layer before it is added with the output of the regular
|
| 494 |
+
lora layer.
|
| 495 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 496 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
| 497 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
| 498 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
| 499 |
+
argument to `True` will raise an error.
|
| 500 |
+
adapter_name (`str`, *optional*):
|
| 501 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
| 502 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
| 503 |
+
"""
|
| 504 |
+
low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
|
| 505 |
+
|
| 506 |
+
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
|
| 507 |
+
# then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
|
| 508 |
+
# their prefixes.
|
| 509 |
+
keys = list(state_dict.keys())
|
| 510 |
+
prefix = cls.text_encoder_name if prefix is None else prefix
|
| 511 |
+
|
| 512 |
+
# Safe prefix to check with.
|
| 513 |
+
if any(cls.text_encoder_name in key for key in keys):
|
| 514 |
+
# Load the layers corresponding to text encoder and make necessary adjustments.
|
| 515 |
+
text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
|
| 516 |
+
text_encoder_lora_state_dict = {
|
| 517 |
+
k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
if len(text_encoder_lora_state_dict) > 0:
|
| 521 |
+
logger.info(f"Loading {prefix}.")
|
| 522 |
+
rank = {}
|
| 523 |
+
text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
|
| 524 |
+
|
| 525 |
+
if USE_PEFT_BACKEND:
|
| 526 |
+
# convert state dict
|
| 527 |
+
text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
|
| 528 |
+
|
| 529 |
+
for name, _ in text_encoder_attn_modules(text_encoder):
|
| 530 |
+
rank_key = f"{name}.out_proj.lora_B.weight"
|
| 531 |
+
rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
|
| 532 |
+
|
| 533 |
+
patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
|
| 534 |
+
if patch_mlp:
|
| 535 |
+
for name, _ in text_encoder_mlp_modules(text_encoder):
|
| 536 |
+
rank_key_fc1 = f"{name}.fc1.lora_B.weight"
|
| 537 |
+
rank_key_fc2 = f"{name}.fc2.lora_B.weight"
|
| 538 |
+
|
| 539 |
+
rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
|
| 540 |
+
rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
|
| 541 |
+
else:
|
| 542 |
+
for name, _ in text_encoder_attn_modules(text_encoder):
|
| 543 |
+
rank_key = f"{name}.out_proj.lora_linear_layer.up.weight"
|
| 544 |
+
rank.update({rank_key: text_encoder_lora_state_dict[rank_key].shape[1]})
|
| 545 |
+
|
| 546 |
+
patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
|
| 547 |
+
if patch_mlp:
|
| 548 |
+
for name, _ in text_encoder_mlp_modules(text_encoder):
|
| 549 |
+
rank_key_fc1 = f"{name}.fc1.lora_linear_layer.up.weight"
|
| 550 |
+
rank_key_fc2 = f"{name}.fc2.lora_linear_layer.up.weight"
|
| 551 |
+
rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
|
| 552 |
+
rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
|
| 553 |
+
|
| 554 |
+
if network_alphas is not None:
|
| 555 |
+
alpha_keys = [
|
| 556 |
+
k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
|
| 557 |
+
]
|
| 558 |
+
network_alphas = {
|
| 559 |
+
k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
if USE_PEFT_BACKEND:
|
| 563 |
+
from peft import LoraConfig
|
| 564 |
+
|
| 565 |
+
lora_config_kwargs = get_peft_kwargs(
|
| 566 |
+
rank, network_alphas, text_encoder_lora_state_dict, is_unet=False
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
lora_config = LoraConfig(**lora_config_kwargs)
|
| 570 |
+
|
| 571 |
+
# adapter_name
|
| 572 |
+
if adapter_name is None:
|
| 573 |
+
adapter_name = get_adapter_name(text_encoder)
|
| 574 |
+
|
| 575 |
+
is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
|
| 576 |
+
|
| 577 |
+
# inject LoRA layers and load the state dict
|
| 578 |
+
# in transformers we automatically check whether the adapter name is already in use or not
|
| 579 |
+
text_encoder.load_adapter(
|
| 580 |
+
adapter_name=adapter_name,
|
| 581 |
+
adapter_state_dict=text_encoder_lora_state_dict,
|
| 582 |
+
peft_config=lora_config,
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
# scale LoRA layers with `lora_scale`
|
| 586 |
+
scale_lora_layers(text_encoder, weight=lora_scale)
|
| 587 |
+
else:
|
| 588 |
+
cls._modify_text_encoder(
|
| 589 |
+
text_encoder,
|
| 590 |
+
lora_scale,
|
| 591 |
+
network_alphas,
|
| 592 |
+
rank=rank,
|
| 593 |
+
patch_mlp=patch_mlp,
|
| 594 |
+
low_cpu_mem_usage=low_cpu_mem_usage,
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
is_pipeline_offloaded = _pipeline is not None and any(
|
| 598 |
+
isinstance(c, torch.nn.Module) and hasattr(c, "_hf_hook")
|
| 599 |
+
for c in _pipeline.components.values()
|
| 600 |
+
)
|
| 601 |
+
if is_pipeline_offloaded and low_cpu_mem_usage:
|
| 602 |
+
low_cpu_mem_usage = True
|
| 603 |
+
logger.info(
|
| 604 |
+
f"Pipeline {_pipeline.__class__} is offloaded. Therefore low cpu mem usage loading is forced."
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
if low_cpu_mem_usage:
|
| 608 |
+
device = next(iter(text_encoder_lora_state_dict.values())).device
|
| 609 |
+
dtype = next(iter(text_encoder_lora_state_dict.values())).dtype
|
| 610 |
+
unexpected_keys = load_model_dict_into_meta(
|
| 611 |
+
text_encoder, text_encoder_lora_state_dict, device=device, dtype=dtype
|
| 612 |
+
)
|
| 613 |
+
else:
|
| 614 |
+
load_state_dict_results = text_encoder.load_state_dict(
|
| 615 |
+
text_encoder_lora_state_dict, strict=False
|
| 616 |
+
)
|
| 617 |
+
unexpected_keys = load_state_dict_results.unexpected_keys
|
| 618 |
+
|
| 619 |
+
if len(unexpected_keys) != 0:
|
| 620 |
+
raise ValueError(
|
| 621 |
+
f"failed to load text encoder state dict, unexpected keys: {load_state_dict_results.unexpected_keys}"
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
# <Unsafe code
|
| 625 |
+
# We can be sure that the following works as all we do is change the dtype and device of the text encoder
|
| 626 |
+
# Now we remove any existing hooks to
|
| 627 |
+
is_model_cpu_offload = False
|
| 628 |
+
is_sequential_cpu_offload = False
|
| 629 |
+
if _pipeline is not None:
|
| 630 |
+
for _, component in _pipeline.components.items():
|
| 631 |
+
if isinstance(component, torch.nn.Module):
|
| 632 |
+
if hasattr(component, "_hf_hook"):
|
| 633 |
+
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
| 634 |
+
is_sequential_cpu_offload = isinstance(
|
| 635 |
+
getattr(component, "_hf_hook"), AlignDevicesHook
|
| 636 |
+
)
|
| 637 |
+
logger.info(
|
| 638 |
+
"Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
|
| 639 |
+
)
|
| 640 |
+
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
| 641 |
+
|
| 642 |
+
text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
|
| 643 |
+
|
| 644 |
+
# Offload back.
|
| 645 |
+
if is_model_cpu_offload:
|
| 646 |
+
_pipeline.enable_model_cpu_offload()
|
| 647 |
+
elif is_sequential_cpu_offload:
|
| 648 |
+
_pipeline.enable_sequential_cpu_offload()
|
| 649 |
+
# Unsafe code />
|
| 650 |
+
|
| 651 |
+
@property
|
| 652 |
+
def lora_scale(self) -> float:
|
| 653 |
+
# property function that returns the lora scale which can be set at run time by the pipeline.
|
| 654 |
+
# if _lora_scale has not been set, return 1
|
| 655 |
+
return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
|
| 656 |
+
|
| 657 |
+
def _remove_text_encoder_monkey_patch(self):
|
| 658 |
+
if USE_PEFT_BACKEND:
|
| 659 |
+
remove_method = recurse_remove_peft_layers
|
| 660 |
+
else:
|
| 661 |
+
remove_method = self._remove_text_encoder_monkey_patch_classmethod
|
| 662 |
+
|
| 663 |
+
if hasattr(self, "text_encoder"):
|
| 664 |
+
remove_method(self.text_encoder)
|
| 665 |
+
|
| 666 |
+
# In case text encoder have no Lora attached
|
| 667 |
+
if USE_PEFT_BACKEND and getattr(self.text_encoder, "peft_config", None) is not None:
|
| 668 |
+
del self.text_encoder.peft_config
|
| 669 |
+
self.text_encoder._hf_peft_config_loaded = None
|
| 670 |
+
if hasattr(self, "text_encoder_2"):
|
| 671 |
+
remove_method(self.text_encoder_2)
|
| 672 |
+
if USE_PEFT_BACKEND:
|
| 673 |
+
del self.text_encoder_2.peft_config
|
| 674 |
+
self.text_encoder_2._hf_peft_config_loaded = None
|
| 675 |
+
|
| 676 |
+
@classmethod
|
| 677 |
+
def _remove_text_encoder_monkey_patch_classmethod(cls, text_encoder):
|
| 678 |
+
if version.parse(__version__) > version.parse("0.23"):
|
| 679 |
+
deprecate("_remove_text_encoder_monkey_patch_classmethod", "0.25", LORA_DEPRECATION_MESSAGE)
|
| 680 |
+
|
| 681 |
+
for _, attn_module in text_encoder_attn_modules(text_encoder):
|
| 682 |
+
if isinstance(attn_module.q_proj, PatchedLoraProjection):
|
| 683 |
+
attn_module.q_proj.lora_linear_layer = None
|
| 684 |
+
attn_module.k_proj.lora_linear_layer = None
|
| 685 |
+
attn_module.v_proj.lora_linear_layer = None
|
| 686 |
+
attn_module.out_proj.lora_linear_layer = None
|
| 687 |
+
|
| 688 |
+
for _, mlp_module in text_encoder_mlp_modules(text_encoder):
|
| 689 |
+
if isinstance(mlp_module.fc1, PatchedLoraProjection):
|
| 690 |
+
mlp_module.fc1.lora_linear_layer = None
|
| 691 |
+
mlp_module.fc2.lora_linear_layer = None
|
| 692 |
+
|
| 693 |
+
@classmethod
|
| 694 |
+
def _modify_text_encoder(
|
| 695 |
+
cls,
|
| 696 |
+
text_encoder,
|
| 697 |
+
lora_scale=1,
|
| 698 |
+
network_alphas=None,
|
| 699 |
+
rank: Union[Dict[str, int], int] = 4,
|
| 700 |
+
dtype=None,
|
| 701 |
+
patch_mlp=False,
|
| 702 |
+
low_cpu_mem_usage=False,
|
| 703 |
+
):
|
| 704 |
+
r"""
|
| 705 |
+
Monkey-patches the forward passes of attention modules of the text encoder.
|
| 706 |
+
"""
|
| 707 |
+
if version.parse(__version__) > version.parse("0.23"):
|
| 708 |
+
deprecate("_modify_text_encoder", "0.25", LORA_DEPRECATION_MESSAGE)
|
| 709 |
+
|
| 710 |
+
def create_patched_linear_lora(model, network_alpha, rank, dtype, lora_parameters):
|
| 711 |
+
linear_layer = model.regular_linear_layer if isinstance(model, PatchedLoraProjection) else model
|
| 712 |
+
ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
|
| 713 |
+
with ctx():
|
| 714 |
+
model = PatchedLoraProjection(linear_layer, lora_scale, network_alpha, rank, dtype=dtype)
|
| 715 |
+
|
| 716 |
+
lora_parameters.extend(model.lora_linear_layer.parameters())
|
| 717 |
+
return model
|
| 718 |
+
|
| 719 |
+
# First, remove any monkey-patch that might have been applied before
|
| 720 |
+
cls._remove_text_encoder_monkey_patch_classmethod(text_encoder)
|
| 721 |
+
|
| 722 |
+
lora_parameters = []
|
| 723 |
+
network_alphas = {} if network_alphas is None else network_alphas
|
| 724 |
+
is_network_alphas_populated = len(network_alphas) > 0
|
| 725 |
+
|
| 726 |
+
for name, attn_module in text_encoder_attn_modules(text_encoder):
|
| 727 |
+
query_alpha = network_alphas.pop(name + ".to_q_lora.down.weight.alpha", None)
|
| 728 |
+
key_alpha = network_alphas.pop(name + ".to_k_lora.down.weight.alpha", None)
|
| 729 |
+
value_alpha = network_alphas.pop(name + ".to_v_lora.down.weight.alpha", None)
|
| 730 |
+
out_alpha = network_alphas.pop(name + ".to_out_lora.down.weight.alpha", None)
|
| 731 |
+
|
| 732 |
+
if isinstance(rank, dict):
|
| 733 |
+
current_rank = rank.pop(f"{name}.out_proj.lora_linear_layer.up.weight")
|
| 734 |
+
else:
|
| 735 |
+
current_rank = rank
|
| 736 |
+
|
| 737 |
+
attn_module.q_proj = create_patched_linear_lora(
|
| 738 |
+
attn_module.q_proj, query_alpha, current_rank, dtype, lora_parameters
|
| 739 |
+
)
|
| 740 |
+
attn_module.k_proj = create_patched_linear_lora(
|
| 741 |
+
attn_module.k_proj, key_alpha, current_rank, dtype, lora_parameters
|
| 742 |
+
)
|
| 743 |
+
attn_module.v_proj = create_patched_linear_lora(
|
| 744 |
+
attn_module.v_proj, value_alpha, current_rank, dtype, lora_parameters
|
| 745 |
+
)
|
| 746 |
+
attn_module.out_proj = create_patched_linear_lora(
|
| 747 |
+
attn_module.out_proj, out_alpha, current_rank, dtype, lora_parameters
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
if patch_mlp:
|
| 751 |
+
for name, mlp_module in text_encoder_mlp_modules(text_encoder):
|
| 752 |
+
fc1_alpha = network_alphas.pop(name + ".fc1.lora_linear_layer.down.weight.alpha", None)
|
| 753 |
+
fc2_alpha = network_alphas.pop(name + ".fc2.lora_linear_layer.down.weight.alpha", None)
|
| 754 |
+
|
| 755 |
+
current_rank_fc1 = rank.pop(f"{name}.fc1.lora_linear_layer.up.weight")
|
| 756 |
+
current_rank_fc2 = rank.pop(f"{name}.fc2.lora_linear_layer.up.weight")
|
| 757 |
+
|
| 758 |
+
mlp_module.fc1 = create_patched_linear_lora(
|
| 759 |
+
mlp_module.fc1, fc1_alpha, current_rank_fc1, dtype, lora_parameters
|
| 760 |
+
)
|
| 761 |
+
mlp_module.fc2 = create_patched_linear_lora(
|
| 762 |
+
mlp_module.fc2, fc2_alpha, current_rank_fc2, dtype, lora_parameters
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
if is_network_alphas_populated and len(network_alphas) > 0:
|
| 766 |
+
raise ValueError(
|
| 767 |
+
f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
return lora_parameters
|
| 771 |
+
|
| 772 |
+
@classmethod
|
| 773 |
+
def save_lora_weights(
|
| 774 |
+
cls,
|
| 775 |
+
save_directory: Union[str, os.PathLike],
|
| 776 |
+
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 777 |
+
text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
|
| 778 |
+
is_main_process: bool = True,
|
| 779 |
+
weight_name: str = None,
|
| 780 |
+
save_function: Callable = None,
|
| 781 |
+
safe_serialization: bool = True,
|
| 782 |
+
):
|
| 783 |
+
r"""
|
| 784 |
+
Save the LoRA parameters corresponding to the UNet and text encoder.
|
| 785 |
+
|
| 786 |
+
Arguments:
|
| 787 |
+
save_directory (`str` or `os.PathLike`):
|
| 788 |
+
Directory to save LoRA parameters to. Will be created if it doesn't exist.
|
| 789 |
+
unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
| 790 |
+
State dict of the LoRA layers corresponding to the `unet`.
|
| 791 |
+
text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
| 792 |
+
State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
|
| 793 |
+
encoder LoRA state dict because it comes from 🤗 Transformers.
|
| 794 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
| 795 |
+
Whether the process calling this is the main process or not. Useful during distributed training and you
|
| 796 |
+
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
| 797 |
+
process to avoid race conditions.
|
| 798 |
+
save_function (`Callable`):
|
| 799 |
+
The function to use to save the state dictionary. Useful during distributed training when you need to
|
| 800 |
+
replace `torch.save` with another method. Can be configured with the environment variable
|
| 801 |
+
`DIFFUSERS_SAVE_MODE`.
|
| 802 |
+
safe_serialization (`bool`, *optional*, defaults to `True`):
|
| 803 |
+
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
| 804 |
+
"""
|
| 805 |
+
# Create a flat dictionary.
|
| 806 |
+
state_dict = {}
|
| 807 |
+
|
| 808 |
+
# Populate the dictionary.
|
| 809 |
+
if unet_lora_layers is not None:
|
| 810 |
+
weights = (
|
| 811 |
+
unet_lora_layers.state_dict() if isinstance(unet_lora_layers, torch.nn.Module) else unet_lora_layers
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
unet_lora_state_dict = {f"{cls.unet_name}.{module_name}": param for module_name, param in weights.items()}
|
| 815 |
+
state_dict.update(unet_lora_state_dict)
|
| 816 |
+
|
| 817 |
+
if text_encoder_lora_layers is not None:
|
| 818 |
+
weights = (
|
| 819 |
+
text_encoder_lora_layers.state_dict()
|
| 820 |
+
if isinstance(text_encoder_lora_layers, torch.nn.Module)
|
| 821 |
+
else text_encoder_lora_layers
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
text_encoder_lora_state_dict = {
|
| 825 |
+
f"{cls.text_encoder_name}.{module_name}": param for module_name, param in weights.items()
|
| 826 |
+
}
|
| 827 |
+
state_dict.update(text_encoder_lora_state_dict)
|
| 828 |
+
|
| 829 |
+
# Save the model
|
| 830 |
+
cls.write_lora_layers(
|
| 831 |
+
state_dict=state_dict,
|
| 832 |
+
save_directory=save_directory,
|
| 833 |
+
is_main_process=is_main_process,
|
| 834 |
+
weight_name=weight_name,
|
| 835 |
+
save_function=save_function,
|
| 836 |
+
safe_serialization=safe_serialization,
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
@staticmethod
|
| 840 |
+
def write_lora_layers(
|
| 841 |
+
state_dict: Dict[str, torch.Tensor],
|
| 842 |
+
save_directory: str,
|
| 843 |
+
is_main_process: bool,
|
| 844 |
+
weight_name: str,
|
| 845 |
+
save_function: Callable,
|
| 846 |
+
safe_serialization: bool,
|
| 847 |
+
):
|
| 848 |
+
if os.path.isfile(save_directory):
|
| 849 |
+
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
| 850 |
+
return
|
| 851 |
+
|
| 852 |
+
if save_function is None:
|
| 853 |
+
if safe_serialization:
|
| 854 |
+
|
| 855 |
+
def save_function(weights, filename):
|
| 856 |
+
return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
|
| 857 |
+
|
| 858 |
+
else:
|
| 859 |
+
save_function = torch.save
|
| 860 |
+
|
| 861 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 862 |
+
|
| 863 |
+
if weight_name is None:
|
| 864 |
+
if safe_serialization:
|
| 865 |
+
weight_name = LORA_WEIGHT_NAME_SAFE
|
| 866 |
+
else:
|
| 867 |
+
weight_name = LORA_WEIGHT_NAME
|
| 868 |
+
|
| 869 |
+
save_function(state_dict, os.path.join(save_directory, weight_name))
|
| 870 |
+
logger.info(f"Model weights saved in {os.path.join(save_directory, weight_name)}")
|
| 871 |
+
|
| 872 |
+
def unload_lora_weights(self):
|
| 873 |
+
"""
|
| 874 |
+
Unloads the LoRA parameters.
|
| 875 |
+
|
| 876 |
+
Examples:
|
| 877 |
+
|
| 878 |
+
```python
|
| 879 |
+
>>> # Assuming `pipeline` is already loaded with the LoRA parameters.
|
| 880 |
+
>>> pipeline.unload_lora_weights()
|
| 881 |
+
>>> ...
|
| 882 |
+
```
|
| 883 |
+
"""
|
| 884 |
+
if not USE_PEFT_BACKEND:
|
| 885 |
+
if version.parse(__version__) > version.parse("0.23"):
|
| 886 |
+
logger.warn(
|
| 887 |
+
"You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
|
| 888 |
+
"you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
for _, module in self.unet.named_modules():
|
| 892 |
+
if hasattr(module, "set_lora_layer"):
|
| 893 |
+
module.set_lora_layer(None)
|
| 894 |
+
else:
|
| 895 |
+
recurse_remove_peft_layers(self.unet)
|
| 896 |
+
if hasattr(self.unet, "peft_config"):
|
| 897 |
+
del self.unet.peft_config
|
| 898 |
+
|
| 899 |
+
# Safe to call the following regardless of LoRA.
|
| 900 |
+
self._remove_text_encoder_monkey_patch()
|
| 901 |
+
|
| 902 |
+
def fuse_lora(
|
| 903 |
+
self,
|
| 904 |
+
fuse_unet: bool = True,
|
| 905 |
+
fuse_text_encoder: bool = True,
|
| 906 |
+
lora_scale: float = 1.0,
|
| 907 |
+
safe_fusing: bool = False,
|
| 908 |
+
):
|
| 909 |
+
r"""
|
| 910 |
+
Fuses the LoRA parameters into the original parameters of the corresponding blocks.
|
| 911 |
+
|
| 912 |
+
<Tip warning={true}>
|
| 913 |
+
|
| 914 |
+
This is an experimental API.
|
| 915 |
+
|
| 916 |
+
</Tip>
|
| 917 |
+
|
| 918 |
+
Args:
|
| 919 |
+
fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
|
| 920 |
+
fuse_text_encoder (`bool`, defaults to `True`):
|
| 921 |
+
Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
|
| 922 |
+
LoRA parameters then it won't have any effect.
|
| 923 |
+
lora_scale (`float`, defaults to 1.0):
|
| 924 |
+
Controls how much to influence the outputs with the LoRA parameters.
|
| 925 |
+
safe_fusing (`bool`, defaults to `False`):
|
| 926 |
+
Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
|
| 927 |
+
"""
|
| 928 |
+
if fuse_unet or fuse_text_encoder:
|
| 929 |
+
self.num_fused_loras += 1
|
| 930 |
+
if self.num_fused_loras > 1:
|
| 931 |
+
logger.warn(
|
| 932 |
+
"The current API is supported for operating with a single LoRA file. You are trying to load and fuse more than one LoRA which is not well-supported.",
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
if fuse_unet:
|
| 936 |
+
self.unet.fuse_lora(lora_scale, safe_fusing=safe_fusing)
|
| 937 |
+
|
| 938 |
+
if USE_PEFT_BACKEND:
|
| 939 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 940 |
+
|
| 941 |
+
def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False):
|
| 942 |
+
# TODO(Patrick, Younes): enable "safe" fusing
|
| 943 |
+
for module in text_encoder.modules():
|
| 944 |
+
if isinstance(module, BaseTunerLayer):
|
| 945 |
+
if lora_scale != 1.0:
|
| 946 |
+
module.scale_layer(lora_scale)
|
| 947 |
+
|
| 948 |
+
module.merge()
|
| 949 |
+
|
| 950 |
+
else:
|
| 951 |
+
if version.parse(__version__) > version.parse("0.23"):
|
| 952 |
+
deprecate("fuse_text_encoder_lora", "0.25", LORA_DEPRECATION_MESSAGE)
|
| 953 |
+
|
| 954 |
+
def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False):
|
| 955 |
+
for _, attn_module in text_encoder_attn_modules(text_encoder):
|
| 956 |
+
if isinstance(attn_module.q_proj, PatchedLoraProjection):
|
| 957 |
+
attn_module.q_proj._fuse_lora(lora_scale, safe_fusing)
|
| 958 |
+
attn_module.k_proj._fuse_lora(lora_scale, safe_fusing)
|
| 959 |
+
attn_module.v_proj._fuse_lora(lora_scale, safe_fusing)
|
| 960 |
+
attn_module.out_proj._fuse_lora(lora_scale, safe_fusing)
|
| 961 |
+
|
| 962 |
+
for _, mlp_module in text_encoder_mlp_modules(text_encoder):
|
| 963 |
+
if isinstance(mlp_module.fc1, PatchedLoraProjection):
|
| 964 |
+
mlp_module.fc1._fuse_lora(lora_scale, safe_fusing)
|
| 965 |
+
mlp_module.fc2._fuse_lora(lora_scale, safe_fusing)
|
| 966 |
+
|
| 967 |
+
if fuse_text_encoder:
|
| 968 |
+
if hasattr(self, "text_encoder"):
|
| 969 |
+
fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing)
|
| 970 |
+
if hasattr(self, "text_encoder_2"):
|
| 971 |
+
fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing)
|
| 972 |
+
|
| 973 |
+
def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
|
| 974 |
+
r"""
|
| 975 |
+
Reverses the effect of
|
| 976 |
+
[`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
|
| 977 |
+
|
| 978 |
+
<Tip warning={true}>
|
| 979 |
+
|
| 980 |
+
This is an experimental API.
|
| 981 |
+
|
| 982 |
+
</Tip>
|
| 983 |
+
|
| 984 |
+
Args:
|
| 985 |
+
unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
|
| 986 |
+
unfuse_text_encoder (`bool`, defaults to `True`):
|
| 987 |
+
Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
|
| 988 |
+
LoRA parameters then it won't have any effect.
|
| 989 |
+
"""
|
| 990 |
+
if unfuse_unet:
|
| 991 |
+
if not USE_PEFT_BACKEND:
|
| 992 |
+
self.unet.unfuse_lora()
|
| 993 |
+
else:
|
| 994 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 995 |
+
|
| 996 |
+
for module in self.unet.modules():
|
| 997 |
+
if isinstance(module, BaseTunerLayer):
|
| 998 |
+
module.unmerge()
|
| 999 |
+
|
| 1000 |
+
if USE_PEFT_BACKEND:
|
| 1001 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 1002 |
+
|
| 1003 |
+
def unfuse_text_encoder_lora(text_encoder):
|
| 1004 |
+
for module in text_encoder.modules():
|
| 1005 |
+
if isinstance(module, BaseTunerLayer):
|
| 1006 |
+
module.unmerge()
|
| 1007 |
+
|
| 1008 |
+
else:
|
| 1009 |
+
if version.parse(__version__) > version.parse("0.23"):
|
| 1010 |
+
deprecate("unfuse_text_encoder_lora", "0.25", LORA_DEPRECATION_MESSAGE)
|
| 1011 |
+
|
| 1012 |
+
def unfuse_text_encoder_lora(text_encoder):
|
| 1013 |
+
for _, attn_module in text_encoder_attn_modules(text_encoder):
|
| 1014 |
+
if isinstance(attn_module.q_proj, PatchedLoraProjection):
|
| 1015 |
+
attn_module.q_proj._unfuse_lora()
|
| 1016 |
+
attn_module.k_proj._unfuse_lora()
|
| 1017 |
+
attn_module.v_proj._unfuse_lora()
|
| 1018 |
+
attn_module.out_proj._unfuse_lora()
|
| 1019 |
+
|
| 1020 |
+
for _, mlp_module in text_encoder_mlp_modules(text_encoder):
|
| 1021 |
+
if isinstance(mlp_module.fc1, PatchedLoraProjection):
|
| 1022 |
+
mlp_module.fc1._unfuse_lora()
|
| 1023 |
+
mlp_module.fc2._unfuse_lora()
|
| 1024 |
+
|
| 1025 |
+
if unfuse_text_encoder:
|
| 1026 |
+
if hasattr(self, "text_encoder"):
|
| 1027 |
+
unfuse_text_encoder_lora(self.text_encoder)
|
| 1028 |
+
if hasattr(self, "text_encoder_2"):
|
| 1029 |
+
unfuse_text_encoder_lora(self.text_encoder_2)
|
| 1030 |
+
|
| 1031 |
+
self.num_fused_loras -= 1
|
| 1032 |
+
|
| 1033 |
+
def set_adapters_for_text_encoder(
|
| 1034 |
+
self,
|
| 1035 |
+
adapter_names: Union[List[str], str],
|
| 1036 |
+
text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
|
| 1037 |
+
text_encoder_weights: List[float] = None,
|
| 1038 |
+
):
|
| 1039 |
+
"""
|
| 1040 |
+
Sets the adapter layers for the text encoder.
|
| 1041 |
+
|
| 1042 |
+
Args:
|
| 1043 |
+
adapter_names (`List[str]` or `str`):
|
| 1044 |
+
The names of the adapters to use.
|
| 1045 |
+
text_encoder (`torch.nn.Module`, *optional*):
|
| 1046 |
+
The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
|
| 1047 |
+
attribute.
|
| 1048 |
+
text_encoder_weights (`List[float]`, *optional*):
|
| 1049 |
+
The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
|
| 1050 |
+
"""
|
| 1051 |
+
if not USE_PEFT_BACKEND:
|
| 1052 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 1053 |
+
|
| 1054 |
+
def process_weights(adapter_names, weights):
|
| 1055 |
+
if weights is None:
|
| 1056 |
+
weights = [1.0] * len(adapter_names)
|
| 1057 |
+
elif isinstance(weights, float):
|
| 1058 |
+
weights = [weights]
|
| 1059 |
+
|
| 1060 |
+
if len(adapter_names) != len(weights):
|
| 1061 |
+
raise ValueError(
|
| 1062 |
+
f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
|
| 1063 |
+
)
|
| 1064 |
+
return weights
|
| 1065 |
+
|
| 1066 |
+
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
| 1067 |
+
text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
|
| 1068 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
| 1069 |
+
if text_encoder is None:
|
| 1070 |
+
raise ValueError(
|
| 1071 |
+
"The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
|
| 1072 |
+
)
|
| 1073 |
+
set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
|
| 1074 |
+
|
| 1075 |
+
def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
|
| 1076 |
+
"""
|
| 1077 |
+
Disables the LoRA layers for the text encoder.
|
| 1078 |
+
|
| 1079 |
+
Args:
|
| 1080 |
+
text_encoder (`torch.nn.Module`, *optional*):
|
| 1081 |
+
The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
|
| 1082 |
+
`text_encoder` attribute.
|
| 1083 |
+
"""
|
| 1084 |
+
if not USE_PEFT_BACKEND:
|
| 1085 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 1086 |
+
|
| 1087 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
| 1088 |
+
if text_encoder is None:
|
| 1089 |
+
raise ValueError("Text Encoder not found.")
|
| 1090 |
+
set_adapter_layers(text_encoder, enabled=False)
|
| 1091 |
+
|
| 1092 |
+
def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
|
| 1093 |
+
"""
|
| 1094 |
+
Enables the LoRA layers for the text encoder.
|
| 1095 |
+
|
| 1096 |
+
Args:
|
| 1097 |
+
text_encoder (`torch.nn.Module`, *optional*):
|
| 1098 |
+
The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
|
| 1099 |
+
attribute.
|
| 1100 |
+
"""
|
| 1101 |
+
if not USE_PEFT_BACKEND:
|
| 1102 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 1103 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
| 1104 |
+
if text_encoder is None:
|
| 1105 |
+
raise ValueError("Text Encoder not found.")
|
| 1106 |
+
set_adapter_layers(self.text_encoder, enabled=True)
|
| 1107 |
+
|
| 1108 |
+
def set_adapters(
|
| 1109 |
+
self,
|
| 1110 |
+
adapter_names: Union[List[str], str],
|
| 1111 |
+
adapter_weights: Optional[List[float]] = None,
|
| 1112 |
+
):
|
| 1113 |
+
# Handle the UNET
|
| 1114 |
+
self.unet.set_adapters(adapter_names, adapter_weights)
|
| 1115 |
+
|
| 1116 |
+
# Handle the Text Encoder
|
| 1117 |
+
if hasattr(self, "text_encoder"):
|
| 1118 |
+
self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, adapter_weights)
|
| 1119 |
+
if hasattr(self, "text_encoder_2"):
|
| 1120 |
+
self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, adapter_weights)
|
| 1121 |
+
|
| 1122 |
+
def disable_lora(self):
|
| 1123 |
+
if not USE_PEFT_BACKEND:
|
| 1124 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 1125 |
+
|
| 1126 |
+
# Disable unet adapters
|
| 1127 |
+
self.unet.disable_lora()
|
| 1128 |
+
|
| 1129 |
+
# Disable text encoder adapters
|
| 1130 |
+
if hasattr(self, "text_encoder"):
|
| 1131 |
+
self.disable_lora_for_text_encoder(self.text_encoder)
|
| 1132 |
+
if hasattr(self, "text_encoder_2"):
|
| 1133 |
+
self.disable_lora_for_text_encoder(self.text_encoder_2)
|
| 1134 |
+
|
| 1135 |
+
def enable_lora(self):
|
| 1136 |
+
if not USE_PEFT_BACKEND:
|
| 1137 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 1138 |
+
|
| 1139 |
+
# Enable unet adapters
|
| 1140 |
+
self.unet.enable_lora()
|
| 1141 |
+
|
| 1142 |
+
# Enable text encoder adapters
|
| 1143 |
+
if hasattr(self, "text_encoder"):
|
| 1144 |
+
self.enable_lora_for_text_encoder(self.text_encoder)
|
| 1145 |
+
if hasattr(self, "text_encoder_2"):
|
| 1146 |
+
self.enable_lora_for_text_encoder(self.text_encoder_2)
|
| 1147 |
+
|
| 1148 |
+
def delete_adapters(self, adapter_names: Union[List[str], str]):
|
| 1149 |
+
"""
|
| 1150 |
+
Args:
|
| 1151 |
+
Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
|
| 1152 |
+
adapter_names (`Union[List[str], str]`):
|
| 1153 |
+
The names of the adapter to delete. Can be a single string or a list of strings
|
| 1154 |
+
"""
|
| 1155 |
+
if not USE_PEFT_BACKEND:
|
| 1156 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 1157 |
+
|
| 1158 |
+
if isinstance(adapter_names, str):
|
| 1159 |
+
adapter_names = [adapter_names]
|
| 1160 |
+
|
| 1161 |
+
# Delete unet adapters
|
| 1162 |
+
self.unet.delete_adapters(adapter_names)
|
| 1163 |
+
|
| 1164 |
+
for adapter_name in adapter_names:
|
| 1165 |
+
# Delete text encoder adapters
|
| 1166 |
+
if hasattr(self, "text_encoder"):
|
| 1167 |
+
delete_adapter_layers(self.text_encoder, adapter_name)
|
| 1168 |
+
if hasattr(self, "text_encoder_2"):
|
| 1169 |
+
delete_adapter_layers(self.text_encoder_2, adapter_name)
|
| 1170 |
+
|
| 1171 |
+
def get_active_adapters(self) -> List[str]:
|
| 1172 |
+
"""
|
| 1173 |
+
Gets the list of the current active adapters.
|
| 1174 |
+
|
| 1175 |
+
Example:
|
| 1176 |
+
|
| 1177 |
+
```python
|
| 1178 |
+
from diffusers import DiffusionPipeline
|
| 1179 |
+
|
| 1180 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 1181 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 1182 |
+
).to("cuda")
|
| 1183 |
+
pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
|
| 1184 |
+
pipeline.get_active_adapters()
|
| 1185 |
+
```
|
| 1186 |
+
"""
|
| 1187 |
+
if not USE_PEFT_BACKEND:
|
| 1188 |
+
raise ValueError(
|
| 1189 |
+
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 1193 |
+
|
| 1194 |
+
active_adapters = []
|
| 1195 |
+
|
| 1196 |
+
for module in self.unet.modules():
|
| 1197 |
+
if isinstance(module, BaseTunerLayer):
|
| 1198 |
+
active_adapters = module.active_adapters
|
| 1199 |
+
break
|
| 1200 |
+
|
| 1201 |
+
return active_adapters
|
| 1202 |
+
|
| 1203 |
+
def get_list_adapters(self) -> Dict[str, List[str]]:
|
| 1204 |
+
"""
|
| 1205 |
+
Gets the current list of all available adapters in the pipeline.
|
| 1206 |
+
"""
|
| 1207 |
+
if not USE_PEFT_BACKEND:
|
| 1208 |
+
raise ValueError(
|
| 1209 |
+
"PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
set_adapters = {}
|
| 1213 |
+
|
| 1214 |
+
if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
|
| 1215 |
+
set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
|
| 1216 |
+
|
| 1217 |
+
if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
|
| 1218 |
+
set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
|
| 1219 |
+
|
| 1220 |
+
if hasattr(self, "unet") and hasattr(self.unet, "peft_config"):
|
| 1221 |
+
set_adapters["unet"] = list(self.unet.peft_config.keys())
|
| 1222 |
+
|
| 1223 |
+
return set_adapters
|
| 1224 |
+
|
| 1225 |
+
def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
|
| 1226 |
+
"""
|
| 1227 |
+
Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
|
| 1228 |
+
you want to load multiple adapters and free some GPU memory.
|
| 1229 |
+
|
| 1230 |
+
Args:
|
| 1231 |
+
adapter_names (`List[str]`):
|
| 1232 |
+
List of adapters to send device to.
|
| 1233 |
+
device (`Union[torch.device, str, int]`):
|
| 1234 |
+
Device to send the adapters to. Can be either a torch device, a str or an integer.
|
| 1235 |
+
"""
|
| 1236 |
+
if not USE_PEFT_BACKEND:
|
| 1237 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 1238 |
+
|
| 1239 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 1240 |
+
|
| 1241 |
+
# Handle the UNET
|
| 1242 |
+
for unet_module in self.unet.modules():
|
| 1243 |
+
if isinstance(unet_module, BaseTunerLayer):
|
| 1244 |
+
for adapter_name in adapter_names:
|
| 1245 |
+
unet_module.lora_A[adapter_name].to(device)
|
| 1246 |
+
unet_module.lora_B[adapter_name].to(device)
|
| 1247 |
+
|
| 1248 |
+
# Handle the text encoder
|
| 1249 |
+
modules_to_process = []
|
| 1250 |
+
if hasattr(self, "text_encoder"):
|
| 1251 |
+
modules_to_process.append(self.text_encoder)
|
| 1252 |
+
|
| 1253 |
+
if hasattr(self, "text_encoder_2"):
|
| 1254 |
+
modules_to_process.append(self.text_encoder_2)
|
| 1255 |
+
|
| 1256 |
+
for text_encoder in modules_to_process:
|
| 1257 |
+
# loop over submodules
|
| 1258 |
+
for text_encoder_module in text_encoder.modules():
|
| 1259 |
+
if isinstance(text_encoder_module, BaseTunerLayer):
|
| 1260 |
+
for adapter_name in adapter_names:
|
| 1261 |
+
text_encoder_module.lora_A[adapter_name].to(device)
|
| 1262 |
+
text_encoder_module.lora_B[adapter_name].to(device)
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
|
| 1266 |
+
"""This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
|
| 1267 |
+
|
| 1268 |
+
# Overrride to properly handle the loading and unloading of the additional text encoder.
|
| 1269 |
+
def load_lora_weights(
|
| 1270 |
+
self,
|
| 1271 |
+
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
| 1272 |
+
adapter_name: Optional[str] = None,
|
| 1273 |
+
**kwargs,
|
| 1274 |
+
):
|
| 1275 |
+
"""
|
| 1276 |
+
Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
|
| 1277 |
+
`self.text_encoder`.
|
| 1278 |
+
|
| 1279 |
+
All kwargs are forwarded to `self.lora_state_dict`.
|
| 1280 |
+
|
| 1281 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
|
| 1282 |
+
|
| 1283 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
|
| 1284 |
+
`self.unet`.
|
| 1285 |
+
|
| 1286 |
+
See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
|
| 1287 |
+
into `self.text_encoder`.
|
| 1288 |
+
|
| 1289 |
+
Parameters:
|
| 1290 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
| 1291 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
| 1292 |
+
adapter_name (`str`, *optional*):
|
| 1293 |
+
Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
|
| 1294 |
+
`default_{i}` where i is the total number of adapters being loaded.
|
| 1295 |
+
kwargs (`dict`, *optional*):
|
| 1296 |
+
See [`~loaders.LoraLoaderMixin.lora_state_dict`].
|
| 1297 |
+
"""
|
| 1298 |
+
# We could have accessed the unet config from `lora_state_dict()` too. We pass
|
| 1299 |
+
# it here explicitly to be able to tell that it's coming from an SDXL
|
| 1300 |
+
# pipeline.
|
| 1301 |
+
|
| 1302 |
+
# First, ensure that the checkpoint is a compatible one and can be successfully loaded.
|
| 1303 |
+
state_dict, network_alphas = self.lora_state_dict(
|
| 1304 |
+
pretrained_model_name_or_path_or_dict,
|
| 1305 |
+
unet_config=self.unet.config,
|
| 1306 |
+
**kwargs,
|
| 1307 |
+
)
|
| 1308 |
+
is_correct_format = all("lora" in key for key in state_dict.keys())
|
| 1309 |
+
if not is_correct_format:
|
| 1310 |
+
raise ValueError("Invalid LoRA checkpoint.")
|
| 1311 |
+
|
| 1312 |
+
self.load_lora_into_unet(
|
| 1313 |
+
state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
|
| 1314 |
+
)
|
| 1315 |
+
text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
|
| 1316 |
+
if len(text_encoder_state_dict) > 0:
|
| 1317 |
+
self.load_lora_into_text_encoder(
|
| 1318 |
+
text_encoder_state_dict,
|
| 1319 |
+
network_alphas=network_alphas,
|
| 1320 |
+
text_encoder=self.text_encoder,
|
| 1321 |
+
prefix="text_encoder",
|
| 1322 |
+
lora_scale=self.lora_scale,
|
| 1323 |
+
adapter_name=adapter_name,
|
| 1324 |
+
_pipeline=self,
|
| 1325 |
+
)
|
| 1326 |
+
|
| 1327 |
+
text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
|
| 1328 |
+
if len(text_encoder_2_state_dict) > 0:
|
| 1329 |
+
self.load_lora_into_text_encoder(
|
| 1330 |
+
text_encoder_2_state_dict,
|
| 1331 |
+
network_alphas=network_alphas,
|
| 1332 |
+
text_encoder=self.text_encoder_2,
|
| 1333 |
+
prefix="text_encoder_2",
|
| 1334 |
+
lora_scale=self.lora_scale,
|
| 1335 |
+
adapter_name=adapter_name,
|
| 1336 |
+
_pipeline=self,
|
| 1337 |
+
)
|
| 1338 |
+
|
| 1339 |
+
@classmethod
|
| 1340 |
+
def save_lora_weights(
|
| 1341 |
+
cls,
|
| 1342 |
+
save_directory: Union[str, os.PathLike],
|
| 1343 |
+
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 1344 |
+
text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 1345 |
+
text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 1346 |
+
is_main_process: bool = True,
|
| 1347 |
+
weight_name: str = None,
|
| 1348 |
+
save_function: Callable = None,
|
| 1349 |
+
safe_serialization: bool = True,
|
| 1350 |
+
):
|
| 1351 |
+
r"""
|
| 1352 |
+
Save the LoRA parameters corresponding to the UNet and text encoder.
|
| 1353 |
+
|
| 1354 |
+
Arguments:
|
| 1355 |
+
save_directory (`str` or `os.PathLike`):
|
| 1356 |
+
Directory to save LoRA parameters to. Will be created if it doesn't exist.
|
| 1357 |
+
unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
| 1358 |
+
State dict of the LoRA layers corresponding to the `unet`.
|
| 1359 |
+
text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
|
| 1360 |
+
State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
|
| 1361 |
+
encoder LoRA state dict because it comes from 🤗 Transformers.
|
| 1362 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
| 1363 |
+
Whether the process calling this is the main process or not. Useful during distributed training and you
|
| 1364 |
+
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
| 1365 |
+
process to avoid race conditions.
|
| 1366 |
+
save_function (`Callable`):
|
| 1367 |
+
The function to use to save the state dictionary. Useful during distributed training when you need to
|
| 1368 |
+
replace `torch.save` with another method. Can be configured with the environment variable
|
| 1369 |
+
`DIFFUSERS_SAVE_MODE`.
|
| 1370 |
+
safe_serialization (`bool`, *optional*, defaults to `True`):
|
| 1371 |
+
Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
|
| 1372 |
+
"""
|
| 1373 |
+
state_dict = {}
|
| 1374 |
+
|
| 1375 |
+
def pack_weights(layers, prefix):
|
| 1376 |
+
layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
| 1377 |
+
layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
|
| 1378 |
+
return layers_state_dict
|
| 1379 |
+
|
| 1380 |
+
if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
|
| 1381 |
+
raise ValueError(
|
| 1382 |
+
"You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
|
| 1383 |
+
)
|
| 1384 |
+
|
| 1385 |
+
if unet_lora_layers:
|
| 1386 |
+
state_dict.update(pack_weights(unet_lora_layers, "unet"))
|
| 1387 |
+
|
| 1388 |
+
if text_encoder_lora_layers and text_encoder_2_lora_layers:
|
| 1389 |
+
state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
|
| 1390 |
+
state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
|
| 1391 |
+
|
| 1392 |
+
cls.write_lora_layers(
|
| 1393 |
+
state_dict=state_dict,
|
| 1394 |
+
save_directory=save_directory,
|
| 1395 |
+
is_main_process=is_main_process,
|
| 1396 |
+
weight_name=weight_name,
|
| 1397 |
+
save_function=save_function,
|
| 1398 |
+
safe_serialization=safe_serialization,
|
| 1399 |
+
)
|
| 1400 |
+
|
| 1401 |
+
def _remove_text_encoder_monkey_patch(self):
|
| 1402 |
+
if USE_PEFT_BACKEND:
|
| 1403 |
+
recurse_remove_peft_layers(self.text_encoder)
|
| 1404 |
+
# TODO: @younesbelkada handle this in transformers side
|
| 1405 |
+
if getattr(self.text_encoder, "peft_config", None) is not None:
|
| 1406 |
+
del self.text_encoder.peft_config
|
| 1407 |
+
self.text_encoder._hf_peft_config_loaded = None
|
| 1408 |
+
|
| 1409 |
+
recurse_remove_peft_layers(self.text_encoder_2)
|
| 1410 |
+
if getattr(self.text_encoder_2, "peft_config", None) is not None:
|
| 1411 |
+
del self.text_encoder_2.peft_config
|
| 1412 |
+
self.text_encoder_2._hf_peft_config_loaded = None
|
| 1413 |
+
else:
|
| 1414 |
+
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
|
| 1415 |
+
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
|
diffusers/loaders/lora_conversion_utils.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import re
|
| 16 |
+
|
| 17 |
+
from ..utils import logging
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
logger = logging.get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config, delimiter="_", block_slice_pos=5):
|
| 24 |
+
# 1. get all state_dict_keys
|
| 25 |
+
all_keys = list(state_dict.keys())
|
| 26 |
+
sgm_patterns = ["input_blocks", "middle_block", "output_blocks"]
|
| 27 |
+
|
| 28 |
+
# 2. check if needs remapping, if not return original dict
|
| 29 |
+
is_in_sgm_format = False
|
| 30 |
+
for key in all_keys:
|
| 31 |
+
if any(p in key for p in sgm_patterns):
|
| 32 |
+
is_in_sgm_format = True
|
| 33 |
+
break
|
| 34 |
+
|
| 35 |
+
if not is_in_sgm_format:
|
| 36 |
+
return state_dict
|
| 37 |
+
|
| 38 |
+
# 3. Else remap from SGM patterns
|
| 39 |
+
new_state_dict = {}
|
| 40 |
+
inner_block_map = ["resnets", "attentions", "upsamplers"]
|
| 41 |
+
|
| 42 |
+
# Retrieves # of down, mid and up blocks
|
| 43 |
+
input_block_ids, middle_block_ids, output_block_ids = set(), set(), set()
|
| 44 |
+
|
| 45 |
+
for layer in all_keys:
|
| 46 |
+
if "text" in layer:
|
| 47 |
+
new_state_dict[layer] = state_dict.pop(layer)
|
| 48 |
+
else:
|
| 49 |
+
layer_id = int(layer.split(delimiter)[:block_slice_pos][-1])
|
| 50 |
+
if sgm_patterns[0] in layer:
|
| 51 |
+
input_block_ids.add(layer_id)
|
| 52 |
+
elif sgm_patterns[1] in layer:
|
| 53 |
+
middle_block_ids.add(layer_id)
|
| 54 |
+
elif sgm_patterns[2] in layer:
|
| 55 |
+
output_block_ids.add(layer_id)
|
| 56 |
+
else:
|
| 57 |
+
raise ValueError(f"Checkpoint not supported because layer {layer} not supported.")
|
| 58 |
+
|
| 59 |
+
input_blocks = {
|
| 60 |
+
layer_id: [key for key in state_dict if f"input_blocks{delimiter}{layer_id}" in key]
|
| 61 |
+
for layer_id in input_block_ids
|
| 62 |
+
}
|
| 63 |
+
middle_blocks = {
|
| 64 |
+
layer_id: [key for key in state_dict if f"middle_block{delimiter}{layer_id}" in key]
|
| 65 |
+
for layer_id in middle_block_ids
|
| 66 |
+
}
|
| 67 |
+
output_blocks = {
|
| 68 |
+
layer_id: [key for key in state_dict if f"output_blocks{delimiter}{layer_id}" in key]
|
| 69 |
+
for layer_id in output_block_ids
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
# Rename keys accordingly
|
| 73 |
+
for i in input_block_ids:
|
| 74 |
+
block_id = (i - 1) // (unet_config.layers_per_block + 1)
|
| 75 |
+
layer_in_block_id = (i - 1) % (unet_config.layers_per_block + 1)
|
| 76 |
+
|
| 77 |
+
for key in input_blocks[i]:
|
| 78 |
+
inner_block_id = int(key.split(delimiter)[block_slice_pos])
|
| 79 |
+
inner_block_key = inner_block_map[inner_block_id] if "op" not in key else "downsamplers"
|
| 80 |
+
inner_layers_in_block = str(layer_in_block_id) if "op" not in key else "0"
|
| 81 |
+
new_key = delimiter.join(
|
| 82 |
+
key.split(delimiter)[: block_slice_pos - 1]
|
| 83 |
+
+ [str(block_id), inner_block_key, inner_layers_in_block]
|
| 84 |
+
+ key.split(delimiter)[block_slice_pos + 1 :]
|
| 85 |
+
)
|
| 86 |
+
new_state_dict[new_key] = state_dict.pop(key)
|
| 87 |
+
|
| 88 |
+
for i in middle_block_ids:
|
| 89 |
+
key_part = None
|
| 90 |
+
if i == 0:
|
| 91 |
+
key_part = [inner_block_map[0], "0"]
|
| 92 |
+
elif i == 1:
|
| 93 |
+
key_part = [inner_block_map[1], "0"]
|
| 94 |
+
elif i == 2:
|
| 95 |
+
key_part = [inner_block_map[0], "1"]
|
| 96 |
+
else:
|
| 97 |
+
raise ValueError(f"Invalid middle block id {i}.")
|
| 98 |
+
|
| 99 |
+
for key in middle_blocks[i]:
|
| 100 |
+
new_key = delimiter.join(
|
| 101 |
+
key.split(delimiter)[: block_slice_pos - 1] + key_part + key.split(delimiter)[block_slice_pos:]
|
| 102 |
+
)
|
| 103 |
+
new_state_dict[new_key] = state_dict.pop(key)
|
| 104 |
+
|
| 105 |
+
for i in output_block_ids:
|
| 106 |
+
block_id = i // (unet_config.layers_per_block + 1)
|
| 107 |
+
layer_in_block_id = i % (unet_config.layers_per_block + 1)
|
| 108 |
+
|
| 109 |
+
for key in output_blocks[i]:
|
| 110 |
+
inner_block_id = int(key.split(delimiter)[block_slice_pos])
|
| 111 |
+
inner_block_key = inner_block_map[inner_block_id]
|
| 112 |
+
inner_layers_in_block = str(layer_in_block_id) if inner_block_id < 2 else "0"
|
| 113 |
+
new_key = delimiter.join(
|
| 114 |
+
key.split(delimiter)[: block_slice_pos - 1]
|
| 115 |
+
+ [str(block_id), inner_block_key, inner_layers_in_block]
|
| 116 |
+
+ key.split(delimiter)[block_slice_pos + 1 :]
|
| 117 |
+
)
|
| 118 |
+
new_state_dict[new_key] = state_dict.pop(key)
|
| 119 |
+
|
| 120 |
+
if len(state_dict) > 0:
|
| 121 |
+
raise ValueError("At this point all state dict entries have to be converted.")
|
| 122 |
+
|
| 123 |
+
return new_state_dict
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _convert_kohya_lora_to_diffusers(state_dict, unet_name="unet", text_encoder_name="text_encoder"):
|
| 127 |
+
unet_state_dict = {}
|
| 128 |
+
te_state_dict = {}
|
| 129 |
+
te2_state_dict = {}
|
| 130 |
+
network_alphas = {}
|
| 131 |
+
|
| 132 |
+
# every down weight has a corresponding up weight and potentially an alpha weight
|
| 133 |
+
lora_keys = [k for k in state_dict.keys() if k.endswith("lora_down.weight")]
|
| 134 |
+
for key in lora_keys:
|
| 135 |
+
lora_name = key.split(".")[0]
|
| 136 |
+
lora_name_up = lora_name + ".lora_up.weight"
|
| 137 |
+
lora_name_alpha = lora_name + ".alpha"
|
| 138 |
+
|
| 139 |
+
if lora_name.startswith("lora_unet_"):
|
| 140 |
+
diffusers_name = key.replace("lora_unet_", "").replace("_", ".")
|
| 141 |
+
|
| 142 |
+
if "input.blocks" in diffusers_name:
|
| 143 |
+
diffusers_name = diffusers_name.replace("input.blocks", "down_blocks")
|
| 144 |
+
else:
|
| 145 |
+
diffusers_name = diffusers_name.replace("down.blocks", "down_blocks")
|
| 146 |
+
|
| 147 |
+
if "middle.block" in diffusers_name:
|
| 148 |
+
diffusers_name = diffusers_name.replace("middle.block", "mid_block")
|
| 149 |
+
else:
|
| 150 |
+
diffusers_name = diffusers_name.replace("mid.block", "mid_block")
|
| 151 |
+
if "output.blocks" in diffusers_name:
|
| 152 |
+
diffusers_name = diffusers_name.replace("output.blocks", "up_blocks")
|
| 153 |
+
else:
|
| 154 |
+
diffusers_name = diffusers_name.replace("up.blocks", "up_blocks")
|
| 155 |
+
|
| 156 |
+
diffusers_name = diffusers_name.replace("transformer.blocks", "transformer_blocks")
|
| 157 |
+
diffusers_name = diffusers_name.replace("to.q.lora", "to_q_lora")
|
| 158 |
+
diffusers_name = diffusers_name.replace("to.k.lora", "to_k_lora")
|
| 159 |
+
diffusers_name = diffusers_name.replace("to.v.lora", "to_v_lora")
|
| 160 |
+
diffusers_name = diffusers_name.replace("to.out.0.lora", "to_out_lora")
|
| 161 |
+
diffusers_name = diffusers_name.replace("proj.in", "proj_in")
|
| 162 |
+
diffusers_name = diffusers_name.replace("proj.out", "proj_out")
|
| 163 |
+
diffusers_name = diffusers_name.replace("emb.layers", "time_emb_proj")
|
| 164 |
+
|
| 165 |
+
# SDXL specificity.
|
| 166 |
+
if "emb" in diffusers_name and "time.emb.proj" not in diffusers_name:
|
| 167 |
+
pattern = r"\.\d+(?=\D*$)"
|
| 168 |
+
diffusers_name = re.sub(pattern, "", diffusers_name, count=1)
|
| 169 |
+
if ".in." in diffusers_name:
|
| 170 |
+
diffusers_name = diffusers_name.replace("in.layers.2", "conv1")
|
| 171 |
+
if ".out." in diffusers_name:
|
| 172 |
+
diffusers_name = diffusers_name.replace("out.layers.3", "conv2")
|
| 173 |
+
if "downsamplers" in diffusers_name or "upsamplers" in diffusers_name:
|
| 174 |
+
diffusers_name = diffusers_name.replace("op", "conv")
|
| 175 |
+
if "skip" in diffusers_name:
|
| 176 |
+
diffusers_name = diffusers_name.replace("skip.connection", "conv_shortcut")
|
| 177 |
+
|
| 178 |
+
# LyCORIS specificity.
|
| 179 |
+
if "time.emb.proj" in diffusers_name:
|
| 180 |
+
diffusers_name = diffusers_name.replace("time.emb.proj", "time_emb_proj")
|
| 181 |
+
if "conv.shortcut" in diffusers_name:
|
| 182 |
+
diffusers_name = diffusers_name.replace("conv.shortcut", "conv_shortcut")
|
| 183 |
+
|
| 184 |
+
# General coverage.
|
| 185 |
+
if "transformer_blocks" in diffusers_name:
|
| 186 |
+
if "attn1" in diffusers_name or "attn2" in diffusers_name:
|
| 187 |
+
diffusers_name = diffusers_name.replace("attn1", "attn1.processor")
|
| 188 |
+
diffusers_name = diffusers_name.replace("attn2", "attn2.processor")
|
| 189 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
| 190 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 191 |
+
elif "ff" in diffusers_name:
|
| 192 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
| 193 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 194 |
+
elif any(key in diffusers_name for key in ("proj_in", "proj_out")):
|
| 195 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
| 196 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 197 |
+
else:
|
| 198 |
+
unet_state_dict[diffusers_name] = state_dict.pop(key)
|
| 199 |
+
unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 200 |
+
|
| 201 |
+
elif lora_name.startswith("lora_te_"):
|
| 202 |
+
diffusers_name = key.replace("lora_te_", "").replace("_", ".")
|
| 203 |
+
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
| 204 |
+
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
| 205 |
+
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
| 206 |
+
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
| 207 |
+
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
| 208 |
+
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
| 209 |
+
if "self_attn" in diffusers_name:
|
| 210 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
| 211 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 212 |
+
elif "mlp" in diffusers_name:
|
| 213 |
+
# Be aware that this is the new diffusers convention and the rest of the code might
|
| 214 |
+
# not utilize it yet.
|
| 215 |
+
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
| 216 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
| 217 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 218 |
+
|
| 219 |
+
# (sayakpaul): Duplicate code. Needs to be cleaned.
|
| 220 |
+
elif lora_name.startswith("lora_te1_"):
|
| 221 |
+
diffusers_name = key.replace("lora_te1_", "").replace("_", ".")
|
| 222 |
+
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
| 223 |
+
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
| 224 |
+
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
| 225 |
+
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
| 226 |
+
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
| 227 |
+
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
| 228 |
+
if "self_attn" in diffusers_name:
|
| 229 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
| 230 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 231 |
+
elif "mlp" in diffusers_name:
|
| 232 |
+
# Be aware that this is the new diffusers convention and the rest of the code might
|
| 233 |
+
# not utilize it yet.
|
| 234 |
+
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
| 235 |
+
te_state_dict[diffusers_name] = state_dict.pop(key)
|
| 236 |
+
te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 237 |
+
|
| 238 |
+
# (sayakpaul): Duplicate code. Needs to be cleaned.
|
| 239 |
+
elif lora_name.startswith("lora_te2_"):
|
| 240 |
+
diffusers_name = key.replace("lora_te2_", "").replace("_", ".")
|
| 241 |
+
diffusers_name = diffusers_name.replace("text.model", "text_model")
|
| 242 |
+
diffusers_name = diffusers_name.replace("self.attn", "self_attn")
|
| 243 |
+
diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
|
| 244 |
+
diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
|
| 245 |
+
diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
|
| 246 |
+
diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
|
| 247 |
+
if "self_attn" in diffusers_name:
|
| 248 |
+
te2_state_dict[diffusers_name] = state_dict.pop(key)
|
| 249 |
+
te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 250 |
+
elif "mlp" in diffusers_name:
|
| 251 |
+
# Be aware that this is the new diffusers convention and the rest of the code might
|
| 252 |
+
# not utilize it yet.
|
| 253 |
+
diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
|
| 254 |
+
te2_state_dict[diffusers_name] = state_dict.pop(key)
|
| 255 |
+
te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
|
| 256 |
+
|
| 257 |
+
# Rename the alphas so that they can be mapped appropriately.
|
| 258 |
+
if lora_name_alpha in state_dict:
|
| 259 |
+
alpha = state_dict.pop(lora_name_alpha).item()
|
| 260 |
+
if lora_name_alpha.startswith("lora_unet_"):
|
| 261 |
+
prefix = "unet."
|
| 262 |
+
elif lora_name_alpha.startswith(("lora_te_", "lora_te1_")):
|
| 263 |
+
prefix = "text_encoder."
|
| 264 |
+
else:
|
| 265 |
+
prefix = "text_encoder_2."
|
| 266 |
+
new_name = prefix + diffusers_name.split(".lora.")[0] + ".alpha"
|
| 267 |
+
network_alphas.update({new_name: alpha})
|
| 268 |
+
|
| 269 |
+
if len(state_dict) > 0:
|
| 270 |
+
raise ValueError(f"The following keys have not been correctly be renamed: \n\n {', '.join(state_dict.keys())}")
|
| 271 |
+
|
| 272 |
+
logger.info("Kohya-style checkpoint detected.")
|
| 273 |
+
unet_state_dict = {f"{unet_name}.{module_name}": params for module_name, params in unet_state_dict.items()}
|
| 274 |
+
te_state_dict = {f"{text_encoder_name}.{module_name}": params for module_name, params in te_state_dict.items()}
|
| 275 |
+
te2_state_dict = (
|
| 276 |
+
{f"text_encoder_2.{module_name}": params for module_name, params in te2_state_dict.items()}
|
| 277 |
+
if len(te2_state_dict) > 0
|
| 278 |
+
else None
|
| 279 |
+
)
|
| 280 |
+
if te2_state_dict is not None:
|
| 281 |
+
te_state_dict.update(te2_state_dict)
|
| 282 |
+
|
| 283 |
+
new_state_dict = {**unet_state_dict, **te_state_dict}
|
| 284 |
+
return new_state_dict, network_alphas
|
diffusers/loaders/single_file.py
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from contextlib import nullcontext
|
| 15 |
+
from io import BytesIO
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import requests
|
| 19 |
+
import torch
|
| 20 |
+
from huggingface_hub import hf_hub_download
|
| 21 |
+
|
| 22 |
+
from ..utils import (
|
| 23 |
+
DIFFUSERS_CACHE,
|
| 24 |
+
HF_HUB_OFFLINE,
|
| 25 |
+
deprecate,
|
| 26 |
+
is_accelerate_available,
|
| 27 |
+
is_omegaconf_available,
|
| 28 |
+
is_transformers_available,
|
| 29 |
+
logging,
|
| 30 |
+
)
|
| 31 |
+
from ..utils.import_utils import BACKENDS_MAPPING
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_transformers_available():
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
if is_accelerate_available():
|
| 38 |
+
from accelerate import init_empty_weights
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class FromSingleFileMixin:
|
| 44 |
+
"""
|
| 45 |
+
Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def from_ckpt(cls, *args, **kwargs):
|
| 50 |
+
deprecation_message = "The function `from_ckpt` is deprecated in favor of `from_single_file` and will be removed in diffusers v.0.21. Please make sure to use `StableDiffusionPipeline.from_single_file(...)` instead."
|
| 51 |
+
deprecate("from_ckpt", "0.21.0", deprecation_message, standard_warn=False)
|
| 52 |
+
return cls.from_single_file(*args, **kwargs)
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
| 56 |
+
r"""
|
| 57 |
+
Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
|
| 58 |
+
format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 59 |
+
|
| 60 |
+
Parameters:
|
| 61 |
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
| 62 |
+
Can be either:
|
| 63 |
+
- A link to the `.ckpt` file (for example
|
| 64 |
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
| 65 |
+
- A path to a *file* containing all pipeline weights.
|
| 66 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
| 67 |
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
| 68 |
+
dtype is automatically derived from the model's weights.
|
| 69 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 70 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 71 |
+
cached versions if they exist.
|
| 72 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 73 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 74 |
+
is not used.
|
| 75 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 76 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 77 |
+
incompletely downloaded files are deleted.
|
| 78 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 79 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 80 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 81 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 82 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 83 |
+
won't be downloaded from the Hub.
|
| 84 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 85 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 86 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 87 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 88 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 89 |
+
allowed by Git.
|
| 90 |
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
| 91 |
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
| 92 |
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
| 93 |
+
weights. If set to `False`, safetensors weights are not loaded.
|
| 94 |
+
extract_ema (`bool`, *optional*, defaults to `False`):
|
| 95 |
+
Whether to extract the EMA weights or not. Pass `True` to extract the EMA weights which usually yield
|
| 96 |
+
higher quality images for inference. Non-EMA weights are usually better for continuing finetuning.
|
| 97 |
+
upcast_attention (`bool`, *optional*, defaults to `None`):
|
| 98 |
+
Whether the attention computation should always be upcasted.
|
| 99 |
+
image_size (`int`, *optional*, defaults to 512):
|
| 100 |
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
| 101 |
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
| 102 |
+
prediction_type (`str`, *optional*):
|
| 103 |
+
The prediction type the model was trained on. Use `'epsilon'` for all Stable Diffusion v1 models and
|
| 104 |
+
the Stable Diffusion v2 base model. Use `'v_prediction'` for Stable Diffusion v2.
|
| 105 |
+
num_in_channels (`int`, *optional*, defaults to `None`):
|
| 106 |
+
The number of input channels. If `None`, it is automatically inferred.
|
| 107 |
+
scheduler_type (`str`, *optional*, defaults to `"pndm"`):
|
| 108 |
+
Type of scheduler to use. Should be one of `["pndm", "lms", "heun", "euler", "euler-ancestral", "dpm",
|
| 109 |
+
"ddim"]`.
|
| 110 |
+
load_safety_checker (`bool`, *optional*, defaults to `True`):
|
| 111 |
+
Whether to load the safety checker or not.
|
| 112 |
+
text_encoder ([`~transformers.CLIPTextModel`], *optional*, defaults to `None`):
|
| 113 |
+
An instance of `CLIPTextModel` to use, specifically the
|
| 114 |
+
[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. If this
|
| 115 |
+
parameter is `None`, the function loads a new instance of `CLIPTextModel` by itself if needed.
|
| 116 |
+
vae (`AutoencoderKL`, *optional*, defaults to `None`):
|
| 117 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. If
|
| 118 |
+
this parameter is `None`, the function will load a new instance of [CLIP] by itself, if needed.
|
| 119 |
+
tokenizer ([`~transformers.CLIPTokenizer`], *optional*, defaults to `None`):
|
| 120 |
+
An instance of `CLIPTokenizer` to use. If this parameter is `None`, the function loads a new instance
|
| 121 |
+
of `CLIPTokenizer` by itself if needed.
|
| 122 |
+
original_config_file (`str`):
|
| 123 |
+
Path to `.yaml` config file corresponding to the original architecture. If `None`, will be
|
| 124 |
+
automatically inferred by looking for a key that only exists in SD2.0 models.
|
| 125 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 126 |
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
| 127 |
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
| 128 |
+
method. See example below for more information.
|
| 129 |
+
|
| 130 |
+
Examples:
|
| 131 |
+
|
| 132 |
+
```py
|
| 133 |
+
>>> from diffusers import StableDiffusionPipeline
|
| 134 |
+
|
| 135 |
+
>>> # Download pipeline from huggingface.co and cache.
|
| 136 |
+
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
| 137 |
+
... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
|
| 138 |
+
... )
|
| 139 |
+
|
| 140 |
+
>>> # Download pipeline from local file
|
| 141 |
+
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
|
| 142 |
+
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
|
| 143 |
+
|
| 144 |
+
>>> # Enable float16 and move to GPU
|
| 145 |
+
>>> pipeline = StableDiffusionPipeline.from_single_file(
|
| 146 |
+
... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
|
| 147 |
+
... torch_dtype=torch.float16,
|
| 148 |
+
... )
|
| 149 |
+
>>> pipeline.to("cuda")
|
| 150 |
+
```
|
| 151 |
+
"""
|
| 152 |
+
# import here to avoid circular dependency
|
| 153 |
+
from ..pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
|
| 154 |
+
|
| 155 |
+
original_config_file = kwargs.pop("original_config_file", None)
|
| 156 |
+
config_files = kwargs.pop("config_files", None)
|
| 157 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 158 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 159 |
+
force_download = kwargs.pop("force_download", False)
|
| 160 |
+
proxies = kwargs.pop("proxies", None)
|
| 161 |
+
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
| 162 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 163 |
+
revision = kwargs.pop("revision", None)
|
| 164 |
+
extract_ema = kwargs.pop("extract_ema", False)
|
| 165 |
+
image_size = kwargs.pop("image_size", None)
|
| 166 |
+
scheduler_type = kwargs.pop("scheduler_type", "pndm")
|
| 167 |
+
num_in_channels = kwargs.pop("num_in_channels", None)
|
| 168 |
+
upcast_attention = kwargs.pop("upcast_attention", None)
|
| 169 |
+
load_safety_checker = kwargs.pop("load_safety_checker", True)
|
| 170 |
+
prediction_type = kwargs.pop("prediction_type", None)
|
| 171 |
+
text_encoder = kwargs.pop("text_encoder", None)
|
| 172 |
+
vae = kwargs.pop("vae", None)
|
| 173 |
+
controlnet = kwargs.pop("controlnet", None)
|
| 174 |
+
adapter = kwargs.pop("adapter", None)
|
| 175 |
+
tokenizer = kwargs.pop("tokenizer", None)
|
| 176 |
+
|
| 177 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
| 178 |
+
|
| 179 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
| 180 |
+
|
| 181 |
+
pipeline_name = cls.__name__
|
| 182 |
+
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
| 183 |
+
from_safetensors = file_extension == "safetensors"
|
| 184 |
+
|
| 185 |
+
if from_safetensors and use_safetensors is False:
|
| 186 |
+
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
| 187 |
+
|
| 188 |
+
# TODO: For now we only support stable diffusion
|
| 189 |
+
stable_unclip = None
|
| 190 |
+
model_type = None
|
| 191 |
+
|
| 192 |
+
if pipeline_name in [
|
| 193 |
+
"StableDiffusionControlNetPipeline",
|
| 194 |
+
"StableDiffusionControlNetImg2ImgPipeline",
|
| 195 |
+
"StableDiffusionControlNetInpaintPipeline",
|
| 196 |
+
]:
|
| 197 |
+
from ..models.controlnet import ControlNetModel
|
| 198 |
+
from ..pipelines.controlnet.multicontrolnet import MultiControlNetModel
|
| 199 |
+
|
| 200 |
+
# list/tuple or a single instance of ControlNetModel or MultiControlNetModel
|
| 201 |
+
if not (
|
| 202 |
+
isinstance(controlnet, (ControlNetModel, MultiControlNetModel))
|
| 203 |
+
or isinstance(controlnet, (list, tuple))
|
| 204 |
+
and isinstance(controlnet[0], ControlNetModel)
|
| 205 |
+
):
|
| 206 |
+
raise ValueError("ControlNet needs to be passed if loading from ControlNet pipeline.")
|
| 207 |
+
elif "StableDiffusion" in pipeline_name:
|
| 208 |
+
# Model type will be inferred from the checkpoint.
|
| 209 |
+
pass
|
| 210 |
+
elif pipeline_name == "StableUnCLIPPipeline":
|
| 211 |
+
model_type = "FrozenOpenCLIPEmbedder"
|
| 212 |
+
stable_unclip = "txt2img"
|
| 213 |
+
elif pipeline_name == "StableUnCLIPImg2ImgPipeline":
|
| 214 |
+
model_type = "FrozenOpenCLIPEmbedder"
|
| 215 |
+
stable_unclip = "img2img"
|
| 216 |
+
elif pipeline_name == "PaintByExamplePipeline":
|
| 217 |
+
model_type = "PaintByExample"
|
| 218 |
+
elif pipeline_name == "LDMTextToImagePipeline":
|
| 219 |
+
model_type = "LDMTextToImage"
|
| 220 |
+
else:
|
| 221 |
+
raise ValueError(f"Unhandled pipeline class: {pipeline_name}")
|
| 222 |
+
|
| 223 |
+
# remove huggingface url
|
| 224 |
+
has_valid_url_prefix = False
|
| 225 |
+
valid_url_prefixes = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
|
| 226 |
+
for prefix in valid_url_prefixes:
|
| 227 |
+
if pretrained_model_link_or_path.startswith(prefix):
|
| 228 |
+
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
| 229 |
+
has_valid_url_prefix = True
|
| 230 |
+
|
| 231 |
+
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
| 232 |
+
ckpt_path = Path(pretrained_model_link_or_path)
|
| 233 |
+
if not ckpt_path.is_file():
|
| 234 |
+
if not has_valid_url_prefix:
|
| 235 |
+
raise ValueError(
|
| 236 |
+
f"The provided path is either not a file or a valid huggingface URL was not provided. Valid URLs begin with {', '.join(valid_url_prefixes)}"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# get repo_id and (potentially nested) file path of ckpt in repo
|
| 240 |
+
repo_id = "/".join(ckpt_path.parts[:2])
|
| 241 |
+
file_path = "/".join(ckpt_path.parts[2:])
|
| 242 |
+
|
| 243 |
+
if file_path.startswith("blob/"):
|
| 244 |
+
file_path = file_path[len("blob/") :]
|
| 245 |
+
|
| 246 |
+
if file_path.startswith("main/"):
|
| 247 |
+
file_path = file_path[len("main/") :]
|
| 248 |
+
|
| 249 |
+
pretrained_model_link_or_path = hf_hub_download(
|
| 250 |
+
repo_id,
|
| 251 |
+
filename=file_path,
|
| 252 |
+
cache_dir=cache_dir,
|
| 253 |
+
resume_download=resume_download,
|
| 254 |
+
proxies=proxies,
|
| 255 |
+
local_files_only=local_files_only,
|
| 256 |
+
use_auth_token=use_auth_token,
|
| 257 |
+
revision=revision,
|
| 258 |
+
force_download=force_download,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
pipe = download_from_original_stable_diffusion_ckpt(
|
| 262 |
+
pretrained_model_link_or_path,
|
| 263 |
+
pipeline_class=cls,
|
| 264 |
+
model_type=model_type,
|
| 265 |
+
stable_unclip=stable_unclip,
|
| 266 |
+
controlnet=controlnet,
|
| 267 |
+
adapter=adapter,
|
| 268 |
+
from_safetensors=from_safetensors,
|
| 269 |
+
extract_ema=extract_ema,
|
| 270 |
+
image_size=image_size,
|
| 271 |
+
scheduler_type=scheduler_type,
|
| 272 |
+
num_in_channels=num_in_channels,
|
| 273 |
+
upcast_attention=upcast_attention,
|
| 274 |
+
load_safety_checker=load_safety_checker,
|
| 275 |
+
prediction_type=prediction_type,
|
| 276 |
+
text_encoder=text_encoder,
|
| 277 |
+
vae=vae,
|
| 278 |
+
tokenizer=tokenizer,
|
| 279 |
+
original_config_file=original_config_file,
|
| 280 |
+
config_files=config_files,
|
| 281 |
+
local_files_only=local_files_only,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
if torch_dtype is not None:
|
| 285 |
+
pipe.to(torch_dtype=torch_dtype)
|
| 286 |
+
|
| 287 |
+
return pipe
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class FromOriginalVAEMixin:
|
| 291 |
+
"""
|
| 292 |
+
Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into an [`AutoencoderKL`].
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
@classmethod
|
| 296 |
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
| 297 |
+
r"""
|
| 298 |
+
Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
|
| 299 |
+
`.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 300 |
+
|
| 301 |
+
Parameters:
|
| 302 |
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
| 303 |
+
Can be either:
|
| 304 |
+
- A link to the `.ckpt` file (for example
|
| 305 |
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
| 306 |
+
- A path to a *file* containing all pipeline weights.
|
| 307 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
| 308 |
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
| 309 |
+
dtype is automatically derived from the model's weights.
|
| 310 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 311 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 312 |
+
cached versions if they exist.
|
| 313 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 314 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 315 |
+
is not used.
|
| 316 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 317 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 318 |
+
incompletely downloaded files are deleted.
|
| 319 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 320 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 321 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 322 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 323 |
+
Whether to only load local model weights and configuration files or not. If set to True, the model
|
| 324 |
+
won't be downloaded from the Hub.
|
| 325 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 326 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 327 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 328 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 329 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 330 |
+
allowed by Git.
|
| 331 |
+
image_size (`int`, *optional*, defaults to 512):
|
| 332 |
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
| 333 |
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
| 334 |
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
| 335 |
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
| 336 |
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
| 337 |
+
weights. If set to `False`, safetensors weights are not loaded.
|
| 338 |
+
upcast_attention (`bool`, *optional*, defaults to `None`):
|
| 339 |
+
Whether the attention computation should always be upcasted.
|
| 340 |
+
scaling_factor (`float`, *optional*, defaults to 0.18215):
|
| 341 |
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
| 342 |
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
| 343 |
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
| 344 |
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
|
| 345 |
+
= 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
|
| 346 |
+
Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
| 347 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 348 |
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
| 349 |
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
| 350 |
+
method. See example below for more information.
|
| 351 |
+
|
| 352 |
+
<Tip warning={true}>
|
| 353 |
+
|
| 354 |
+
Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
|
| 355 |
+
a VAE from SDXL or a Stable Diffusion v2 model or higher.
|
| 356 |
+
|
| 357 |
+
</Tip>
|
| 358 |
+
|
| 359 |
+
Examples:
|
| 360 |
+
|
| 361 |
+
```py
|
| 362 |
+
from diffusers import AutoencoderKL
|
| 363 |
+
|
| 364 |
+
url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
|
| 365 |
+
model = AutoencoderKL.from_single_file(url)
|
| 366 |
+
```
|
| 367 |
+
"""
|
| 368 |
+
if not is_omegaconf_available():
|
| 369 |
+
raise ValueError(BACKENDS_MAPPING["omegaconf"][1])
|
| 370 |
+
|
| 371 |
+
from omegaconf import OmegaConf
|
| 372 |
+
|
| 373 |
+
from ..models import AutoencoderKL
|
| 374 |
+
|
| 375 |
+
# import here to avoid circular dependency
|
| 376 |
+
from ..pipelines.stable_diffusion.convert_from_ckpt import (
|
| 377 |
+
convert_ldm_vae_checkpoint,
|
| 378 |
+
create_vae_diffusers_config,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
config_file = kwargs.pop("config_file", None)
|
| 382 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 383 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 384 |
+
force_download = kwargs.pop("force_download", False)
|
| 385 |
+
proxies = kwargs.pop("proxies", None)
|
| 386 |
+
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
| 387 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 388 |
+
revision = kwargs.pop("revision", None)
|
| 389 |
+
image_size = kwargs.pop("image_size", None)
|
| 390 |
+
scaling_factor = kwargs.pop("scaling_factor", None)
|
| 391 |
+
kwargs.pop("upcast_attention", None)
|
| 392 |
+
|
| 393 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
| 394 |
+
|
| 395 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
| 396 |
+
|
| 397 |
+
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
| 398 |
+
from_safetensors = file_extension == "safetensors"
|
| 399 |
+
|
| 400 |
+
if from_safetensors and use_safetensors is False:
|
| 401 |
+
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
| 402 |
+
|
| 403 |
+
# remove huggingface url
|
| 404 |
+
for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
|
| 405 |
+
if pretrained_model_link_or_path.startswith(prefix):
|
| 406 |
+
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
| 407 |
+
|
| 408 |
+
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
| 409 |
+
ckpt_path = Path(pretrained_model_link_or_path)
|
| 410 |
+
if not ckpt_path.is_file():
|
| 411 |
+
# get repo_id and (potentially nested) file path of ckpt in repo
|
| 412 |
+
repo_id = "/".join(ckpt_path.parts[:2])
|
| 413 |
+
file_path = "/".join(ckpt_path.parts[2:])
|
| 414 |
+
|
| 415 |
+
if file_path.startswith("blob/"):
|
| 416 |
+
file_path = file_path[len("blob/") :]
|
| 417 |
+
|
| 418 |
+
if file_path.startswith("main/"):
|
| 419 |
+
file_path = file_path[len("main/") :]
|
| 420 |
+
|
| 421 |
+
pretrained_model_link_or_path = hf_hub_download(
|
| 422 |
+
repo_id,
|
| 423 |
+
filename=file_path,
|
| 424 |
+
cache_dir=cache_dir,
|
| 425 |
+
resume_download=resume_download,
|
| 426 |
+
proxies=proxies,
|
| 427 |
+
local_files_only=local_files_only,
|
| 428 |
+
use_auth_token=use_auth_token,
|
| 429 |
+
revision=revision,
|
| 430 |
+
force_download=force_download,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
if from_safetensors:
|
| 434 |
+
from safetensors import safe_open
|
| 435 |
+
|
| 436 |
+
checkpoint = {}
|
| 437 |
+
with safe_open(pretrained_model_link_or_path, framework="pt", device="cpu") as f:
|
| 438 |
+
for key in f.keys():
|
| 439 |
+
checkpoint[key] = f.get_tensor(key)
|
| 440 |
+
else:
|
| 441 |
+
checkpoint = torch.load(pretrained_model_link_or_path, map_location="cpu")
|
| 442 |
+
|
| 443 |
+
if "state_dict" in checkpoint:
|
| 444 |
+
checkpoint = checkpoint["state_dict"]
|
| 445 |
+
|
| 446 |
+
if config_file is None:
|
| 447 |
+
config_url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"
|
| 448 |
+
config_file = BytesIO(requests.get(config_url).content)
|
| 449 |
+
|
| 450 |
+
original_config = OmegaConf.load(config_file)
|
| 451 |
+
|
| 452 |
+
# default to sd-v1-5
|
| 453 |
+
image_size = image_size or 512
|
| 454 |
+
|
| 455 |
+
vae_config = create_vae_diffusers_config(original_config, image_size=image_size)
|
| 456 |
+
converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
|
| 457 |
+
|
| 458 |
+
if scaling_factor is None:
|
| 459 |
+
if (
|
| 460 |
+
"model" in original_config
|
| 461 |
+
and "params" in original_config.model
|
| 462 |
+
and "scale_factor" in original_config.model.params
|
| 463 |
+
):
|
| 464 |
+
vae_scaling_factor = original_config.model.params.scale_factor
|
| 465 |
+
else:
|
| 466 |
+
vae_scaling_factor = 0.18215 # default SD scaling factor
|
| 467 |
+
|
| 468 |
+
vae_config["scaling_factor"] = vae_scaling_factor
|
| 469 |
+
|
| 470 |
+
ctx = init_empty_weights if is_accelerate_available() else nullcontext
|
| 471 |
+
with ctx():
|
| 472 |
+
vae = AutoencoderKL(**vae_config)
|
| 473 |
+
|
| 474 |
+
if is_accelerate_available():
|
| 475 |
+
from ..models.modeling_utils import load_model_dict_into_meta
|
| 476 |
+
|
| 477 |
+
load_model_dict_into_meta(vae, converted_vae_checkpoint, device="cpu")
|
| 478 |
+
else:
|
| 479 |
+
vae.load_state_dict(converted_vae_checkpoint)
|
| 480 |
+
|
| 481 |
+
if torch_dtype is not None:
|
| 482 |
+
vae.to(dtype=torch_dtype)
|
| 483 |
+
|
| 484 |
+
return vae
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class FromOriginalControlnetMixin:
|
| 488 |
+
"""
|
| 489 |
+
Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
|
| 490 |
+
"""
|
| 491 |
+
|
| 492 |
+
@classmethod
|
| 493 |
+
def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
|
| 494 |
+
r"""
|
| 495 |
+
Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
|
| 496 |
+
`.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
|
| 497 |
+
|
| 498 |
+
Parameters:
|
| 499 |
+
pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
|
| 500 |
+
Can be either:
|
| 501 |
+
- A link to the `.ckpt` file (for example
|
| 502 |
+
`"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
|
| 503 |
+
- A path to a *file* containing all pipeline weights.
|
| 504 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
| 505 |
+
Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
|
| 506 |
+
dtype is automatically derived from the model's weights.
|
| 507 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 508 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 509 |
+
cached versions if they exist.
|
| 510 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 511 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 512 |
+
is not used.
|
| 513 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 514 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 515 |
+
incompletely downloaded files are deleted.
|
| 516 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 517 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 518 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 519 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 520 |
+
Whether to only load local model weights and configuration files or not. If set to True, the model
|
| 521 |
+
won't be downloaded from the Hub.
|
| 522 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 523 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 524 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 525 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 526 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 527 |
+
allowed by Git.
|
| 528 |
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
| 529 |
+
If set to `None`, the safetensors weights are downloaded if they're available **and** if the
|
| 530 |
+
safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
|
| 531 |
+
weights. If set to `False`, safetensors weights are not loaded.
|
| 532 |
+
image_size (`int`, *optional*, defaults to 512):
|
| 533 |
+
The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
|
| 534 |
+
Diffusion v2 base model. Use 768 for Stable Diffusion v2.
|
| 535 |
+
upcast_attention (`bool`, *optional*, defaults to `None`):
|
| 536 |
+
Whether the attention computation should always be upcasted.
|
| 537 |
+
kwargs (remaining dictionary of keyword arguments, *optional*):
|
| 538 |
+
Can be used to overwrite load and saveable variables (for example the pipeline components of the
|
| 539 |
+
specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
|
| 540 |
+
method. See example below for more information.
|
| 541 |
+
|
| 542 |
+
Examples:
|
| 543 |
+
|
| 544 |
+
```py
|
| 545 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
|
| 546 |
+
|
| 547 |
+
url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
|
| 548 |
+
model = ControlNetModel.from_single_file(url)
|
| 549 |
+
|
| 550 |
+
url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
|
| 551 |
+
pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
|
| 552 |
+
```
|
| 553 |
+
"""
|
| 554 |
+
# import here to avoid circular dependency
|
| 555 |
+
from ..pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
|
| 556 |
+
|
| 557 |
+
config_file = kwargs.pop("config_file", None)
|
| 558 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 559 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 560 |
+
force_download = kwargs.pop("force_download", False)
|
| 561 |
+
proxies = kwargs.pop("proxies", None)
|
| 562 |
+
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
| 563 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 564 |
+
num_in_channels = kwargs.pop("num_in_channels", None)
|
| 565 |
+
use_linear_projection = kwargs.pop("use_linear_projection", None)
|
| 566 |
+
revision = kwargs.pop("revision", None)
|
| 567 |
+
extract_ema = kwargs.pop("extract_ema", False)
|
| 568 |
+
image_size = kwargs.pop("image_size", None)
|
| 569 |
+
upcast_attention = kwargs.pop("upcast_attention", None)
|
| 570 |
+
|
| 571 |
+
torch_dtype = kwargs.pop("torch_dtype", None)
|
| 572 |
+
|
| 573 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
| 574 |
+
|
| 575 |
+
file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
|
| 576 |
+
from_safetensors = file_extension == "safetensors"
|
| 577 |
+
|
| 578 |
+
if from_safetensors and use_safetensors is False:
|
| 579 |
+
raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
|
| 580 |
+
|
| 581 |
+
# remove huggingface url
|
| 582 |
+
for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
|
| 583 |
+
if pretrained_model_link_or_path.startswith(prefix):
|
| 584 |
+
pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
|
| 585 |
+
|
| 586 |
+
# Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
|
| 587 |
+
ckpt_path = Path(pretrained_model_link_or_path)
|
| 588 |
+
if not ckpt_path.is_file():
|
| 589 |
+
# get repo_id and (potentially nested) file path of ckpt in repo
|
| 590 |
+
repo_id = "/".join(ckpt_path.parts[:2])
|
| 591 |
+
file_path = "/".join(ckpt_path.parts[2:])
|
| 592 |
+
|
| 593 |
+
if file_path.startswith("blob/"):
|
| 594 |
+
file_path = file_path[len("blob/") :]
|
| 595 |
+
|
| 596 |
+
if file_path.startswith("main/"):
|
| 597 |
+
file_path = file_path[len("main/") :]
|
| 598 |
+
|
| 599 |
+
pretrained_model_link_or_path = hf_hub_download(
|
| 600 |
+
repo_id,
|
| 601 |
+
filename=file_path,
|
| 602 |
+
cache_dir=cache_dir,
|
| 603 |
+
resume_download=resume_download,
|
| 604 |
+
proxies=proxies,
|
| 605 |
+
local_files_only=local_files_only,
|
| 606 |
+
use_auth_token=use_auth_token,
|
| 607 |
+
revision=revision,
|
| 608 |
+
force_download=force_download,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
if config_file is None:
|
| 612 |
+
config_url = "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml"
|
| 613 |
+
config_file = BytesIO(requests.get(config_url).content)
|
| 614 |
+
|
| 615 |
+
image_size = image_size or 512
|
| 616 |
+
|
| 617 |
+
controlnet = download_controlnet_from_original_ckpt(
|
| 618 |
+
pretrained_model_link_or_path,
|
| 619 |
+
original_config_file=config_file,
|
| 620 |
+
image_size=image_size,
|
| 621 |
+
extract_ema=extract_ema,
|
| 622 |
+
num_in_channels=num_in_channels,
|
| 623 |
+
upcast_attention=upcast_attention,
|
| 624 |
+
from_safetensors=from_safetensors,
|
| 625 |
+
use_linear_projection=use_linear_projection,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
if torch_dtype is not None:
|
| 629 |
+
controlnet.to(dtype=torch_dtype)
|
| 630 |
+
|
| 631 |
+
return controlnet
|
diffusers/loaders/textual_inversion.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Dict, List, Optional, Union
|
| 15 |
+
|
| 16 |
+
import safetensors
|
| 17 |
+
import torch
|
| 18 |
+
from torch import nn
|
| 19 |
+
|
| 20 |
+
from ..utils import (
|
| 21 |
+
DIFFUSERS_CACHE,
|
| 22 |
+
HF_HUB_OFFLINE,
|
| 23 |
+
_get_model_file,
|
| 24 |
+
is_accelerate_available,
|
| 25 |
+
is_transformers_available,
|
| 26 |
+
logging,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_transformers_available():
|
| 31 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer
|
| 32 |
+
|
| 33 |
+
if is_accelerate_available():
|
| 34 |
+
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
TEXT_INVERSION_NAME = "learned_embeds.bin"
|
| 39 |
+
TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
|
| 43 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 44 |
+
force_download = kwargs.pop("force_download", False)
|
| 45 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 46 |
+
proxies = kwargs.pop("proxies", None)
|
| 47 |
+
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
| 48 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 49 |
+
revision = kwargs.pop("revision", None)
|
| 50 |
+
subfolder = kwargs.pop("subfolder", None)
|
| 51 |
+
weight_name = kwargs.pop("weight_name", None)
|
| 52 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
| 53 |
+
|
| 54 |
+
allow_pickle = False
|
| 55 |
+
if use_safetensors is None:
|
| 56 |
+
use_safetensors = True
|
| 57 |
+
allow_pickle = True
|
| 58 |
+
|
| 59 |
+
user_agent = {
|
| 60 |
+
"file_type": "text_inversion",
|
| 61 |
+
"framework": "pytorch",
|
| 62 |
+
}
|
| 63 |
+
state_dicts = []
|
| 64 |
+
for pretrained_model_name_or_path in pretrained_model_name_or_paths:
|
| 65 |
+
if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
|
| 66 |
+
# 3.1. Load textual inversion file
|
| 67 |
+
model_file = None
|
| 68 |
+
|
| 69 |
+
# Let's first try to load .safetensors weights
|
| 70 |
+
if (use_safetensors and weight_name is None) or (
|
| 71 |
+
weight_name is not None and weight_name.endswith(".safetensors")
|
| 72 |
+
):
|
| 73 |
+
try:
|
| 74 |
+
model_file = _get_model_file(
|
| 75 |
+
pretrained_model_name_or_path,
|
| 76 |
+
weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
|
| 77 |
+
cache_dir=cache_dir,
|
| 78 |
+
force_download=force_download,
|
| 79 |
+
resume_download=resume_download,
|
| 80 |
+
proxies=proxies,
|
| 81 |
+
local_files_only=local_files_only,
|
| 82 |
+
use_auth_token=use_auth_token,
|
| 83 |
+
revision=revision,
|
| 84 |
+
subfolder=subfolder,
|
| 85 |
+
user_agent=user_agent,
|
| 86 |
+
)
|
| 87 |
+
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
| 88 |
+
except Exception as e:
|
| 89 |
+
if not allow_pickle:
|
| 90 |
+
raise e
|
| 91 |
+
|
| 92 |
+
model_file = None
|
| 93 |
+
|
| 94 |
+
if model_file is None:
|
| 95 |
+
model_file = _get_model_file(
|
| 96 |
+
pretrained_model_name_or_path,
|
| 97 |
+
weights_name=weight_name or TEXT_INVERSION_NAME,
|
| 98 |
+
cache_dir=cache_dir,
|
| 99 |
+
force_download=force_download,
|
| 100 |
+
resume_download=resume_download,
|
| 101 |
+
proxies=proxies,
|
| 102 |
+
local_files_only=local_files_only,
|
| 103 |
+
use_auth_token=use_auth_token,
|
| 104 |
+
revision=revision,
|
| 105 |
+
subfolder=subfolder,
|
| 106 |
+
user_agent=user_agent,
|
| 107 |
+
)
|
| 108 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 109 |
+
else:
|
| 110 |
+
state_dict = pretrained_model_name_or_path
|
| 111 |
+
|
| 112 |
+
state_dicts.append(state_dict)
|
| 113 |
+
|
| 114 |
+
return state_dicts
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TextualInversionLoaderMixin:
|
| 118 |
+
r"""
|
| 119 |
+
Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
|
| 123 |
+
r"""
|
| 124 |
+
Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
|
| 125 |
+
be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
|
| 126 |
+
inversion token or if the textual inversion token is a single vector, the input prompt is returned.
|
| 127 |
+
|
| 128 |
+
Parameters:
|
| 129 |
+
prompt (`str` or list of `str`):
|
| 130 |
+
The prompt or prompts to guide the image generation.
|
| 131 |
+
tokenizer (`PreTrainedTokenizer`):
|
| 132 |
+
The tokenizer responsible for encoding the prompt into input tokens.
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
`str` or list of `str`: The converted prompt
|
| 136 |
+
"""
|
| 137 |
+
if not isinstance(prompt, List):
|
| 138 |
+
prompts = [prompt]
|
| 139 |
+
else:
|
| 140 |
+
prompts = prompt
|
| 141 |
+
|
| 142 |
+
prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
|
| 143 |
+
|
| 144 |
+
if not isinstance(prompt, List):
|
| 145 |
+
return prompts[0]
|
| 146 |
+
|
| 147 |
+
return prompts
|
| 148 |
+
|
| 149 |
+
def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
|
| 150 |
+
r"""
|
| 151 |
+
Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
|
| 152 |
+
to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
|
| 153 |
+
is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
|
| 154 |
+
inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
|
| 155 |
+
|
| 156 |
+
Parameters:
|
| 157 |
+
prompt (`str`):
|
| 158 |
+
The prompt to guide the image generation.
|
| 159 |
+
tokenizer (`PreTrainedTokenizer`):
|
| 160 |
+
The tokenizer responsible for encoding the prompt into input tokens.
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
`str`: The converted prompt
|
| 164 |
+
"""
|
| 165 |
+
tokens = tokenizer.tokenize(prompt)
|
| 166 |
+
unique_tokens = set(tokens)
|
| 167 |
+
for token in unique_tokens:
|
| 168 |
+
if token in tokenizer.added_tokens_encoder:
|
| 169 |
+
replacement = token
|
| 170 |
+
i = 1
|
| 171 |
+
while f"{token}_{i}" in tokenizer.added_tokens_encoder:
|
| 172 |
+
replacement += f" {token}_{i}"
|
| 173 |
+
i += 1
|
| 174 |
+
|
| 175 |
+
prompt = prompt.replace(token, replacement)
|
| 176 |
+
|
| 177 |
+
return prompt
|
| 178 |
+
|
| 179 |
+
def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
|
| 180 |
+
if tokenizer is None:
|
| 181 |
+
raise ValueError(
|
| 182 |
+
f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
|
| 183 |
+
f" `{self.load_textual_inversion.__name__}`"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
if text_encoder is None:
|
| 187 |
+
raise ValueError(
|
| 188 |
+
f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
|
| 189 |
+
f" `{self.load_textual_inversion.__name__}`"
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
if len(pretrained_model_name_or_paths) > 1 and len(pretrained_model_name_or_paths) != len(tokens):
|
| 193 |
+
raise ValueError(
|
| 194 |
+
f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
|
| 195 |
+
f"Make sure both lists have the same length."
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
valid_tokens = [t for t in tokens if t is not None]
|
| 199 |
+
if len(set(valid_tokens)) < len(valid_tokens):
|
| 200 |
+
raise ValueError(f"You have passed a list of tokens that contains duplicates: {tokens}")
|
| 201 |
+
|
| 202 |
+
@staticmethod
|
| 203 |
+
def _retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer):
|
| 204 |
+
all_tokens = []
|
| 205 |
+
all_embeddings = []
|
| 206 |
+
for state_dict, token in zip(state_dicts, tokens):
|
| 207 |
+
if isinstance(state_dict, torch.Tensor):
|
| 208 |
+
if token is None:
|
| 209 |
+
raise ValueError(
|
| 210 |
+
"You are trying to load a textual inversion embedding that has been saved as a PyTorch tensor. Make sure to pass the name of the corresponding token in this case: `token=...`."
|
| 211 |
+
)
|
| 212 |
+
loaded_token = token
|
| 213 |
+
embedding = state_dict
|
| 214 |
+
elif len(state_dict) == 1:
|
| 215 |
+
# diffusers
|
| 216 |
+
loaded_token, embedding = next(iter(state_dict.items()))
|
| 217 |
+
elif "string_to_param" in state_dict:
|
| 218 |
+
# A1111
|
| 219 |
+
loaded_token = state_dict["name"]
|
| 220 |
+
embedding = state_dict["string_to_param"]["*"]
|
| 221 |
+
else:
|
| 222 |
+
raise ValueError(
|
| 223 |
+
f"Loaded state dictonary is incorrect: {state_dict}. \n\n"
|
| 224 |
+
"Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param`"
|
| 225 |
+
" input key."
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
if token is not None and loaded_token != token:
|
| 229 |
+
logger.info(f"The loaded token: {loaded_token} is overwritten by the passed token {token}.")
|
| 230 |
+
else:
|
| 231 |
+
token = loaded_token
|
| 232 |
+
|
| 233 |
+
if token in tokenizer.get_vocab():
|
| 234 |
+
raise ValueError(
|
| 235 |
+
f"Token {token} already in tokenizer vocabulary. Please choose a different token name or remove {token} and embedding from the tokenizer and text encoder."
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
all_tokens.append(token)
|
| 239 |
+
all_embeddings.append(embedding)
|
| 240 |
+
|
| 241 |
+
return all_tokens, all_embeddings
|
| 242 |
+
|
| 243 |
+
@staticmethod
|
| 244 |
+
def _extend_tokens_and_embeddings(tokens, embeddings, tokenizer):
|
| 245 |
+
all_tokens = []
|
| 246 |
+
all_embeddings = []
|
| 247 |
+
|
| 248 |
+
for embedding, token in zip(embeddings, tokens):
|
| 249 |
+
if f"{token}_1" in tokenizer.get_vocab():
|
| 250 |
+
multi_vector_tokens = [token]
|
| 251 |
+
i = 1
|
| 252 |
+
while f"{token}_{i}" in tokenizer.added_tokens_encoder:
|
| 253 |
+
multi_vector_tokens.append(f"{token}_{i}")
|
| 254 |
+
i += 1
|
| 255 |
+
|
| 256 |
+
raise ValueError(
|
| 257 |
+
f"Multi-vector Token {multi_vector_tokens} already in tokenizer vocabulary. Please choose a different token name or remove the {multi_vector_tokens} and embedding from the tokenizer and text encoder."
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
is_multi_vector = len(embedding.shape) > 1 and embedding.shape[0] > 1
|
| 261 |
+
if is_multi_vector:
|
| 262 |
+
all_tokens += [token] + [f"{token}_{i}" for i in range(1, embedding.shape[0])]
|
| 263 |
+
all_embeddings += [e for e in embedding] # noqa: C416
|
| 264 |
+
else:
|
| 265 |
+
all_tokens += [token]
|
| 266 |
+
all_embeddings += [embedding[0]] if len(embedding.shape) > 1 else [embedding]
|
| 267 |
+
|
| 268 |
+
return all_tokens, all_embeddings
|
| 269 |
+
|
| 270 |
+
def load_textual_inversion(
|
| 271 |
+
self,
|
| 272 |
+
pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]],
|
| 273 |
+
token: Optional[Union[str, List[str]]] = None,
|
| 274 |
+
tokenizer: Optional["PreTrainedTokenizer"] = None, # noqa: F821
|
| 275 |
+
text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
|
| 276 |
+
**kwargs,
|
| 277 |
+
):
|
| 278 |
+
r"""
|
| 279 |
+
Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
|
| 280 |
+
Automatic1111 formats are supported).
|
| 281 |
+
|
| 282 |
+
Parameters:
|
| 283 |
+
pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
|
| 284 |
+
Can be either one of the following or a list of them:
|
| 285 |
+
|
| 286 |
+
- A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
|
| 287 |
+
pretrained model hosted on the Hub.
|
| 288 |
+
- A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
|
| 289 |
+
inversion weights.
|
| 290 |
+
- A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
|
| 291 |
+
- A [torch state
|
| 292 |
+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
| 293 |
+
|
| 294 |
+
token (`str` or `List[str]`, *optional*):
|
| 295 |
+
Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
|
| 296 |
+
list, then `token` must also be a list of equal length.
|
| 297 |
+
text_encoder ([`~transformers.CLIPTextModel`], *optional*):
|
| 298 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 299 |
+
If not specified, function will take self.tokenizer.
|
| 300 |
+
tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
|
| 301 |
+
A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
|
| 302 |
+
weight_name (`str`, *optional*):
|
| 303 |
+
Name of a custom weight file. This should be used when:
|
| 304 |
+
|
| 305 |
+
- The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
|
| 306 |
+
name such as `text_inv.bin`.
|
| 307 |
+
- The saved textual inversion file is in the Automatic1111 format.
|
| 308 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 309 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 310 |
+
is not used.
|
| 311 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 312 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 313 |
+
cached versions if they exist.
|
| 314 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 315 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 316 |
+
incompletely downloaded files are deleted.
|
| 317 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 318 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 319 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 320 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 321 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 322 |
+
won't be downloaded from the Hub.
|
| 323 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 324 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 325 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 326 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 327 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 328 |
+
allowed by Git.
|
| 329 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 330 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
| 331 |
+
mirror (`str`, *optional*):
|
| 332 |
+
Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
|
| 333 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
| 334 |
+
information.
|
| 335 |
+
|
| 336 |
+
Example:
|
| 337 |
+
|
| 338 |
+
To load a Textual Inversion embedding vector in 🤗 Diffusers format:
|
| 339 |
+
|
| 340 |
+
```py
|
| 341 |
+
from diffusers import StableDiffusionPipeline
|
| 342 |
+
import torch
|
| 343 |
+
|
| 344 |
+
model_id = "runwayml/stable-diffusion-v1-5"
|
| 345 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
| 346 |
+
|
| 347 |
+
pipe.load_textual_inversion("sd-concepts-library/cat-toy")
|
| 348 |
+
|
| 349 |
+
prompt = "A <cat-toy> backpack"
|
| 350 |
+
|
| 351 |
+
image = pipe(prompt, num_inference_steps=50).images[0]
|
| 352 |
+
image.save("cat-backpack.png")
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
|
| 356 |
+
(for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
|
| 357 |
+
locally:
|
| 358 |
+
|
| 359 |
+
```py
|
| 360 |
+
from diffusers import StableDiffusionPipeline
|
| 361 |
+
import torch
|
| 362 |
+
|
| 363 |
+
model_id = "runwayml/stable-diffusion-v1-5"
|
| 364 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
| 365 |
+
|
| 366 |
+
pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
|
| 367 |
+
|
| 368 |
+
prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
|
| 369 |
+
|
| 370 |
+
image = pipe(prompt, num_inference_steps=50).images[0]
|
| 371 |
+
image.save("character.png")
|
| 372 |
+
```
|
| 373 |
+
|
| 374 |
+
"""
|
| 375 |
+
# 1. Set correct tokenizer and text encoder
|
| 376 |
+
tokenizer = tokenizer or getattr(self, "tokenizer", None)
|
| 377 |
+
text_encoder = text_encoder or getattr(self, "text_encoder", None)
|
| 378 |
+
|
| 379 |
+
# 2. Normalize inputs
|
| 380 |
+
pretrained_model_name_or_paths = (
|
| 381 |
+
[pretrained_model_name_or_path]
|
| 382 |
+
if not isinstance(pretrained_model_name_or_path, list)
|
| 383 |
+
else pretrained_model_name_or_path
|
| 384 |
+
)
|
| 385 |
+
tokens = [token] if not isinstance(token, list) else token
|
| 386 |
+
if tokens[0] is None:
|
| 387 |
+
tokens = tokens * len(pretrained_model_name_or_paths)
|
| 388 |
+
|
| 389 |
+
# 3. Check inputs
|
| 390 |
+
self._check_text_inv_inputs(tokenizer, text_encoder, pretrained_model_name_or_paths, tokens)
|
| 391 |
+
|
| 392 |
+
# 4. Load state dicts of textual embeddings
|
| 393 |
+
state_dicts = load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs)
|
| 394 |
+
|
| 395 |
+
# 4.1 Handle the special case when state_dict is a tensor that contains n embeddings for n tokens
|
| 396 |
+
if len(tokens) > 1 and len(state_dicts) == 1:
|
| 397 |
+
if isinstance(state_dicts[0], torch.Tensor):
|
| 398 |
+
state_dicts = list(state_dicts[0])
|
| 399 |
+
if len(tokens) != len(state_dicts):
|
| 400 |
+
raise ValueError(
|
| 401 |
+
f"You have passed a state_dict contains {len(state_dicts)} embeddings, and list of tokens of length {len(tokens)} "
|
| 402 |
+
f"Make sure both have the same length."
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# 4. Retrieve tokens and embeddings
|
| 406 |
+
tokens, embeddings = self._retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer)
|
| 407 |
+
|
| 408 |
+
# 5. Extend tokens and embeddings for multi vector
|
| 409 |
+
tokens, embeddings = self._extend_tokens_and_embeddings(tokens, embeddings, tokenizer)
|
| 410 |
+
|
| 411 |
+
# 6. Make sure all embeddings have the correct size
|
| 412 |
+
expected_emb_dim = text_encoder.get_input_embeddings().weight.shape[-1]
|
| 413 |
+
if any(expected_emb_dim != emb.shape[-1] for emb in embeddings):
|
| 414 |
+
raise ValueError(
|
| 415 |
+
"Loaded embeddings are of incorrect shape. Expected each textual inversion embedding "
|
| 416 |
+
"to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} "
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# 7. Now we can be sure that loading the embedding matrix works
|
| 420 |
+
# < Unsafe code:
|
| 421 |
+
|
| 422 |
+
# 7.1 Offload all hooks in case the pipeline was cpu offloaded before make sure, we offload and onload again
|
| 423 |
+
is_model_cpu_offload = False
|
| 424 |
+
is_sequential_cpu_offload = False
|
| 425 |
+
for _, component in self.components.items():
|
| 426 |
+
if isinstance(component, nn.Module):
|
| 427 |
+
if hasattr(component, "_hf_hook"):
|
| 428 |
+
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
| 429 |
+
is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
|
| 430 |
+
logger.info(
|
| 431 |
+
"Accelerate hooks detected. Since you have called `load_textual_inversion()`, the previous hooks will be first removed. Then the textual inversion parameters will be loaded and the hooks will be applied again."
|
| 432 |
+
)
|
| 433 |
+
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
| 434 |
+
|
| 435 |
+
# 7.2 save expected device and dtype
|
| 436 |
+
device = text_encoder.device
|
| 437 |
+
dtype = text_encoder.dtype
|
| 438 |
+
|
| 439 |
+
# 7.3 Increase token embedding matrix
|
| 440 |
+
text_encoder.resize_token_embeddings(len(tokenizer) + len(tokens))
|
| 441 |
+
input_embeddings = text_encoder.get_input_embeddings().weight
|
| 442 |
+
|
| 443 |
+
# 7.4 Load token and embedding
|
| 444 |
+
for token, embedding in zip(tokens, embeddings):
|
| 445 |
+
# add tokens and get ids
|
| 446 |
+
tokenizer.add_tokens(token)
|
| 447 |
+
token_id = tokenizer.convert_tokens_to_ids(token)
|
| 448 |
+
input_embeddings.data[token_id] = embedding
|
| 449 |
+
logger.info(f"Loaded textual inversion embedding for {token}.")
|
| 450 |
+
|
| 451 |
+
input_embeddings.to(dtype=dtype, device=device)
|
| 452 |
+
|
| 453 |
+
# 7.5 Offload the model again
|
| 454 |
+
if is_model_cpu_offload:
|
| 455 |
+
self.enable_model_cpu_offload()
|
| 456 |
+
elif is_sequential_cpu_offload:
|
| 457 |
+
self.enable_sequential_cpu_offload()
|
| 458 |
+
|
| 459 |
+
# / Unsafe Code >
|
diffusers/loaders/unet.py
ADDED
|
@@ -0,0 +1,735 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import os
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
from contextlib import nullcontext
|
| 17 |
+
from typing import Callable, Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import safetensors
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from ..models.embeddings import ImageProjection
|
| 25 |
+
from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
|
| 26 |
+
from ..utils import (
|
| 27 |
+
DIFFUSERS_CACHE,
|
| 28 |
+
HF_HUB_OFFLINE,
|
| 29 |
+
USE_PEFT_BACKEND,
|
| 30 |
+
_get_model_file,
|
| 31 |
+
delete_adapter_layers,
|
| 32 |
+
is_accelerate_available,
|
| 33 |
+
logging,
|
| 34 |
+
set_adapter_layers,
|
| 35 |
+
set_weights_and_activate_adapters,
|
| 36 |
+
)
|
| 37 |
+
from .utils import AttnProcsLayers
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if is_accelerate_available():
|
| 41 |
+
from accelerate import init_empty_weights
|
| 42 |
+
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
TEXT_ENCODER_NAME = "text_encoder"
|
| 48 |
+
UNET_NAME = "unet"
|
| 49 |
+
|
| 50 |
+
LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
|
| 51 |
+
LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
|
| 52 |
+
|
| 53 |
+
CUSTOM_DIFFUSION_WEIGHT_NAME = "pytorch_custom_diffusion_weights.bin"
|
| 54 |
+
CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE = "pytorch_custom_diffusion_weights.safetensors"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class UNet2DConditionLoadersMixin:
|
| 58 |
+
"""
|
| 59 |
+
Load LoRA layers into a [`UNet2DCondtionModel`].
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
text_encoder_name = TEXT_ENCODER_NAME
|
| 63 |
+
unet_name = UNET_NAME
|
| 64 |
+
|
| 65 |
+
def load_attn_procs(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
|
| 66 |
+
r"""
|
| 67 |
+
Load pretrained attention processor layers into [`UNet2DConditionModel`]. Attention processor layers have to be
|
| 68 |
+
defined in
|
| 69 |
+
[`attention_processor.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)
|
| 70 |
+
and be a `torch.nn.Module` class.
|
| 71 |
+
|
| 72 |
+
Parameters:
|
| 73 |
+
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
|
| 74 |
+
Can be either:
|
| 75 |
+
|
| 76 |
+
- A string, the model id (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
|
| 77 |
+
the Hub.
|
| 78 |
+
- A path to a directory (for example `./my_model_directory`) containing the model weights saved
|
| 79 |
+
with [`ModelMixin.save_pretrained`].
|
| 80 |
+
- A [torch state
|
| 81 |
+
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
|
| 82 |
+
|
| 83 |
+
cache_dir (`Union[str, os.PathLike]`, *optional*):
|
| 84 |
+
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
|
| 85 |
+
is not used.
|
| 86 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 87 |
+
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
|
| 88 |
+
cached versions if they exist.
|
| 89 |
+
resume_download (`bool`, *optional*, defaults to `False`):
|
| 90 |
+
Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
|
| 91 |
+
incompletely downloaded files are deleted.
|
| 92 |
+
proxies (`Dict[str, str]`, *optional*):
|
| 93 |
+
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
|
| 94 |
+
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
|
| 95 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 96 |
+
Whether to only load local model weights and configuration files or not. If set to `True`, the model
|
| 97 |
+
won't be downloaded from the Hub.
|
| 98 |
+
use_auth_token (`str` or *bool*, *optional*):
|
| 99 |
+
The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
|
| 100 |
+
`diffusers-cli login` (stored in `~/.huggingface`) is used.
|
| 101 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 102 |
+
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
|
| 103 |
+
tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
|
| 104 |
+
Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
|
| 105 |
+
argument to `True` will raise an error.
|
| 106 |
+
revision (`str`, *optional*, defaults to `"main"`):
|
| 107 |
+
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
|
| 108 |
+
allowed by Git.
|
| 109 |
+
subfolder (`str`, *optional*, defaults to `""`):
|
| 110 |
+
The subfolder location of a model file within a larger model repository on the Hub or locally.
|
| 111 |
+
mirror (`str`, *optional*):
|
| 112 |
+
Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
|
| 113 |
+
guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
|
| 114 |
+
information.
|
| 115 |
+
|
| 116 |
+
Example:
|
| 117 |
+
|
| 118 |
+
```py
|
| 119 |
+
from diffusers import AutoPipelineForText2Image
|
| 120 |
+
import torch
|
| 121 |
+
|
| 122 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 123 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 124 |
+
).to("cuda")
|
| 125 |
+
pipeline.unet.load_attn_procs(
|
| 126 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
|
| 127 |
+
)
|
| 128 |
+
```
|
| 129 |
+
"""
|
| 130 |
+
from ..models.attention_processor import CustomDiffusionAttnProcessor
|
| 131 |
+
from ..models.lora import LoRACompatibleConv, LoRACompatibleLinear, LoRAConv2dLayer, LoRALinearLayer
|
| 132 |
+
|
| 133 |
+
cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
|
| 134 |
+
force_download = kwargs.pop("force_download", False)
|
| 135 |
+
resume_download = kwargs.pop("resume_download", False)
|
| 136 |
+
proxies = kwargs.pop("proxies", None)
|
| 137 |
+
local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
|
| 138 |
+
use_auth_token = kwargs.pop("use_auth_token", None)
|
| 139 |
+
revision = kwargs.pop("revision", None)
|
| 140 |
+
subfolder = kwargs.pop("subfolder", None)
|
| 141 |
+
weight_name = kwargs.pop("weight_name", None)
|
| 142 |
+
use_safetensors = kwargs.pop("use_safetensors", None)
|
| 143 |
+
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
|
| 144 |
+
# This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
|
| 145 |
+
# See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
|
| 146 |
+
network_alphas = kwargs.pop("network_alphas", None)
|
| 147 |
+
|
| 148 |
+
_pipeline = kwargs.pop("_pipeline", None)
|
| 149 |
+
|
| 150 |
+
is_network_alphas_none = network_alphas is None
|
| 151 |
+
|
| 152 |
+
allow_pickle = False
|
| 153 |
+
|
| 154 |
+
if use_safetensors is None:
|
| 155 |
+
use_safetensors = True
|
| 156 |
+
allow_pickle = True
|
| 157 |
+
|
| 158 |
+
user_agent = {
|
| 159 |
+
"file_type": "attn_procs_weights",
|
| 160 |
+
"framework": "pytorch",
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
if low_cpu_mem_usage and not is_accelerate_available():
|
| 164 |
+
low_cpu_mem_usage = False
|
| 165 |
+
logger.warning(
|
| 166 |
+
"Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
|
| 167 |
+
" environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
|
| 168 |
+
" `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
|
| 169 |
+
" install accelerate\n```\n."
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
model_file = None
|
| 173 |
+
if not isinstance(pretrained_model_name_or_path_or_dict, dict):
|
| 174 |
+
# Let's first try to load .safetensors weights
|
| 175 |
+
if (use_safetensors and weight_name is None) or (
|
| 176 |
+
weight_name is not None and weight_name.endswith(".safetensors")
|
| 177 |
+
):
|
| 178 |
+
try:
|
| 179 |
+
model_file = _get_model_file(
|
| 180 |
+
pretrained_model_name_or_path_or_dict,
|
| 181 |
+
weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
|
| 182 |
+
cache_dir=cache_dir,
|
| 183 |
+
force_download=force_download,
|
| 184 |
+
resume_download=resume_download,
|
| 185 |
+
proxies=proxies,
|
| 186 |
+
local_files_only=local_files_only,
|
| 187 |
+
use_auth_token=use_auth_token,
|
| 188 |
+
revision=revision,
|
| 189 |
+
subfolder=subfolder,
|
| 190 |
+
user_agent=user_agent,
|
| 191 |
+
)
|
| 192 |
+
state_dict = safetensors.torch.load_file(model_file, device="cpu")
|
| 193 |
+
except IOError as e:
|
| 194 |
+
if not allow_pickle:
|
| 195 |
+
raise e
|
| 196 |
+
# try loading non-safetensors weights
|
| 197 |
+
pass
|
| 198 |
+
if model_file is None:
|
| 199 |
+
model_file = _get_model_file(
|
| 200 |
+
pretrained_model_name_or_path_or_dict,
|
| 201 |
+
weights_name=weight_name or LORA_WEIGHT_NAME,
|
| 202 |
+
cache_dir=cache_dir,
|
| 203 |
+
force_download=force_download,
|
| 204 |
+
resume_download=resume_download,
|
| 205 |
+
proxies=proxies,
|
| 206 |
+
local_files_only=local_files_only,
|
| 207 |
+
use_auth_token=use_auth_token,
|
| 208 |
+
revision=revision,
|
| 209 |
+
subfolder=subfolder,
|
| 210 |
+
user_agent=user_agent,
|
| 211 |
+
)
|
| 212 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 213 |
+
else:
|
| 214 |
+
state_dict = pretrained_model_name_or_path_or_dict
|
| 215 |
+
|
| 216 |
+
# fill attn processors
|
| 217 |
+
lora_layers_list = []
|
| 218 |
+
|
| 219 |
+
is_lora = all(("lora" in k or k.endswith(".alpha")) for k in state_dict.keys()) and not USE_PEFT_BACKEND
|
| 220 |
+
is_custom_diffusion = any("custom_diffusion" in k for k in state_dict.keys())
|
| 221 |
+
|
| 222 |
+
if is_lora:
|
| 223 |
+
# correct keys
|
| 224 |
+
state_dict, network_alphas = self.convert_state_dict_legacy_attn_format(state_dict, network_alphas)
|
| 225 |
+
|
| 226 |
+
if network_alphas is not None:
|
| 227 |
+
network_alphas_keys = list(network_alphas.keys())
|
| 228 |
+
used_network_alphas_keys = set()
|
| 229 |
+
|
| 230 |
+
lora_grouped_dict = defaultdict(dict)
|
| 231 |
+
mapped_network_alphas = {}
|
| 232 |
+
|
| 233 |
+
all_keys = list(state_dict.keys())
|
| 234 |
+
for key in all_keys:
|
| 235 |
+
value = state_dict.pop(key)
|
| 236 |
+
attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
|
| 237 |
+
lora_grouped_dict[attn_processor_key][sub_key] = value
|
| 238 |
+
|
| 239 |
+
# Create another `mapped_network_alphas` dictionary so that we can properly map them.
|
| 240 |
+
if network_alphas is not None:
|
| 241 |
+
for k in network_alphas_keys:
|
| 242 |
+
if k.replace(".alpha", "") in key:
|
| 243 |
+
mapped_network_alphas.update({attn_processor_key: network_alphas.get(k)})
|
| 244 |
+
used_network_alphas_keys.add(k)
|
| 245 |
+
|
| 246 |
+
if not is_network_alphas_none:
|
| 247 |
+
if len(set(network_alphas_keys) - used_network_alphas_keys) > 0:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if len(state_dict) > 0:
|
| 253 |
+
raise ValueError(
|
| 254 |
+
f"The `state_dict` has to be empty at this point but has the following keys \n\n {', '.join(state_dict.keys())}"
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
for key, value_dict in lora_grouped_dict.items():
|
| 258 |
+
attn_processor = self
|
| 259 |
+
for sub_key in key.split("."):
|
| 260 |
+
attn_processor = getattr(attn_processor, sub_key)
|
| 261 |
+
|
| 262 |
+
# Process non-attention layers, which don't have to_{k,v,q,out_proj}_lora layers
|
| 263 |
+
# or add_{k,v,q,out_proj}_proj_lora layers.
|
| 264 |
+
rank = value_dict["lora.down.weight"].shape[0]
|
| 265 |
+
|
| 266 |
+
if isinstance(attn_processor, LoRACompatibleConv):
|
| 267 |
+
in_features = attn_processor.in_channels
|
| 268 |
+
out_features = attn_processor.out_channels
|
| 269 |
+
kernel_size = attn_processor.kernel_size
|
| 270 |
+
|
| 271 |
+
ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
|
| 272 |
+
with ctx():
|
| 273 |
+
lora = LoRAConv2dLayer(
|
| 274 |
+
in_features=in_features,
|
| 275 |
+
out_features=out_features,
|
| 276 |
+
rank=rank,
|
| 277 |
+
kernel_size=kernel_size,
|
| 278 |
+
stride=attn_processor.stride,
|
| 279 |
+
padding=attn_processor.padding,
|
| 280 |
+
network_alpha=mapped_network_alphas.get(key),
|
| 281 |
+
)
|
| 282 |
+
elif isinstance(attn_processor, LoRACompatibleLinear):
|
| 283 |
+
ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
|
| 284 |
+
with ctx():
|
| 285 |
+
lora = LoRALinearLayer(
|
| 286 |
+
attn_processor.in_features,
|
| 287 |
+
attn_processor.out_features,
|
| 288 |
+
rank,
|
| 289 |
+
mapped_network_alphas.get(key),
|
| 290 |
+
)
|
| 291 |
+
else:
|
| 292 |
+
raise ValueError(f"Module {key} is not a LoRACompatibleConv or LoRACompatibleLinear module.")
|
| 293 |
+
|
| 294 |
+
value_dict = {k.replace("lora.", ""): v for k, v in value_dict.items()}
|
| 295 |
+
lora_layers_list.append((attn_processor, lora))
|
| 296 |
+
|
| 297 |
+
if low_cpu_mem_usage:
|
| 298 |
+
device = next(iter(value_dict.values())).device
|
| 299 |
+
dtype = next(iter(value_dict.values())).dtype
|
| 300 |
+
load_model_dict_into_meta(lora, value_dict, device=device, dtype=dtype)
|
| 301 |
+
else:
|
| 302 |
+
lora.load_state_dict(value_dict)
|
| 303 |
+
|
| 304 |
+
elif is_custom_diffusion:
|
| 305 |
+
attn_processors = {}
|
| 306 |
+
custom_diffusion_grouped_dict = defaultdict(dict)
|
| 307 |
+
for key, value in state_dict.items():
|
| 308 |
+
if len(value) == 0:
|
| 309 |
+
custom_diffusion_grouped_dict[key] = {}
|
| 310 |
+
else:
|
| 311 |
+
if "to_out" in key:
|
| 312 |
+
attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
|
| 313 |
+
else:
|
| 314 |
+
attn_processor_key, sub_key = ".".join(key.split(".")[:-2]), ".".join(key.split(".")[-2:])
|
| 315 |
+
custom_diffusion_grouped_dict[attn_processor_key][sub_key] = value
|
| 316 |
+
|
| 317 |
+
for key, value_dict in custom_diffusion_grouped_dict.items():
|
| 318 |
+
if len(value_dict) == 0:
|
| 319 |
+
attn_processors[key] = CustomDiffusionAttnProcessor(
|
| 320 |
+
train_kv=False, train_q_out=False, hidden_size=None, cross_attention_dim=None
|
| 321 |
+
)
|
| 322 |
+
else:
|
| 323 |
+
cross_attention_dim = value_dict["to_k_custom_diffusion.weight"].shape[1]
|
| 324 |
+
hidden_size = value_dict["to_k_custom_diffusion.weight"].shape[0]
|
| 325 |
+
train_q_out = True if "to_q_custom_diffusion.weight" in value_dict else False
|
| 326 |
+
attn_processors[key] = CustomDiffusionAttnProcessor(
|
| 327 |
+
train_kv=True,
|
| 328 |
+
train_q_out=train_q_out,
|
| 329 |
+
hidden_size=hidden_size,
|
| 330 |
+
cross_attention_dim=cross_attention_dim,
|
| 331 |
+
)
|
| 332 |
+
attn_processors[key].load_state_dict(value_dict)
|
| 333 |
+
elif USE_PEFT_BACKEND:
|
| 334 |
+
# In that case we have nothing to do as loading the adapter weights is already handled above by `set_peft_model_state_dict`
|
| 335 |
+
# on the Unet
|
| 336 |
+
pass
|
| 337 |
+
else:
|
| 338 |
+
raise ValueError(
|
| 339 |
+
f"{model_file} does not seem to be in the correct format expected by LoRA or Custom Diffusion training."
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
# <Unsafe code
|
| 343 |
+
# We can be sure that the following works as it just sets attention processors, lora layers and puts all in the same dtype
|
| 344 |
+
# Now we remove any existing hooks to
|
| 345 |
+
is_model_cpu_offload = False
|
| 346 |
+
is_sequential_cpu_offload = False
|
| 347 |
+
|
| 348 |
+
# For PEFT backend the Unet is already offloaded at this stage as it is handled inside `lora_lora_weights_into_unet`
|
| 349 |
+
if not USE_PEFT_BACKEND:
|
| 350 |
+
if _pipeline is not None:
|
| 351 |
+
for _, component in _pipeline.components.items():
|
| 352 |
+
if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
|
| 353 |
+
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
| 354 |
+
is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
|
| 355 |
+
|
| 356 |
+
logger.info(
|
| 357 |
+
"Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
|
| 358 |
+
)
|
| 359 |
+
remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
|
| 360 |
+
|
| 361 |
+
# only custom diffusion needs to set attn processors
|
| 362 |
+
if is_custom_diffusion:
|
| 363 |
+
self.set_attn_processor(attn_processors)
|
| 364 |
+
|
| 365 |
+
# set lora layers
|
| 366 |
+
for target_module, lora_layer in lora_layers_list:
|
| 367 |
+
target_module.set_lora_layer(lora_layer)
|
| 368 |
+
|
| 369 |
+
self.to(dtype=self.dtype, device=self.device)
|
| 370 |
+
|
| 371 |
+
# Offload back.
|
| 372 |
+
if is_model_cpu_offload:
|
| 373 |
+
_pipeline.enable_model_cpu_offload()
|
| 374 |
+
elif is_sequential_cpu_offload:
|
| 375 |
+
_pipeline.enable_sequential_cpu_offload()
|
| 376 |
+
# Unsafe code />
|
| 377 |
+
|
| 378 |
+
def convert_state_dict_legacy_attn_format(self, state_dict, network_alphas):
|
| 379 |
+
is_new_lora_format = all(
|
| 380 |
+
key.startswith(self.unet_name) or key.startswith(self.text_encoder_name) for key in state_dict.keys()
|
| 381 |
+
)
|
| 382 |
+
if is_new_lora_format:
|
| 383 |
+
# Strip the `"unet"` prefix.
|
| 384 |
+
is_text_encoder_present = any(key.startswith(self.text_encoder_name) for key in state_dict.keys())
|
| 385 |
+
if is_text_encoder_present:
|
| 386 |
+
warn_message = "The state_dict contains LoRA params corresponding to the text encoder which are not being used here. To use both UNet and text encoder related LoRA params, use [`pipe.load_lora_weights()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.load_lora_weights)."
|
| 387 |
+
logger.warn(warn_message)
|
| 388 |
+
unet_keys = [k for k in state_dict.keys() if k.startswith(self.unet_name)]
|
| 389 |
+
state_dict = {k.replace(f"{self.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
|
| 390 |
+
|
| 391 |
+
# change processor format to 'pure' LoRACompatibleLinear format
|
| 392 |
+
if any("processor" in k.split(".") for k in state_dict.keys()):
|
| 393 |
+
|
| 394 |
+
def format_to_lora_compatible(key):
|
| 395 |
+
if "processor" not in key.split("."):
|
| 396 |
+
return key
|
| 397 |
+
return key.replace(".processor", "").replace("to_out_lora", "to_out.0.lora").replace("_lora", ".lora")
|
| 398 |
+
|
| 399 |
+
state_dict = {format_to_lora_compatible(k): v for k, v in state_dict.items()}
|
| 400 |
+
|
| 401 |
+
if network_alphas is not None:
|
| 402 |
+
network_alphas = {format_to_lora_compatible(k): v for k, v in network_alphas.items()}
|
| 403 |
+
return state_dict, network_alphas
|
| 404 |
+
|
| 405 |
+
def save_attn_procs(
|
| 406 |
+
self,
|
| 407 |
+
save_directory: Union[str, os.PathLike],
|
| 408 |
+
is_main_process: bool = True,
|
| 409 |
+
weight_name: str = None,
|
| 410 |
+
save_function: Callable = None,
|
| 411 |
+
safe_serialization: bool = True,
|
| 412 |
+
**kwargs,
|
| 413 |
+
):
|
| 414 |
+
r"""
|
| 415 |
+
Save attention processor layers to a directory so that it can be reloaded with the
|
| 416 |
+
[`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] method.
|
| 417 |
+
|
| 418 |
+
Arguments:
|
| 419 |
+
save_directory (`str` or `os.PathLike`):
|
| 420 |
+
Directory to save an attention processor to (will be created if it doesn't exist).
|
| 421 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
| 422 |
+
Whether the process calling this is the main process or not. Useful during distributed training and you
|
| 423 |
+
need to call this function on all processes. In this case, set `is_main_process=True` only on the main
|
| 424 |
+
process to avoid race conditions.
|
| 425 |
+
save_function (`Callable`):
|
| 426 |
+
The function to use to save the state dictionary. Useful during distributed training when you need to
|
| 427 |
+
replace `torch.save` with another method. Can be configured with the environment variable
|
| 428 |
+
`DIFFUSERS_SAVE_MODE`.
|
| 429 |
+
safe_serialization (`bool`, *optional*, defaults to `True`):
|
| 430 |
+
Whether to save the model using `safetensors` or with `pickle`.
|
| 431 |
+
|
| 432 |
+
Example:
|
| 433 |
+
|
| 434 |
+
```py
|
| 435 |
+
import torch
|
| 436 |
+
from diffusers import DiffusionPipeline
|
| 437 |
+
|
| 438 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 439 |
+
"CompVis/stable-diffusion-v1-4",
|
| 440 |
+
torch_dtype=torch.float16,
|
| 441 |
+
).to("cuda")
|
| 442 |
+
pipeline.unet.load_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
|
| 443 |
+
pipeline.unet.save_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
|
| 444 |
+
```
|
| 445 |
+
"""
|
| 446 |
+
from ..models.attention_processor import (
|
| 447 |
+
CustomDiffusionAttnProcessor,
|
| 448 |
+
CustomDiffusionAttnProcessor2_0,
|
| 449 |
+
CustomDiffusionXFormersAttnProcessor,
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
if os.path.isfile(save_directory):
|
| 453 |
+
logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
|
| 454 |
+
return
|
| 455 |
+
|
| 456 |
+
if save_function is None:
|
| 457 |
+
if safe_serialization:
|
| 458 |
+
|
| 459 |
+
def save_function(weights, filename):
|
| 460 |
+
return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
|
| 461 |
+
|
| 462 |
+
else:
|
| 463 |
+
save_function = torch.save
|
| 464 |
+
|
| 465 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 466 |
+
|
| 467 |
+
is_custom_diffusion = any(
|
| 468 |
+
isinstance(
|
| 469 |
+
x,
|
| 470 |
+
(CustomDiffusionAttnProcessor, CustomDiffusionAttnProcessor2_0, CustomDiffusionXFormersAttnProcessor),
|
| 471 |
+
)
|
| 472 |
+
for (_, x) in self.attn_processors.items()
|
| 473 |
+
)
|
| 474 |
+
if is_custom_diffusion:
|
| 475 |
+
model_to_save = AttnProcsLayers(
|
| 476 |
+
{
|
| 477 |
+
y: x
|
| 478 |
+
for (y, x) in self.attn_processors.items()
|
| 479 |
+
if isinstance(
|
| 480 |
+
x,
|
| 481 |
+
(
|
| 482 |
+
CustomDiffusionAttnProcessor,
|
| 483 |
+
CustomDiffusionAttnProcessor2_0,
|
| 484 |
+
CustomDiffusionXFormersAttnProcessor,
|
| 485 |
+
),
|
| 486 |
+
)
|
| 487 |
+
}
|
| 488 |
+
)
|
| 489 |
+
state_dict = model_to_save.state_dict()
|
| 490 |
+
for name, attn in self.attn_processors.items():
|
| 491 |
+
if len(attn.state_dict()) == 0:
|
| 492 |
+
state_dict[name] = {}
|
| 493 |
+
else:
|
| 494 |
+
model_to_save = AttnProcsLayers(self.attn_processors)
|
| 495 |
+
state_dict = model_to_save.state_dict()
|
| 496 |
+
|
| 497 |
+
if weight_name is None:
|
| 498 |
+
if safe_serialization:
|
| 499 |
+
weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE if is_custom_diffusion else LORA_WEIGHT_NAME_SAFE
|
| 500 |
+
else:
|
| 501 |
+
weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME if is_custom_diffusion else LORA_WEIGHT_NAME
|
| 502 |
+
|
| 503 |
+
# Save the model
|
| 504 |
+
save_function(state_dict, os.path.join(save_directory, weight_name))
|
| 505 |
+
logger.info(f"Model weights saved in {os.path.join(save_directory, weight_name)}")
|
| 506 |
+
|
| 507 |
+
def fuse_lora(self, lora_scale=1.0, safe_fusing=False):
|
| 508 |
+
self.lora_scale = lora_scale
|
| 509 |
+
self._safe_fusing = safe_fusing
|
| 510 |
+
self.apply(self._fuse_lora_apply)
|
| 511 |
+
|
| 512 |
+
def _fuse_lora_apply(self, module):
|
| 513 |
+
if not USE_PEFT_BACKEND:
|
| 514 |
+
if hasattr(module, "_fuse_lora"):
|
| 515 |
+
module._fuse_lora(self.lora_scale, self._safe_fusing)
|
| 516 |
+
else:
|
| 517 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 518 |
+
|
| 519 |
+
if isinstance(module, BaseTunerLayer):
|
| 520 |
+
if self.lora_scale != 1.0:
|
| 521 |
+
module.scale_layer(self.lora_scale)
|
| 522 |
+
module.merge(safe_merge=self._safe_fusing)
|
| 523 |
+
|
| 524 |
+
def unfuse_lora(self):
|
| 525 |
+
self.apply(self._unfuse_lora_apply)
|
| 526 |
+
|
| 527 |
+
def _unfuse_lora_apply(self, module):
|
| 528 |
+
if not USE_PEFT_BACKEND:
|
| 529 |
+
if hasattr(module, "_unfuse_lora"):
|
| 530 |
+
module._unfuse_lora()
|
| 531 |
+
else:
|
| 532 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 533 |
+
|
| 534 |
+
if isinstance(module, BaseTunerLayer):
|
| 535 |
+
module.unmerge()
|
| 536 |
+
|
| 537 |
+
def set_adapters(
|
| 538 |
+
self,
|
| 539 |
+
adapter_names: Union[List[str], str],
|
| 540 |
+
weights: Optional[Union[List[float], float]] = None,
|
| 541 |
+
):
|
| 542 |
+
"""
|
| 543 |
+
Set the currently active adapters for use in the UNet.
|
| 544 |
+
|
| 545 |
+
Args:
|
| 546 |
+
adapter_names (`List[str]` or `str`):
|
| 547 |
+
The names of the adapters to use.
|
| 548 |
+
adapter_weights (`Union[List[float], float]`, *optional*):
|
| 549 |
+
The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
|
| 550 |
+
adapters.
|
| 551 |
+
|
| 552 |
+
Example:
|
| 553 |
+
|
| 554 |
+
```py
|
| 555 |
+
from diffusers import AutoPipelineForText2Image
|
| 556 |
+
import torch
|
| 557 |
+
|
| 558 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 559 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 560 |
+
).to("cuda")
|
| 561 |
+
pipeline.load_lora_weights(
|
| 562 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
|
| 563 |
+
)
|
| 564 |
+
pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
|
| 565 |
+
pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
|
| 566 |
+
```
|
| 567 |
+
"""
|
| 568 |
+
if not USE_PEFT_BACKEND:
|
| 569 |
+
raise ValueError("PEFT backend is required for `set_adapters()`.")
|
| 570 |
+
|
| 571 |
+
adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
|
| 572 |
+
|
| 573 |
+
if weights is None:
|
| 574 |
+
weights = [1.0] * len(adapter_names)
|
| 575 |
+
elif isinstance(weights, float):
|
| 576 |
+
weights = [weights] * len(adapter_names)
|
| 577 |
+
|
| 578 |
+
if len(adapter_names) != len(weights):
|
| 579 |
+
raise ValueError(
|
| 580 |
+
f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
set_weights_and_activate_adapters(self, adapter_names, weights)
|
| 584 |
+
|
| 585 |
+
def disable_lora(self):
|
| 586 |
+
"""
|
| 587 |
+
Disable the UNet's active LoRA layers.
|
| 588 |
+
|
| 589 |
+
Example:
|
| 590 |
+
|
| 591 |
+
```py
|
| 592 |
+
from diffusers import AutoPipelineForText2Image
|
| 593 |
+
import torch
|
| 594 |
+
|
| 595 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 596 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 597 |
+
).to("cuda")
|
| 598 |
+
pipeline.load_lora_weights(
|
| 599 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
|
| 600 |
+
)
|
| 601 |
+
pipeline.disable_lora()
|
| 602 |
+
```
|
| 603 |
+
"""
|
| 604 |
+
if not USE_PEFT_BACKEND:
|
| 605 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 606 |
+
set_adapter_layers(self, enabled=False)
|
| 607 |
+
|
| 608 |
+
def enable_lora(self):
|
| 609 |
+
"""
|
| 610 |
+
Enable the UNet's active LoRA layers.
|
| 611 |
+
|
| 612 |
+
Example:
|
| 613 |
+
|
| 614 |
+
```py
|
| 615 |
+
from diffusers import AutoPipelineForText2Image
|
| 616 |
+
import torch
|
| 617 |
+
|
| 618 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 619 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 620 |
+
).to("cuda")
|
| 621 |
+
pipeline.load_lora_weights(
|
| 622 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
|
| 623 |
+
)
|
| 624 |
+
pipeline.enable_lora()
|
| 625 |
+
```
|
| 626 |
+
"""
|
| 627 |
+
if not USE_PEFT_BACKEND:
|
| 628 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 629 |
+
set_adapter_layers(self, enabled=True)
|
| 630 |
+
|
| 631 |
+
def delete_adapters(self, adapter_names: Union[List[str], str]):
|
| 632 |
+
"""
|
| 633 |
+
Delete an adapter's LoRA layers from the UNet.
|
| 634 |
+
|
| 635 |
+
Args:
|
| 636 |
+
adapter_names (`Union[List[str], str]`):
|
| 637 |
+
The names (single string or list of strings) of the adapter to delete.
|
| 638 |
+
|
| 639 |
+
Example:
|
| 640 |
+
|
| 641 |
+
```py
|
| 642 |
+
from diffusers import AutoPipelineForText2Image
|
| 643 |
+
import torch
|
| 644 |
+
|
| 645 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 646 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 647 |
+
).to("cuda")
|
| 648 |
+
pipeline.load_lora_weights(
|
| 649 |
+
"jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
|
| 650 |
+
)
|
| 651 |
+
pipeline.delete_adapters("cinematic")
|
| 652 |
+
```
|
| 653 |
+
"""
|
| 654 |
+
if not USE_PEFT_BACKEND:
|
| 655 |
+
raise ValueError("PEFT backend is required for this method.")
|
| 656 |
+
|
| 657 |
+
if isinstance(adapter_names, str):
|
| 658 |
+
adapter_names = [adapter_names]
|
| 659 |
+
|
| 660 |
+
for adapter_name in adapter_names:
|
| 661 |
+
delete_adapter_layers(self, adapter_name)
|
| 662 |
+
|
| 663 |
+
# Pop also the corresponding adapter from the config
|
| 664 |
+
if hasattr(self, "peft_config"):
|
| 665 |
+
self.peft_config.pop(adapter_name, None)
|
| 666 |
+
|
| 667 |
+
def _load_ip_adapter_weights(self, state_dict):
|
| 668 |
+
from ..models.attention_processor import (
|
| 669 |
+
AttnProcessor,
|
| 670 |
+
AttnProcessor2_0,
|
| 671 |
+
IPAdapterAttnProcessor,
|
| 672 |
+
IPAdapterAttnProcessor2_0,
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
# set ip-adapter cross-attention processors & load state_dict
|
| 676 |
+
attn_procs = {}
|
| 677 |
+
key_id = 1
|
| 678 |
+
for name in self.attn_processors.keys():
|
| 679 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else self.config.cross_attention_dim
|
| 680 |
+
if name.startswith("mid_block"):
|
| 681 |
+
hidden_size = self.config.block_out_channels[-1]
|
| 682 |
+
elif name.startswith("up_blocks"):
|
| 683 |
+
block_id = int(name[len("up_blocks.")])
|
| 684 |
+
hidden_size = list(reversed(self.config.block_out_channels))[block_id]
|
| 685 |
+
elif name.startswith("down_blocks"):
|
| 686 |
+
block_id = int(name[len("down_blocks.")])
|
| 687 |
+
hidden_size = self.config.block_out_channels[block_id]
|
| 688 |
+
if cross_attention_dim is None or "motion_modules" in name:
|
| 689 |
+
attn_processor_class = (
|
| 690 |
+
AttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else AttnProcessor
|
| 691 |
+
)
|
| 692 |
+
attn_procs[name] = attn_processor_class()
|
| 693 |
+
else:
|
| 694 |
+
attn_processor_class = (
|
| 695 |
+
IPAdapterAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else IPAdapterAttnProcessor
|
| 696 |
+
)
|
| 697 |
+
attn_procs[name] = attn_processor_class(
|
| 698 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0
|
| 699 |
+
).to(dtype=self.dtype, device=self.device)
|
| 700 |
+
|
| 701 |
+
value_dict = {}
|
| 702 |
+
for k, w in attn_procs[name].state_dict().items():
|
| 703 |
+
value_dict.update({f"{k}": state_dict["ip_adapter"][f"{key_id}.{k}"]})
|
| 704 |
+
|
| 705 |
+
attn_procs[name].load_state_dict(value_dict)
|
| 706 |
+
key_id += 2
|
| 707 |
+
|
| 708 |
+
self.set_attn_processor(attn_procs)
|
| 709 |
+
|
| 710 |
+
# create image projection layers.
|
| 711 |
+
clip_embeddings_dim = state_dict["image_proj"]["proj.weight"].shape[-1]
|
| 712 |
+
cross_attention_dim = state_dict["image_proj"]["proj.weight"].shape[0] // 4
|
| 713 |
+
|
| 714 |
+
image_projection = ImageProjection(
|
| 715 |
+
cross_attention_dim=cross_attention_dim, image_embed_dim=clip_embeddings_dim, num_image_text_embeds=4
|
| 716 |
+
)
|
| 717 |
+
image_projection.to(dtype=self.dtype, device=self.device)
|
| 718 |
+
|
| 719 |
+
# load image projection layer weights
|
| 720 |
+
image_proj_state_dict = {}
|
| 721 |
+
image_proj_state_dict.update(
|
| 722 |
+
{
|
| 723 |
+
"image_embeds.weight": state_dict["image_proj"]["proj.weight"],
|
| 724 |
+
"image_embeds.bias": state_dict["image_proj"]["proj.bias"],
|
| 725 |
+
"norm.weight": state_dict["image_proj"]["norm.weight"],
|
| 726 |
+
"norm.bias": state_dict["image_proj"]["norm.bias"],
|
| 727 |
+
}
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
image_projection.load_state_dict(image_proj_state_dict)
|
| 731 |
+
|
| 732 |
+
self.encoder_hid_proj = image_projection.to(device=self.device, dtype=self.dtype)
|
| 733 |
+
self.config.encoder_hid_dim_type = "ip_image_proj"
|
| 734 |
+
|
| 735 |
+
delete_adapter_layers
|
diffusers/loaders/utils.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Dict
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class AttnProcsLayers(torch.nn.Module):
|
| 21 |
+
def __init__(self, state_dict: Dict[str, torch.Tensor]):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.layers = torch.nn.ModuleList(state_dict.values())
|
| 24 |
+
self.mapping = dict(enumerate(state_dict.keys()))
|
| 25 |
+
self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
|
| 26 |
+
|
| 27 |
+
# .processor for unet, .self_attn for text encoder
|
| 28 |
+
self.split_keys = [".processor", ".self_attn"]
|
| 29 |
+
|
| 30 |
+
# we add a hook to state_dict() and load_state_dict() so that the
|
| 31 |
+
# naming fits with `unet.attn_processors`
|
| 32 |
+
def map_to(module, state_dict, *args, **kwargs):
|
| 33 |
+
new_state_dict = {}
|
| 34 |
+
for key, value in state_dict.items():
|
| 35 |
+
num = int(key.split(".")[1]) # 0 is always "layers"
|
| 36 |
+
new_key = key.replace(f"layers.{num}", module.mapping[num])
|
| 37 |
+
new_state_dict[new_key] = value
|
| 38 |
+
|
| 39 |
+
return new_state_dict
|
| 40 |
+
|
| 41 |
+
def remap_key(key, state_dict):
|
| 42 |
+
for k in self.split_keys:
|
| 43 |
+
if k in key:
|
| 44 |
+
return key.split(k)[0] + k
|
| 45 |
+
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"There seems to be a problem with the state_dict: {set(state_dict.keys())}. {key} has to have one of {self.split_keys}."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def map_from(module, state_dict, *args, **kwargs):
|
| 51 |
+
all_keys = list(state_dict.keys())
|
| 52 |
+
for key in all_keys:
|
| 53 |
+
replace_key = remap_key(key, state_dict)
|
| 54 |
+
new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
|
| 55 |
+
state_dict[new_key] = state_dict[key]
|
| 56 |
+
del state_dict[key]
|
| 57 |
+
|
| 58 |
+
self._register_state_dict_hook(map_to)
|
| 59 |
+
self._register_load_state_dict_pre_hook(map_from, with_module=True)
|
diffusers/models/README.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Models
|
| 2 |
+
|
| 3 |
+
For more detail on the models, please refer to the [docs](https://huggingface.co/docs/diffusers/api/models/overview).
|
diffusers/models/__init__.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import TYPE_CHECKING
|
| 16 |
+
|
| 17 |
+
from ..utils import (
|
| 18 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 19 |
+
_LazyModule,
|
| 20 |
+
is_flax_available,
|
| 21 |
+
is_torch_available,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
_import_structure = {}
|
| 26 |
+
|
| 27 |
+
if is_torch_available():
|
| 28 |
+
_import_structure["adapter"] = ["MultiAdapter", "T2IAdapter"]
|
| 29 |
+
_import_structure["autoencoder_asym_kl"] = ["AsymmetricAutoencoderKL"]
|
| 30 |
+
_import_structure["autoencoder_kl"] = ["AutoencoderKL"]
|
| 31 |
+
_import_structure["autoencoder_kl_temporal_decoder"] = ["AutoencoderKLTemporalDecoder"]
|
| 32 |
+
_import_structure["autoencoder_tiny"] = ["AutoencoderTiny"]
|
| 33 |
+
_import_structure["consistency_decoder_vae"] = ["ConsistencyDecoderVAE"]
|
| 34 |
+
_import_structure["controlnet"] = ["ControlNetModel"]
|
| 35 |
+
_import_structure["dual_transformer_2d"] = ["DualTransformer2DModel"]
|
| 36 |
+
_import_structure["modeling_utils"] = ["ModelMixin"]
|
| 37 |
+
_import_structure["prior_transformer"] = ["PriorTransformer"]
|
| 38 |
+
_import_structure["t5_film_transformer"] = ["T5FilmDecoder"]
|
| 39 |
+
_import_structure["transformer_2d"] = ["Transformer2DModel"]
|
| 40 |
+
_import_structure["transformer_temporal"] = ["TransformerTemporalModel"]
|
| 41 |
+
_import_structure["unet_1d"] = ["UNet1DModel"]
|
| 42 |
+
_import_structure["unet_2d"] = ["UNet2DModel"]
|
| 43 |
+
_import_structure["unet_2d_condition"] = ["UNet2DConditionModel"]
|
| 44 |
+
_import_structure["unet_3d_condition"] = ["UNet3DConditionModel"]
|
| 45 |
+
_import_structure["unet_kandi3"] = ["Kandinsky3UNet"]
|
| 46 |
+
_import_structure["unet_motion_model"] = ["MotionAdapter", "UNetMotionModel"]
|
| 47 |
+
_import_structure["unet_spatio_temporal_condition"] = ["UNetSpatioTemporalConditionModel"]
|
| 48 |
+
_import_structure["vq_model"] = ["VQModel"]
|
| 49 |
+
|
| 50 |
+
if is_flax_available():
|
| 51 |
+
_import_structure["controlnet_flax"] = ["FlaxControlNetModel"]
|
| 52 |
+
_import_structure["unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
|
| 53 |
+
_import_structure["vae_flax"] = ["FlaxAutoencoderKL"]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 57 |
+
if is_torch_available():
|
| 58 |
+
from .adapter import MultiAdapter, T2IAdapter
|
| 59 |
+
from .autoencoder_asym_kl import AsymmetricAutoencoderKL
|
| 60 |
+
from .autoencoder_kl import AutoencoderKL
|
| 61 |
+
from .autoencoder_kl_temporal_decoder import AutoencoderKLTemporalDecoder
|
| 62 |
+
from .autoencoder_tiny import AutoencoderTiny
|
| 63 |
+
from .consistency_decoder_vae import ConsistencyDecoderVAE
|
| 64 |
+
from .controlnet import ControlNetModel
|
| 65 |
+
from .dual_transformer_2d import DualTransformer2DModel
|
| 66 |
+
from .modeling_utils import ModelMixin
|
| 67 |
+
from .prior_transformer import PriorTransformer
|
| 68 |
+
from .t5_film_transformer import T5FilmDecoder
|
| 69 |
+
from .transformer_2d import Transformer2DModel
|
| 70 |
+
from .transformer_temporal import TransformerTemporalModel
|
| 71 |
+
from .unet_1d import UNet1DModel
|
| 72 |
+
from .unet_2d import UNet2DModel
|
| 73 |
+
from .unet_2d_condition import UNet2DConditionModel
|
| 74 |
+
from .unet_3d_condition import UNet3DConditionModel
|
| 75 |
+
from .unet_kandi3 import Kandinsky3UNet
|
| 76 |
+
from .unet_motion_model import MotionAdapter, UNetMotionModel
|
| 77 |
+
from .unet_spatio_temporal_condition import UNetSpatioTemporalConditionModel
|
| 78 |
+
from .vq_model import VQModel
|
| 79 |
+
|
| 80 |
+
if is_flax_available():
|
| 81 |
+
from .controlnet_flax import FlaxControlNetModel
|
| 82 |
+
from .unet_2d_condition_flax import FlaxUNet2DConditionModel
|
| 83 |
+
from .vae_flax import FlaxAutoencoderKL
|
| 84 |
+
|
| 85 |
+
else:
|
| 86 |
+
import sys
|
| 87 |
+
|
| 88 |
+
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
diffusers/models/activations.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from torch import nn
|
| 19 |
+
|
| 20 |
+
from ..utils import USE_PEFT_BACKEND
|
| 21 |
+
from .lora import LoRACompatibleLinear
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
ACTIVATION_FUNCTIONS = {
|
| 25 |
+
"swish": nn.SiLU(),
|
| 26 |
+
"silu": nn.SiLU(),
|
| 27 |
+
"mish": nn.Mish(),
|
| 28 |
+
"gelu": nn.GELU(),
|
| 29 |
+
"relu": nn.ReLU(),
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_activation(act_fn: str) -> nn.Module:
|
| 34 |
+
"""Helper function to get activation function from string.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
act_fn (str): Name of activation function.
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
nn.Module: Activation function.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
act_fn = act_fn.lower()
|
| 44 |
+
if act_fn in ACTIVATION_FUNCTIONS:
|
| 45 |
+
return ACTIVATION_FUNCTIONS[act_fn]
|
| 46 |
+
else:
|
| 47 |
+
raise ValueError(f"Unsupported activation function: {act_fn}")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class GELU(nn.Module):
|
| 51 |
+
r"""
|
| 52 |
+
GELU activation function with tanh approximation support with `approximate="tanh"`.
|
| 53 |
+
|
| 54 |
+
Parameters:
|
| 55 |
+
dim_in (`int`): The number of channels in the input.
|
| 56 |
+
dim_out (`int`): The number of channels in the output.
|
| 57 |
+
approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, dim_in: int, dim_out: int, approximate: str = "none"):
|
| 61 |
+
super().__init__()
|
| 62 |
+
self.proj = nn.Linear(dim_in, dim_out)
|
| 63 |
+
self.approximate = approximate
|
| 64 |
+
|
| 65 |
+
def gelu(self, gate: torch.Tensor) -> torch.Tensor:
|
| 66 |
+
if gate.device.type != "mps":
|
| 67 |
+
return F.gelu(gate, approximate=self.approximate)
|
| 68 |
+
# mps: gelu is not implemented for float16
|
| 69 |
+
return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
|
| 70 |
+
|
| 71 |
+
def forward(self, hidden_states):
|
| 72 |
+
hidden_states = self.proj(hidden_states)
|
| 73 |
+
hidden_states = self.gelu(hidden_states)
|
| 74 |
+
return hidden_states
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class GEGLU(nn.Module):
|
| 78 |
+
r"""
|
| 79 |
+
A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
|
| 80 |
+
|
| 81 |
+
Parameters:
|
| 82 |
+
dim_in (`int`): The number of channels in the input.
|
| 83 |
+
dim_out (`int`): The number of channels in the output.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, dim_in: int, dim_out: int):
|
| 87 |
+
super().__init__()
|
| 88 |
+
linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
|
| 89 |
+
|
| 90 |
+
self.proj = linear_cls(dim_in, dim_out * 2)
|
| 91 |
+
|
| 92 |
+
def gelu(self, gate: torch.Tensor) -> torch.Tensor:
|
| 93 |
+
if gate.device.type != "mps":
|
| 94 |
+
return F.gelu(gate)
|
| 95 |
+
# mps: gelu is not implemented for float16
|
| 96 |
+
return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
|
| 97 |
+
|
| 98 |
+
def forward(self, hidden_states, scale: float = 1.0):
|
| 99 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
| 100 |
+
hidden_states, gate = self.proj(hidden_states, *args).chunk(2, dim=-1)
|
| 101 |
+
return hidden_states * self.gelu(gate)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class ApproximateGELU(nn.Module):
|
| 105 |
+
r"""
|
| 106 |
+
The approximate form of the Gaussian Error Linear Unit (GELU). For more details, see section 2 of this
|
| 107 |
+
[paper](https://arxiv.org/abs/1606.08415).
|
| 108 |
+
|
| 109 |
+
Parameters:
|
| 110 |
+
dim_in (`int`): The number of channels in the input.
|
| 111 |
+
dim_out (`int`): The number of channels in the output.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
def __init__(self, dim_in: int, dim_out: int):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.proj = nn.Linear(dim_in, dim_out)
|
| 117 |
+
|
| 118 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 119 |
+
x = self.proj(x)
|
| 120 |
+
return x * torch.sigmoid(1.702 * x)
|
diffusers/models/adapter.py
ADDED
|
@@ -0,0 +1,584 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import os
|
| 15 |
+
from typing import Callable, List, Optional, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
|
| 20 |
+
from ..configuration_utils import ConfigMixin, register_to_config
|
| 21 |
+
from ..utils import logging
|
| 22 |
+
from .modeling_utils import ModelMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class MultiAdapter(ModelMixin):
|
| 29 |
+
r"""
|
| 30 |
+
MultiAdapter is a wrapper model that contains multiple adapter models and merges their outputs according to
|
| 31 |
+
user-assigned weighting.
|
| 32 |
+
|
| 33 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
|
| 34 |
+
implements for all the model (such as downloading or saving, etc.)
|
| 35 |
+
|
| 36 |
+
Parameters:
|
| 37 |
+
adapters (`List[T2IAdapter]`, *optional*, defaults to None):
|
| 38 |
+
A list of `T2IAdapter` model instances.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, adapters: List["T2IAdapter"]):
|
| 42 |
+
super(MultiAdapter, self).__init__()
|
| 43 |
+
|
| 44 |
+
self.num_adapter = len(adapters)
|
| 45 |
+
self.adapters = nn.ModuleList(adapters)
|
| 46 |
+
|
| 47 |
+
if len(adapters) == 0:
|
| 48 |
+
raise ValueError("Expecting at least one adapter")
|
| 49 |
+
|
| 50 |
+
if len(adapters) == 1:
|
| 51 |
+
raise ValueError("For a single adapter, please use the `T2IAdapter` class instead of `MultiAdapter`")
|
| 52 |
+
|
| 53 |
+
# The outputs from each adapter are added together with a weight.
|
| 54 |
+
# This means that the change in dimensions from downsampling must
|
| 55 |
+
# be the same for all adapters. Inductively, it also means the
|
| 56 |
+
# downscale_factor and total_downscale_factor must be the same for all
|
| 57 |
+
# adapters.
|
| 58 |
+
first_adapter_total_downscale_factor = adapters[0].total_downscale_factor
|
| 59 |
+
first_adapter_downscale_factor = adapters[0].downscale_factor
|
| 60 |
+
for idx in range(1, len(adapters)):
|
| 61 |
+
if (
|
| 62 |
+
adapters[idx].total_downscale_factor != first_adapter_total_downscale_factor
|
| 63 |
+
or adapters[idx].downscale_factor != first_adapter_downscale_factor
|
| 64 |
+
):
|
| 65 |
+
raise ValueError(
|
| 66 |
+
f"Expecting all adapters to have the same downscaling behavior, but got:\n"
|
| 67 |
+
f"adapters[0].total_downscale_factor={first_adapter_total_downscale_factor}\n"
|
| 68 |
+
f"adapters[0].downscale_factor={first_adapter_downscale_factor}\n"
|
| 69 |
+
f"adapter[`{idx}`].total_downscale_factor={adapters[idx].total_downscale_factor}\n"
|
| 70 |
+
f"adapter[`{idx}`].downscale_factor={adapters[idx].downscale_factor}"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
self.total_downscale_factor = first_adapter_total_downscale_factor
|
| 74 |
+
self.downscale_factor = first_adapter_downscale_factor
|
| 75 |
+
|
| 76 |
+
def forward(self, xs: torch.Tensor, adapter_weights: Optional[List[float]] = None) -> List[torch.Tensor]:
|
| 77 |
+
r"""
|
| 78 |
+
Args:
|
| 79 |
+
xs (`torch.Tensor`):
|
| 80 |
+
(batch, channel, height, width) input images for multiple adapter models concated along dimension 1,
|
| 81 |
+
`channel` should equal to `num_adapter` * "number of channel of image".
|
| 82 |
+
adapter_weights (`List[float]`, *optional*, defaults to None):
|
| 83 |
+
List of floats representing the weight which will be multiply to each adapter's output before adding
|
| 84 |
+
them together.
|
| 85 |
+
"""
|
| 86 |
+
if adapter_weights is None:
|
| 87 |
+
adapter_weights = torch.tensor([1 / self.num_adapter] * self.num_adapter)
|
| 88 |
+
else:
|
| 89 |
+
adapter_weights = torch.tensor(adapter_weights)
|
| 90 |
+
|
| 91 |
+
accume_state = None
|
| 92 |
+
for x, w, adapter in zip(xs, adapter_weights, self.adapters):
|
| 93 |
+
features = adapter(x)
|
| 94 |
+
if accume_state is None:
|
| 95 |
+
accume_state = features
|
| 96 |
+
for i in range(len(accume_state)):
|
| 97 |
+
accume_state[i] = w * accume_state[i]
|
| 98 |
+
else:
|
| 99 |
+
for i in range(len(features)):
|
| 100 |
+
accume_state[i] += w * features[i]
|
| 101 |
+
return accume_state
|
| 102 |
+
|
| 103 |
+
def save_pretrained(
|
| 104 |
+
self,
|
| 105 |
+
save_directory: Union[str, os.PathLike],
|
| 106 |
+
is_main_process: bool = True,
|
| 107 |
+
save_function: Callable = None,
|
| 108 |
+
safe_serialization: bool = True,
|
| 109 |
+
variant: Optional[str] = None,
|
| 110 |
+
):
|
| 111 |
+
"""
|
| 112 |
+
Save a model and its configuration file to a directory, so that it can be re-loaded using the
|
| 113 |
+
`[`~models.adapter.MultiAdapter.from_pretrained`]` class method.
|
| 114 |
+
|
| 115 |
+
Arguments:
|
| 116 |
+
save_directory (`str` or `os.PathLike`):
|
| 117 |
+
Directory to which to save. Will be created if it doesn't exist.
|
| 118 |
+
is_main_process (`bool`, *optional*, defaults to `True`):
|
| 119 |
+
Whether the process calling this is the main process or not. Useful when in distributed training like
|
| 120 |
+
TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on
|
| 121 |
+
the main process to avoid race conditions.
|
| 122 |
+
save_function (`Callable`):
|
| 123 |
+
The function to use to save the state dictionary. Useful on distributed training like TPUs when one
|
| 124 |
+
need to replace `torch.save` by another method. Can be configured with the environment variable
|
| 125 |
+
`DIFFUSERS_SAVE_MODE`.
|
| 126 |
+
safe_serialization (`bool`, *optional*, defaults to `True`):
|
| 127 |
+
Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
|
| 128 |
+
variant (`str`, *optional*):
|
| 129 |
+
If specified, weights are saved in the format pytorch_model.<variant>.bin.
|
| 130 |
+
"""
|
| 131 |
+
idx = 0
|
| 132 |
+
model_path_to_save = save_directory
|
| 133 |
+
for adapter in self.adapters:
|
| 134 |
+
adapter.save_pretrained(
|
| 135 |
+
model_path_to_save,
|
| 136 |
+
is_main_process=is_main_process,
|
| 137 |
+
save_function=save_function,
|
| 138 |
+
safe_serialization=safe_serialization,
|
| 139 |
+
variant=variant,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
idx += 1
|
| 143 |
+
model_path_to_save = model_path_to_save + f"_{idx}"
|
| 144 |
+
|
| 145 |
+
@classmethod
|
| 146 |
+
def from_pretrained(cls, pretrained_model_path: Optional[Union[str, os.PathLike]], **kwargs):
|
| 147 |
+
r"""
|
| 148 |
+
Instantiate a pretrained MultiAdapter model from multiple pre-trained adapter models.
|
| 149 |
+
|
| 150 |
+
The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
|
| 151 |
+
the model, you should first set it back in training mode with `model.train()`.
|
| 152 |
+
|
| 153 |
+
The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
|
| 154 |
+
pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
|
| 155 |
+
task.
|
| 156 |
+
|
| 157 |
+
The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
|
| 158 |
+
weights are discarded.
|
| 159 |
+
|
| 160 |
+
Parameters:
|
| 161 |
+
pretrained_model_path (`os.PathLike`):
|
| 162 |
+
A path to a *directory* containing model weights saved using
|
| 163 |
+
[`~diffusers.models.adapter.MultiAdapter.save_pretrained`], e.g., `./my_model_directory/adapter`.
|
| 164 |
+
torch_dtype (`str` or `torch.dtype`, *optional*):
|
| 165 |
+
Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype
|
| 166 |
+
will be automatically derived from the model's weights.
|
| 167 |
+
output_loading_info(`bool`, *optional*, defaults to `False`):
|
| 168 |
+
Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
|
| 169 |
+
device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
|
| 170 |
+
A map that specifies where each submodule should go. It doesn't need to be refined to each
|
| 171 |
+
parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
|
| 172 |
+
same device.
|
| 173 |
+
|
| 174 |
+
To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
|
| 175 |
+
more information about each option see [designing a device
|
| 176 |
+
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
|
| 177 |
+
max_memory (`Dict`, *optional*):
|
| 178 |
+
A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
|
| 179 |
+
GPU and the available CPU RAM if unset.
|
| 180 |
+
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
|
| 181 |
+
Speed up model loading by not initializing the weights and only loading the pre-trained weights. This
|
| 182 |
+
also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the
|
| 183 |
+
model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch,
|
| 184 |
+
setting this argument to `True` will raise an error.
|
| 185 |
+
variant (`str`, *optional*):
|
| 186 |
+
If specified load weights from `variant` filename, *e.g.* pytorch_model.<variant>.bin. `variant` is
|
| 187 |
+
ignored when using `from_flax`.
|
| 188 |
+
use_safetensors (`bool`, *optional*, defaults to `None`):
|
| 189 |
+
If set to `None`, the `safetensors` weights will be downloaded if they're available **and** if the
|
| 190 |
+
`safetensors` library is installed. If set to `True`, the model will be forcibly loaded from
|
| 191 |
+
`safetensors` weights. If set to `False`, loading will *not* use `safetensors`.
|
| 192 |
+
"""
|
| 193 |
+
idx = 0
|
| 194 |
+
adapters = []
|
| 195 |
+
|
| 196 |
+
# load adapter and append to list until no adapter directory exists anymore
|
| 197 |
+
# first adapter has to be saved under `./mydirectory/adapter` to be compliant with `DiffusionPipeline.from_pretrained`
|
| 198 |
+
# second, third, ... adapters have to be saved under `./mydirectory/adapter_1`, `./mydirectory/adapter_2`, ...
|
| 199 |
+
model_path_to_load = pretrained_model_path
|
| 200 |
+
while os.path.isdir(model_path_to_load):
|
| 201 |
+
adapter = T2IAdapter.from_pretrained(model_path_to_load, **kwargs)
|
| 202 |
+
adapters.append(adapter)
|
| 203 |
+
|
| 204 |
+
idx += 1
|
| 205 |
+
model_path_to_load = pretrained_model_path + f"_{idx}"
|
| 206 |
+
|
| 207 |
+
logger.info(f"{len(adapters)} adapters loaded from {pretrained_model_path}.")
|
| 208 |
+
|
| 209 |
+
if len(adapters) == 0:
|
| 210 |
+
raise ValueError(
|
| 211 |
+
f"No T2IAdapters found under {os.path.dirname(pretrained_model_path)}. Expected at least {pretrained_model_path + '_0'}."
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
return cls(adapters)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class T2IAdapter(ModelMixin, ConfigMixin):
|
| 218 |
+
r"""
|
| 219 |
+
A simple ResNet-like model that accepts images containing control signals such as keyposes and depth. The model
|
| 220 |
+
generates multiple feature maps that are used as additional conditioning in [`UNet2DConditionModel`]. The model's
|
| 221 |
+
architecture follows the original implementation of
|
| 222 |
+
[Adapter](https://github.com/TencentARC/T2I-Adapter/blob/686de4681515662c0ac2ffa07bf5dda83af1038a/ldm/modules/encoders/adapter.py#L97)
|
| 223 |
+
and
|
| 224 |
+
[AdapterLight](https://github.com/TencentARC/T2I-Adapter/blob/686de4681515662c0ac2ffa07bf5dda83af1038a/ldm/modules/encoders/adapter.py#L235).
|
| 225 |
+
|
| 226 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
|
| 227 |
+
implements for all the model (such as downloading or saving, etc.)
|
| 228 |
+
|
| 229 |
+
Parameters:
|
| 230 |
+
in_channels (`int`, *optional*, defaults to 3):
|
| 231 |
+
Number of channels of Aapter's input(*control image*). Set this parameter to 1 if you're using gray scale
|
| 232 |
+
image as *control image*.
|
| 233 |
+
channels (`List[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
|
| 234 |
+
The number of channel of each downsample block's output hidden state. The `len(block_out_channels)` will
|
| 235 |
+
also determine the number of downsample blocks in the Adapter.
|
| 236 |
+
num_res_blocks (`int`, *optional*, defaults to 2):
|
| 237 |
+
Number of ResNet blocks in each downsample block.
|
| 238 |
+
downscale_factor (`int`, *optional*, defaults to 8):
|
| 239 |
+
A factor that determines the total downscale factor of the Adapter.
|
| 240 |
+
adapter_type (`str`, *optional*, defaults to `full_adapter`):
|
| 241 |
+
The type of Adapter to use. Choose either `full_adapter` or `full_adapter_xl` or `light_adapter`.
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
@register_to_config
|
| 245 |
+
def __init__(
|
| 246 |
+
self,
|
| 247 |
+
in_channels: int = 3,
|
| 248 |
+
channels: List[int] = [320, 640, 1280, 1280],
|
| 249 |
+
num_res_blocks: int = 2,
|
| 250 |
+
downscale_factor: int = 8,
|
| 251 |
+
adapter_type: str = "full_adapter",
|
| 252 |
+
):
|
| 253 |
+
super().__init__()
|
| 254 |
+
|
| 255 |
+
if adapter_type == "full_adapter":
|
| 256 |
+
self.adapter = FullAdapter(in_channels, channels, num_res_blocks, downscale_factor)
|
| 257 |
+
elif adapter_type == "full_adapter_xl":
|
| 258 |
+
self.adapter = FullAdapterXL(in_channels, channels, num_res_blocks, downscale_factor)
|
| 259 |
+
elif adapter_type == "light_adapter":
|
| 260 |
+
self.adapter = LightAdapter(in_channels, channels, num_res_blocks, downscale_factor)
|
| 261 |
+
else:
|
| 262 |
+
raise ValueError(
|
| 263 |
+
f"Unsupported adapter_type: '{adapter_type}'. Choose either 'full_adapter' or "
|
| 264 |
+
"'full_adapter_xl' or 'light_adapter'."
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
|
| 268 |
+
r"""
|
| 269 |
+
This function processes the input tensor `x` through the adapter model and returns a list of feature tensors,
|
| 270 |
+
each representing information extracted at a different scale from the input. The length of the list is
|
| 271 |
+
determined by the number of downsample blocks in the Adapter, as specified by the `channels` and
|
| 272 |
+
`num_res_blocks` parameters during initialization.
|
| 273 |
+
"""
|
| 274 |
+
return self.adapter(x)
|
| 275 |
+
|
| 276 |
+
@property
|
| 277 |
+
def total_downscale_factor(self):
|
| 278 |
+
return self.adapter.total_downscale_factor
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def downscale_factor(self):
|
| 282 |
+
"""The downscale factor applied in the T2I-Adapter's initial pixel unshuffle operation. If an input image's dimensions are
|
| 283 |
+
not evenly divisible by the downscale_factor then an exception will be raised.
|
| 284 |
+
"""
|
| 285 |
+
return self.adapter.unshuffle.downscale_factor
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# full adapter
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class FullAdapter(nn.Module):
|
| 292 |
+
r"""
|
| 293 |
+
See [`T2IAdapter`] for more information.
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
def __init__(
|
| 297 |
+
self,
|
| 298 |
+
in_channels: int = 3,
|
| 299 |
+
channels: List[int] = [320, 640, 1280, 1280],
|
| 300 |
+
num_res_blocks: int = 2,
|
| 301 |
+
downscale_factor: int = 8,
|
| 302 |
+
):
|
| 303 |
+
super().__init__()
|
| 304 |
+
|
| 305 |
+
in_channels = in_channels * downscale_factor**2
|
| 306 |
+
|
| 307 |
+
self.unshuffle = nn.PixelUnshuffle(downscale_factor)
|
| 308 |
+
self.conv_in = nn.Conv2d(in_channels, channels[0], kernel_size=3, padding=1)
|
| 309 |
+
|
| 310 |
+
self.body = nn.ModuleList(
|
| 311 |
+
[
|
| 312 |
+
AdapterBlock(channels[0], channels[0], num_res_blocks),
|
| 313 |
+
*[
|
| 314 |
+
AdapterBlock(channels[i - 1], channels[i], num_res_blocks, down=True)
|
| 315 |
+
for i in range(1, len(channels))
|
| 316 |
+
],
|
| 317 |
+
]
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
self.total_downscale_factor = downscale_factor * 2 ** (len(channels) - 1)
|
| 321 |
+
|
| 322 |
+
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
|
| 323 |
+
r"""
|
| 324 |
+
This method processes the input tensor `x` through the FullAdapter model and performs operations including
|
| 325 |
+
pixel unshuffling, convolution, and a stack of AdapterBlocks. It returns a list of feature tensors, each
|
| 326 |
+
capturing information at a different stage of processing within the FullAdapter model. The number of feature
|
| 327 |
+
tensors in the list is determined by the number of downsample blocks specified during initialization.
|
| 328 |
+
"""
|
| 329 |
+
x = self.unshuffle(x)
|
| 330 |
+
x = self.conv_in(x)
|
| 331 |
+
|
| 332 |
+
features = []
|
| 333 |
+
|
| 334 |
+
for block in self.body:
|
| 335 |
+
x = block(x)
|
| 336 |
+
features.append(x)
|
| 337 |
+
|
| 338 |
+
return features
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class FullAdapterXL(nn.Module):
|
| 342 |
+
r"""
|
| 343 |
+
See [`T2IAdapter`] for more information.
|
| 344 |
+
"""
|
| 345 |
+
|
| 346 |
+
def __init__(
|
| 347 |
+
self,
|
| 348 |
+
in_channels: int = 3,
|
| 349 |
+
channels: List[int] = [320, 640, 1280, 1280],
|
| 350 |
+
num_res_blocks: int = 2,
|
| 351 |
+
downscale_factor: int = 16,
|
| 352 |
+
):
|
| 353 |
+
super().__init__()
|
| 354 |
+
|
| 355 |
+
in_channels = in_channels * downscale_factor**2
|
| 356 |
+
|
| 357 |
+
self.unshuffle = nn.PixelUnshuffle(downscale_factor)
|
| 358 |
+
self.conv_in = nn.Conv2d(in_channels, channels[0], kernel_size=3, padding=1)
|
| 359 |
+
|
| 360 |
+
self.body = []
|
| 361 |
+
# blocks to extract XL features with dimensions of [320, 64, 64], [640, 64, 64], [1280, 32, 32], [1280, 32, 32]
|
| 362 |
+
for i in range(len(channels)):
|
| 363 |
+
if i == 1:
|
| 364 |
+
self.body.append(AdapterBlock(channels[i - 1], channels[i], num_res_blocks))
|
| 365 |
+
elif i == 2:
|
| 366 |
+
self.body.append(AdapterBlock(channels[i - 1], channels[i], num_res_blocks, down=True))
|
| 367 |
+
else:
|
| 368 |
+
self.body.append(AdapterBlock(channels[i], channels[i], num_res_blocks))
|
| 369 |
+
|
| 370 |
+
self.body = nn.ModuleList(self.body)
|
| 371 |
+
# XL has only one downsampling AdapterBlock.
|
| 372 |
+
self.total_downscale_factor = downscale_factor * 2
|
| 373 |
+
|
| 374 |
+
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
|
| 375 |
+
r"""
|
| 376 |
+
This method takes the tensor x as input and processes it through FullAdapterXL model. It consists of operations
|
| 377 |
+
including unshuffling pixels, applying convolution layer and appending each block into list of feature tensors.
|
| 378 |
+
"""
|
| 379 |
+
x = self.unshuffle(x)
|
| 380 |
+
x = self.conv_in(x)
|
| 381 |
+
|
| 382 |
+
features = []
|
| 383 |
+
|
| 384 |
+
for block in self.body:
|
| 385 |
+
x = block(x)
|
| 386 |
+
features.append(x)
|
| 387 |
+
|
| 388 |
+
return features
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class AdapterBlock(nn.Module):
|
| 392 |
+
r"""
|
| 393 |
+
An AdapterBlock is a helper model that contains multiple ResNet-like blocks. It is used in the `FullAdapter` and
|
| 394 |
+
`FullAdapterXL` models.
|
| 395 |
+
|
| 396 |
+
Parameters:
|
| 397 |
+
in_channels (`int`):
|
| 398 |
+
Number of channels of AdapterBlock's input.
|
| 399 |
+
out_channels (`int`):
|
| 400 |
+
Number of channels of AdapterBlock's output.
|
| 401 |
+
num_res_blocks (`int`):
|
| 402 |
+
Number of ResNet blocks in the AdapterBlock.
|
| 403 |
+
down (`bool`, *optional*, defaults to `False`):
|
| 404 |
+
Whether to perform downsampling on AdapterBlock's input.
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
def __init__(self, in_channels: int, out_channels: int, num_res_blocks: int, down: bool = False):
|
| 408 |
+
super().__init__()
|
| 409 |
+
|
| 410 |
+
self.downsample = None
|
| 411 |
+
if down:
|
| 412 |
+
self.downsample = nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True)
|
| 413 |
+
|
| 414 |
+
self.in_conv = None
|
| 415 |
+
if in_channels != out_channels:
|
| 416 |
+
self.in_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
|
| 417 |
+
|
| 418 |
+
self.resnets = nn.Sequential(
|
| 419 |
+
*[AdapterResnetBlock(out_channels) for _ in range(num_res_blocks)],
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 423 |
+
r"""
|
| 424 |
+
This method takes tensor x as input and performs operations downsampling and convolutional layers if the
|
| 425 |
+
self.downsample and self.in_conv properties of AdapterBlock model are specified. Then it applies a series of
|
| 426 |
+
residual blocks to the input tensor.
|
| 427 |
+
"""
|
| 428 |
+
if self.downsample is not None:
|
| 429 |
+
x = self.downsample(x)
|
| 430 |
+
|
| 431 |
+
if self.in_conv is not None:
|
| 432 |
+
x = self.in_conv(x)
|
| 433 |
+
|
| 434 |
+
x = self.resnets(x)
|
| 435 |
+
|
| 436 |
+
return x
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class AdapterResnetBlock(nn.Module):
|
| 440 |
+
r"""
|
| 441 |
+
An `AdapterResnetBlock` is a helper model that implements a ResNet-like block.
|
| 442 |
+
|
| 443 |
+
Parameters:
|
| 444 |
+
channels (`int`):
|
| 445 |
+
Number of channels of AdapterResnetBlock's input and output.
|
| 446 |
+
"""
|
| 447 |
+
|
| 448 |
+
def __init__(self, channels: int):
|
| 449 |
+
super().__init__()
|
| 450 |
+
self.block1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
|
| 451 |
+
self.act = nn.ReLU()
|
| 452 |
+
self.block2 = nn.Conv2d(channels, channels, kernel_size=1)
|
| 453 |
+
|
| 454 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 455 |
+
r"""
|
| 456 |
+
This method takes input tensor x and applies a convolutional layer, ReLU activation, and another convolutional
|
| 457 |
+
layer on the input tensor. It returns addition with the input tensor.
|
| 458 |
+
"""
|
| 459 |
+
|
| 460 |
+
h = self.act(self.block1(x))
|
| 461 |
+
h = self.block2(h)
|
| 462 |
+
|
| 463 |
+
return h + x
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# light adapter
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class LightAdapter(nn.Module):
|
| 470 |
+
r"""
|
| 471 |
+
See [`T2IAdapter`] for more information.
|
| 472 |
+
"""
|
| 473 |
+
|
| 474 |
+
def __init__(
|
| 475 |
+
self,
|
| 476 |
+
in_channels: int = 3,
|
| 477 |
+
channels: List[int] = [320, 640, 1280],
|
| 478 |
+
num_res_blocks: int = 4,
|
| 479 |
+
downscale_factor: int = 8,
|
| 480 |
+
):
|
| 481 |
+
super().__init__()
|
| 482 |
+
|
| 483 |
+
in_channels = in_channels * downscale_factor**2
|
| 484 |
+
|
| 485 |
+
self.unshuffle = nn.PixelUnshuffle(downscale_factor)
|
| 486 |
+
|
| 487 |
+
self.body = nn.ModuleList(
|
| 488 |
+
[
|
| 489 |
+
LightAdapterBlock(in_channels, channels[0], num_res_blocks),
|
| 490 |
+
*[
|
| 491 |
+
LightAdapterBlock(channels[i], channels[i + 1], num_res_blocks, down=True)
|
| 492 |
+
for i in range(len(channels) - 1)
|
| 493 |
+
],
|
| 494 |
+
LightAdapterBlock(channels[-1], channels[-1], num_res_blocks, down=True),
|
| 495 |
+
]
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
self.total_downscale_factor = downscale_factor * (2 ** len(channels))
|
| 499 |
+
|
| 500 |
+
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
|
| 501 |
+
r"""
|
| 502 |
+
This method takes the input tensor x and performs downscaling and appends it in list of feature tensors. Each
|
| 503 |
+
feature tensor corresponds to a different level of processing within the LightAdapter.
|
| 504 |
+
"""
|
| 505 |
+
x = self.unshuffle(x)
|
| 506 |
+
|
| 507 |
+
features = []
|
| 508 |
+
|
| 509 |
+
for block in self.body:
|
| 510 |
+
x = block(x)
|
| 511 |
+
features.append(x)
|
| 512 |
+
|
| 513 |
+
return features
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class LightAdapterBlock(nn.Module):
|
| 517 |
+
r"""
|
| 518 |
+
A `LightAdapterBlock` is a helper model that contains multiple `LightAdapterResnetBlocks`. It is used in the
|
| 519 |
+
`LightAdapter` model.
|
| 520 |
+
|
| 521 |
+
Parameters:
|
| 522 |
+
in_channels (`int`):
|
| 523 |
+
Number of channels of LightAdapterBlock's input.
|
| 524 |
+
out_channels (`int`):
|
| 525 |
+
Number of channels of LightAdapterBlock's output.
|
| 526 |
+
num_res_blocks (`int`):
|
| 527 |
+
Number of LightAdapterResnetBlocks in the LightAdapterBlock.
|
| 528 |
+
down (`bool`, *optional*, defaults to `False`):
|
| 529 |
+
Whether to perform downsampling on LightAdapterBlock's input.
|
| 530 |
+
"""
|
| 531 |
+
|
| 532 |
+
def __init__(self, in_channels: int, out_channels: int, num_res_blocks: int, down: bool = False):
|
| 533 |
+
super().__init__()
|
| 534 |
+
mid_channels = out_channels // 4
|
| 535 |
+
|
| 536 |
+
self.downsample = None
|
| 537 |
+
if down:
|
| 538 |
+
self.downsample = nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True)
|
| 539 |
+
|
| 540 |
+
self.in_conv = nn.Conv2d(in_channels, mid_channels, kernel_size=1)
|
| 541 |
+
self.resnets = nn.Sequential(*[LightAdapterResnetBlock(mid_channels) for _ in range(num_res_blocks)])
|
| 542 |
+
self.out_conv = nn.Conv2d(mid_channels, out_channels, kernel_size=1)
|
| 543 |
+
|
| 544 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 545 |
+
r"""
|
| 546 |
+
This method takes tensor x as input and performs downsampling if required. Then it applies in convolution
|
| 547 |
+
layer, a sequence of residual blocks, and out convolutional layer.
|
| 548 |
+
"""
|
| 549 |
+
if self.downsample is not None:
|
| 550 |
+
x = self.downsample(x)
|
| 551 |
+
|
| 552 |
+
x = self.in_conv(x)
|
| 553 |
+
x = self.resnets(x)
|
| 554 |
+
x = self.out_conv(x)
|
| 555 |
+
|
| 556 |
+
return x
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
class LightAdapterResnetBlock(nn.Module):
|
| 560 |
+
"""
|
| 561 |
+
A `LightAdapterResnetBlock` is a helper model that implements a ResNet-like block with a slightly different
|
| 562 |
+
architecture than `AdapterResnetBlock`.
|
| 563 |
+
|
| 564 |
+
Parameters:
|
| 565 |
+
channels (`int`):
|
| 566 |
+
Number of channels of LightAdapterResnetBlock's input and output.
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
def __init__(self, channels: int):
|
| 570 |
+
super().__init__()
|
| 571 |
+
self.block1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
|
| 572 |
+
self.act = nn.ReLU()
|
| 573 |
+
self.block2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
|
| 574 |
+
|
| 575 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 576 |
+
r"""
|
| 577 |
+
This function takes input tensor x and processes it through one convolutional layer, ReLU activation, and
|
| 578 |
+
another convolutional layer and adds it to input tensor.
|
| 579 |
+
"""
|
| 580 |
+
|
| 581 |
+
h = self.act(self.block1(x))
|
| 582 |
+
h = self.block2(h)
|
| 583 |
+
|
| 584 |
+
return h + x
|
diffusers/models/attention.py
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Any, Dict, Optional
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch import nn
|
| 18 |
+
|
| 19 |
+
from ..utils import USE_PEFT_BACKEND
|
| 20 |
+
from ..utils.torch_utils import maybe_allow_in_graph
|
| 21 |
+
from .activations import GEGLU, GELU, ApproximateGELU
|
| 22 |
+
from .attention_processor import Attention
|
| 23 |
+
from .embeddings import SinusoidalPositionalEmbedding
|
| 24 |
+
from .lora import LoRACompatibleLinear
|
| 25 |
+
from .normalization import AdaLayerNorm, AdaLayerNormZero
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _chunked_feed_forward(
|
| 29 |
+
ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None
|
| 30 |
+
):
|
| 31 |
+
# "feed_forward_chunk_size" can be used to save memory
|
| 32 |
+
if hidden_states.shape[chunk_dim] % chunk_size != 0:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
num_chunks = hidden_states.shape[chunk_dim] // chunk_size
|
| 38 |
+
if lora_scale is None:
|
| 39 |
+
ff_output = torch.cat(
|
| 40 |
+
[ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
|
| 41 |
+
dim=chunk_dim,
|
| 42 |
+
)
|
| 43 |
+
else:
|
| 44 |
+
# TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete
|
| 45 |
+
ff_output = torch.cat(
|
| 46 |
+
[ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
|
| 47 |
+
dim=chunk_dim,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
return ff_output
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@maybe_allow_in_graph
|
| 54 |
+
class GatedSelfAttentionDense(nn.Module):
|
| 55 |
+
r"""
|
| 56 |
+
A gated self-attention dense layer that combines visual features and object features.
|
| 57 |
+
|
| 58 |
+
Parameters:
|
| 59 |
+
query_dim (`int`): The number of channels in the query.
|
| 60 |
+
context_dim (`int`): The number of channels in the context.
|
| 61 |
+
n_heads (`int`): The number of heads to use for attention.
|
| 62 |
+
d_head (`int`): The number of channels in each head.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
|
| 66 |
+
super().__init__()
|
| 67 |
+
|
| 68 |
+
# we need a linear projection since we need cat visual feature and obj feature
|
| 69 |
+
self.linear = nn.Linear(context_dim, query_dim)
|
| 70 |
+
|
| 71 |
+
self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
|
| 72 |
+
self.ff = FeedForward(query_dim, activation_fn="geglu")
|
| 73 |
+
|
| 74 |
+
self.norm1 = nn.LayerNorm(query_dim)
|
| 75 |
+
self.norm2 = nn.LayerNorm(query_dim)
|
| 76 |
+
|
| 77 |
+
self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
|
| 78 |
+
self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
|
| 79 |
+
|
| 80 |
+
self.enabled = True
|
| 81 |
+
|
| 82 |
+
def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
|
| 83 |
+
if not self.enabled:
|
| 84 |
+
return x
|
| 85 |
+
|
| 86 |
+
n_visual = x.shape[1]
|
| 87 |
+
objs = self.linear(objs)
|
| 88 |
+
|
| 89 |
+
x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
|
| 90 |
+
x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
|
| 91 |
+
|
| 92 |
+
return x
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@maybe_allow_in_graph
|
| 96 |
+
class BasicTransformerBlock(nn.Module):
|
| 97 |
+
r"""
|
| 98 |
+
A basic Transformer block.
|
| 99 |
+
|
| 100 |
+
Parameters:
|
| 101 |
+
dim (`int`): The number of channels in the input and output.
|
| 102 |
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
| 103 |
+
attention_head_dim (`int`): The number of channels in each head.
|
| 104 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
| 105 |
+
cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
|
| 106 |
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
| 107 |
+
num_embeds_ada_norm (:
|
| 108 |
+
obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
|
| 109 |
+
attention_bias (:
|
| 110 |
+
obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
|
| 111 |
+
only_cross_attention (`bool`, *optional*):
|
| 112 |
+
Whether to use only cross-attention layers. In this case two cross attention layers are used.
|
| 113 |
+
double_self_attention (`bool`, *optional*):
|
| 114 |
+
Whether to use two self-attention layers. In this case no cross attention layers are used.
|
| 115 |
+
upcast_attention (`bool`, *optional*):
|
| 116 |
+
Whether to upcast the attention computation to float32. This is useful for mixed precision training.
|
| 117 |
+
norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
|
| 118 |
+
Whether to use learnable elementwise affine parameters for normalization.
|
| 119 |
+
norm_type (`str`, *optional*, defaults to `"layer_norm"`):
|
| 120 |
+
The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
|
| 121 |
+
final_dropout (`bool` *optional*, defaults to False):
|
| 122 |
+
Whether to apply a final dropout after the last feed-forward layer.
|
| 123 |
+
attention_type (`str`, *optional*, defaults to `"default"`):
|
| 124 |
+
The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
|
| 125 |
+
positional_embeddings (`str`, *optional*, defaults to `None`):
|
| 126 |
+
The type of positional embeddings to apply to.
|
| 127 |
+
num_positional_embeddings (`int`, *optional*, defaults to `None`):
|
| 128 |
+
The maximum number of positional embeddings to apply.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
def __init__(
|
| 132 |
+
self,
|
| 133 |
+
dim: int,
|
| 134 |
+
num_attention_heads: int,
|
| 135 |
+
attention_head_dim: int,
|
| 136 |
+
dropout=0.0,
|
| 137 |
+
cross_attention_dim: Optional[int] = None,
|
| 138 |
+
activation_fn: str = "geglu",
|
| 139 |
+
num_embeds_ada_norm: Optional[int] = None,
|
| 140 |
+
attention_bias: bool = False,
|
| 141 |
+
only_cross_attention: bool = False,
|
| 142 |
+
double_self_attention: bool = False,
|
| 143 |
+
upcast_attention: bool = False,
|
| 144 |
+
norm_elementwise_affine: bool = True,
|
| 145 |
+
norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
|
| 146 |
+
norm_eps: float = 1e-5,
|
| 147 |
+
final_dropout: bool = False,
|
| 148 |
+
attention_type: str = "default",
|
| 149 |
+
positional_embeddings: Optional[str] = None,
|
| 150 |
+
num_positional_embeddings: Optional[int] = None,
|
| 151 |
+
):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.only_cross_attention = only_cross_attention
|
| 154 |
+
|
| 155 |
+
self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
|
| 156 |
+
self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
|
| 157 |
+
self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
|
| 158 |
+
self.use_layer_norm = norm_type == "layer_norm"
|
| 159 |
+
|
| 160 |
+
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
|
| 161 |
+
raise ValueError(
|
| 162 |
+
f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
|
| 163 |
+
f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
if positional_embeddings and (num_positional_embeddings is None):
|
| 167 |
+
raise ValueError(
|
| 168 |
+
"If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
if positional_embeddings == "sinusoidal":
|
| 172 |
+
self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
|
| 173 |
+
else:
|
| 174 |
+
self.pos_embed = None
|
| 175 |
+
|
| 176 |
+
# Define 3 blocks. Each block has its own normalization layer.
|
| 177 |
+
# 1. Self-Attn
|
| 178 |
+
if self.use_ada_layer_norm:
|
| 179 |
+
self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
|
| 180 |
+
elif self.use_ada_layer_norm_zero:
|
| 181 |
+
self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
|
| 182 |
+
else:
|
| 183 |
+
self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
| 184 |
+
|
| 185 |
+
self.attn1 = Attention(
|
| 186 |
+
query_dim=dim,
|
| 187 |
+
heads=num_attention_heads,
|
| 188 |
+
dim_head=attention_head_dim,
|
| 189 |
+
dropout=dropout,
|
| 190 |
+
bias=attention_bias,
|
| 191 |
+
cross_attention_dim=cross_attention_dim if only_cross_attention else None,
|
| 192 |
+
upcast_attention=upcast_attention,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# 2. Cross-Attn
|
| 196 |
+
if cross_attention_dim is not None or double_self_attention:
|
| 197 |
+
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
|
| 198 |
+
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
|
| 199 |
+
# the second cross attention block.
|
| 200 |
+
self.norm2 = (
|
| 201 |
+
AdaLayerNorm(dim, num_embeds_ada_norm)
|
| 202 |
+
if self.use_ada_layer_norm
|
| 203 |
+
else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
| 204 |
+
)
|
| 205 |
+
self.attn2 = Attention(
|
| 206 |
+
query_dim=dim,
|
| 207 |
+
cross_attention_dim=cross_attention_dim if not double_self_attention else None,
|
| 208 |
+
heads=num_attention_heads,
|
| 209 |
+
dim_head=attention_head_dim,
|
| 210 |
+
dropout=dropout,
|
| 211 |
+
bias=attention_bias,
|
| 212 |
+
upcast_attention=upcast_attention,
|
| 213 |
+
) # is self-attn if encoder_hidden_states is none
|
| 214 |
+
else:
|
| 215 |
+
self.norm2 = None
|
| 216 |
+
self.attn2 = None
|
| 217 |
+
|
| 218 |
+
# 3. Feed-forward
|
| 219 |
+
if not self.use_ada_layer_norm_single:
|
| 220 |
+
self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
| 221 |
+
|
| 222 |
+
self.ff = FeedForward(
|
| 223 |
+
dim,
|
| 224 |
+
dropout=dropout,
|
| 225 |
+
activation_fn=activation_fn,
|
| 226 |
+
final_dropout=final_dropout,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# 4. Fuser
|
| 230 |
+
if attention_type == "gated" or attention_type == "gated-text-image":
|
| 231 |
+
self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
|
| 232 |
+
|
| 233 |
+
# 5. Scale-shift for PixArt-Alpha.
|
| 234 |
+
if self.use_ada_layer_norm_single:
|
| 235 |
+
self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
|
| 236 |
+
|
| 237 |
+
# let chunk size default to None
|
| 238 |
+
self._chunk_size = None
|
| 239 |
+
self._chunk_dim = 0
|
| 240 |
+
|
| 241 |
+
def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
|
| 242 |
+
# Sets chunk feed-forward
|
| 243 |
+
self._chunk_size = chunk_size
|
| 244 |
+
self._chunk_dim = dim
|
| 245 |
+
|
| 246 |
+
def forward(
|
| 247 |
+
self,
|
| 248 |
+
hidden_states: torch.FloatTensor,
|
| 249 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 250 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 251 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 252 |
+
timestep: Optional[torch.LongTensor] = None,
|
| 253 |
+
cross_attention_kwargs: Dict[str, Any] = None,
|
| 254 |
+
class_labels: Optional[torch.LongTensor] = None,
|
| 255 |
+
) -> torch.FloatTensor:
|
| 256 |
+
# Notice that normalization is always applied before the real computation in the following blocks.
|
| 257 |
+
# 0. Self-Attention
|
| 258 |
+
batch_size = hidden_states.shape[0]
|
| 259 |
+
|
| 260 |
+
if self.use_ada_layer_norm:
|
| 261 |
+
norm_hidden_states = self.norm1(hidden_states, timestep)
|
| 262 |
+
elif self.use_ada_layer_norm_zero:
|
| 263 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
|
| 264 |
+
hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
|
| 265 |
+
)
|
| 266 |
+
elif self.use_layer_norm:
|
| 267 |
+
norm_hidden_states = self.norm1(hidden_states)
|
| 268 |
+
elif self.use_ada_layer_norm_single:
|
| 269 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 270 |
+
self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
|
| 271 |
+
).chunk(6, dim=1)
|
| 272 |
+
norm_hidden_states = self.norm1(hidden_states)
|
| 273 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
|
| 274 |
+
norm_hidden_states = norm_hidden_states.squeeze(1)
|
| 275 |
+
else:
|
| 276 |
+
raise ValueError("Incorrect norm used")
|
| 277 |
+
|
| 278 |
+
if self.pos_embed is not None:
|
| 279 |
+
norm_hidden_states = self.pos_embed(norm_hidden_states)
|
| 280 |
+
|
| 281 |
+
# 1. Retrieve lora scale.
|
| 282 |
+
lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
|
| 283 |
+
|
| 284 |
+
# 2. Prepare GLIGEN inputs
|
| 285 |
+
cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
|
| 286 |
+
gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
|
| 287 |
+
|
| 288 |
+
attn_output = self.attn1(
|
| 289 |
+
norm_hidden_states,
|
| 290 |
+
encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
|
| 291 |
+
attention_mask=attention_mask,
|
| 292 |
+
**cross_attention_kwargs,
|
| 293 |
+
)
|
| 294 |
+
if self.use_ada_layer_norm_zero:
|
| 295 |
+
attn_output = gate_msa.unsqueeze(1) * attn_output
|
| 296 |
+
elif self.use_ada_layer_norm_single:
|
| 297 |
+
attn_output = gate_msa * attn_output
|
| 298 |
+
|
| 299 |
+
hidden_states = attn_output + hidden_states
|
| 300 |
+
if hidden_states.ndim == 4:
|
| 301 |
+
hidden_states = hidden_states.squeeze(1)
|
| 302 |
+
|
| 303 |
+
# 2.5 GLIGEN Control
|
| 304 |
+
if gligen_kwargs is not None:
|
| 305 |
+
hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
|
| 306 |
+
|
| 307 |
+
# 3. Cross-Attention
|
| 308 |
+
if self.attn2 is not None:
|
| 309 |
+
if self.use_ada_layer_norm:
|
| 310 |
+
norm_hidden_states = self.norm2(hidden_states, timestep)
|
| 311 |
+
elif self.use_ada_layer_norm_zero or self.use_layer_norm:
|
| 312 |
+
norm_hidden_states = self.norm2(hidden_states)
|
| 313 |
+
elif self.use_ada_layer_norm_single:
|
| 314 |
+
# For PixArt norm2 isn't applied here:
|
| 315 |
+
# https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
|
| 316 |
+
norm_hidden_states = hidden_states
|
| 317 |
+
else:
|
| 318 |
+
raise ValueError("Incorrect norm")
|
| 319 |
+
|
| 320 |
+
if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
|
| 321 |
+
norm_hidden_states = self.pos_embed(norm_hidden_states)
|
| 322 |
+
|
| 323 |
+
attn_output = self.attn2(
|
| 324 |
+
norm_hidden_states,
|
| 325 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 326 |
+
attention_mask=encoder_attention_mask,
|
| 327 |
+
**cross_attention_kwargs,
|
| 328 |
+
)
|
| 329 |
+
hidden_states = attn_output + hidden_states
|
| 330 |
+
|
| 331 |
+
# 4. Feed-forward
|
| 332 |
+
if not self.use_ada_layer_norm_single:
|
| 333 |
+
norm_hidden_states = self.norm3(hidden_states)
|
| 334 |
+
|
| 335 |
+
if self.use_ada_layer_norm_zero:
|
| 336 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
| 337 |
+
|
| 338 |
+
if self.use_ada_layer_norm_single:
|
| 339 |
+
norm_hidden_states = self.norm2(hidden_states)
|
| 340 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
|
| 341 |
+
|
| 342 |
+
if self._chunk_size is not None:
|
| 343 |
+
# "feed_forward_chunk_size" can be used to save memory
|
| 344 |
+
ff_output = _chunked_feed_forward(
|
| 345 |
+
self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
|
| 346 |
+
)
|
| 347 |
+
else:
|
| 348 |
+
ff_output = self.ff(norm_hidden_states, scale=lora_scale)
|
| 349 |
+
|
| 350 |
+
if self.use_ada_layer_norm_zero:
|
| 351 |
+
ff_output = gate_mlp.unsqueeze(1) * ff_output
|
| 352 |
+
elif self.use_ada_layer_norm_single:
|
| 353 |
+
ff_output = gate_mlp * ff_output
|
| 354 |
+
|
| 355 |
+
hidden_states = ff_output + hidden_states
|
| 356 |
+
if hidden_states.ndim == 4:
|
| 357 |
+
hidden_states = hidden_states.squeeze(1)
|
| 358 |
+
|
| 359 |
+
return hidden_states
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@maybe_allow_in_graph
|
| 363 |
+
class TemporalBasicTransformerBlock(nn.Module):
|
| 364 |
+
r"""
|
| 365 |
+
A basic Transformer block for video like data.
|
| 366 |
+
|
| 367 |
+
Parameters:
|
| 368 |
+
dim (`int`): The number of channels in the input and output.
|
| 369 |
+
time_mix_inner_dim (`int`): The number of channels for temporal attention.
|
| 370 |
+
num_attention_heads (`int`): The number of heads to use for multi-head attention.
|
| 371 |
+
attention_head_dim (`int`): The number of channels in each head.
|
| 372 |
+
cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
def __init__(
|
| 376 |
+
self,
|
| 377 |
+
dim: int,
|
| 378 |
+
time_mix_inner_dim: int,
|
| 379 |
+
num_attention_heads: int,
|
| 380 |
+
attention_head_dim: int,
|
| 381 |
+
cross_attention_dim: Optional[int] = None,
|
| 382 |
+
):
|
| 383 |
+
super().__init__()
|
| 384 |
+
self.is_res = dim == time_mix_inner_dim
|
| 385 |
+
|
| 386 |
+
self.norm_in = nn.LayerNorm(dim)
|
| 387 |
+
|
| 388 |
+
# Define 3 blocks. Each block has its own normalization layer.
|
| 389 |
+
# 1. Self-Attn
|
| 390 |
+
self.norm_in = nn.LayerNorm(dim)
|
| 391 |
+
self.ff_in = FeedForward(
|
| 392 |
+
dim,
|
| 393 |
+
dim_out=time_mix_inner_dim,
|
| 394 |
+
activation_fn="geglu",
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
self.norm1 = nn.LayerNorm(time_mix_inner_dim)
|
| 398 |
+
self.attn1 = Attention(
|
| 399 |
+
query_dim=time_mix_inner_dim,
|
| 400 |
+
heads=num_attention_heads,
|
| 401 |
+
dim_head=attention_head_dim,
|
| 402 |
+
cross_attention_dim=None,
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# 2. Cross-Attn
|
| 406 |
+
if cross_attention_dim is not None:
|
| 407 |
+
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
|
| 408 |
+
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
|
| 409 |
+
# the second cross attention block.
|
| 410 |
+
self.norm2 = nn.LayerNorm(time_mix_inner_dim)
|
| 411 |
+
self.attn2 = Attention(
|
| 412 |
+
query_dim=time_mix_inner_dim,
|
| 413 |
+
cross_attention_dim=cross_attention_dim,
|
| 414 |
+
heads=num_attention_heads,
|
| 415 |
+
dim_head=attention_head_dim,
|
| 416 |
+
) # is self-attn if encoder_hidden_states is none
|
| 417 |
+
else:
|
| 418 |
+
self.norm2 = None
|
| 419 |
+
self.attn2 = None
|
| 420 |
+
|
| 421 |
+
# 3. Feed-forward
|
| 422 |
+
self.norm3 = nn.LayerNorm(time_mix_inner_dim)
|
| 423 |
+
self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
|
| 424 |
+
|
| 425 |
+
# let chunk size default to None
|
| 426 |
+
self._chunk_size = None
|
| 427 |
+
self._chunk_dim = None
|
| 428 |
+
|
| 429 |
+
def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
|
| 430 |
+
# Sets chunk feed-forward
|
| 431 |
+
self._chunk_size = chunk_size
|
| 432 |
+
# chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
|
| 433 |
+
self._chunk_dim = 1
|
| 434 |
+
|
| 435 |
+
def forward(
|
| 436 |
+
self,
|
| 437 |
+
hidden_states: torch.FloatTensor,
|
| 438 |
+
num_frames: int,
|
| 439 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 440 |
+
) -> torch.FloatTensor:
|
| 441 |
+
# Notice that normalization is always applied before the real computation in the following blocks.
|
| 442 |
+
# 0. Self-Attention
|
| 443 |
+
batch_size = hidden_states.shape[0]
|
| 444 |
+
|
| 445 |
+
batch_frames, seq_length, channels = hidden_states.shape
|
| 446 |
+
batch_size = batch_frames // num_frames
|
| 447 |
+
|
| 448 |
+
hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
|
| 449 |
+
hidden_states = hidden_states.permute(0, 2, 1, 3)
|
| 450 |
+
hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
|
| 451 |
+
|
| 452 |
+
residual = hidden_states
|
| 453 |
+
hidden_states = self.norm_in(hidden_states)
|
| 454 |
+
|
| 455 |
+
if self._chunk_size is not None:
|
| 456 |
+
hidden_states = _chunked_feed_forward(self.ff, hidden_states, self._chunk_dim, self._chunk_size)
|
| 457 |
+
else:
|
| 458 |
+
hidden_states = self.ff_in(hidden_states)
|
| 459 |
+
|
| 460 |
+
if self.is_res:
|
| 461 |
+
hidden_states = hidden_states + residual
|
| 462 |
+
|
| 463 |
+
norm_hidden_states = self.norm1(hidden_states)
|
| 464 |
+
attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
|
| 465 |
+
hidden_states = attn_output + hidden_states
|
| 466 |
+
|
| 467 |
+
# 3. Cross-Attention
|
| 468 |
+
if self.attn2 is not None:
|
| 469 |
+
norm_hidden_states = self.norm2(hidden_states)
|
| 470 |
+
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
|
| 471 |
+
hidden_states = attn_output + hidden_states
|
| 472 |
+
|
| 473 |
+
# 4. Feed-forward
|
| 474 |
+
norm_hidden_states = self.norm3(hidden_states)
|
| 475 |
+
|
| 476 |
+
if self._chunk_size is not None:
|
| 477 |
+
ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
|
| 478 |
+
else:
|
| 479 |
+
ff_output = self.ff(norm_hidden_states)
|
| 480 |
+
|
| 481 |
+
if self.is_res:
|
| 482 |
+
hidden_states = ff_output + hidden_states
|
| 483 |
+
else:
|
| 484 |
+
hidden_states = ff_output
|
| 485 |
+
|
| 486 |
+
hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
|
| 487 |
+
hidden_states = hidden_states.permute(0, 2, 1, 3)
|
| 488 |
+
hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
|
| 489 |
+
|
| 490 |
+
return hidden_states
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
class FeedForward(nn.Module):
|
| 494 |
+
r"""
|
| 495 |
+
A feed-forward layer.
|
| 496 |
+
|
| 497 |
+
Parameters:
|
| 498 |
+
dim (`int`): The number of channels in the input.
|
| 499 |
+
dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
|
| 500 |
+
mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
|
| 501 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
| 502 |
+
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
| 503 |
+
final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
|
| 504 |
+
"""
|
| 505 |
+
|
| 506 |
+
def __init__(
|
| 507 |
+
self,
|
| 508 |
+
dim: int,
|
| 509 |
+
dim_out: Optional[int] = None,
|
| 510 |
+
mult: int = 4,
|
| 511 |
+
dropout: float = 0.0,
|
| 512 |
+
activation_fn: str = "geglu",
|
| 513 |
+
final_dropout: bool = False,
|
| 514 |
+
):
|
| 515 |
+
super().__init__()
|
| 516 |
+
inner_dim = int(dim * mult)
|
| 517 |
+
dim_out = dim_out if dim_out is not None else dim
|
| 518 |
+
linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
|
| 519 |
+
|
| 520 |
+
if activation_fn == "gelu":
|
| 521 |
+
act_fn = GELU(dim, inner_dim)
|
| 522 |
+
if activation_fn == "gelu-approximate":
|
| 523 |
+
act_fn = GELU(dim, inner_dim, approximate="tanh")
|
| 524 |
+
elif activation_fn == "geglu":
|
| 525 |
+
act_fn = GEGLU(dim, inner_dim)
|
| 526 |
+
elif activation_fn == "geglu-approximate":
|
| 527 |
+
act_fn = ApproximateGELU(dim, inner_dim)
|
| 528 |
+
|
| 529 |
+
self.net = nn.ModuleList([])
|
| 530 |
+
# project in
|
| 531 |
+
self.net.append(act_fn)
|
| 532 |
+
# project dropout
|
| 533 |
+
self.net.append(nn.Dropout(dropout))
|
| 534 |
+
# project out
|
| 535 |
+
self.net.append(linear_cls(inner_dim, dim_out))
|
| 536 |
+
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
|
| 537 |
+
if final_dropout:
|
| 538 |
+
self.net.append(nn.Dropout(dropout))
|
| 539 |
+
|
| 540 |
+
def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
|
| 541 |
+
compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear)
|
| 542 |
+
for module in self.net:
|
| 543 |
+
if isinstance(module, compatible_cls):
|
| 544 |
+
hidden_states = module(hidden_states, scale)
|
| 545 |
+
else:
|
| 546 |
+
hidden_states = module(hidden_states)
|
| 547 |
+
return hidden_states
|
diffusers/models/attention_flax.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import functools
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import flax.linen as nn
|
| 19 |
+
import jax
|
| 20 |
+
import jax.numpy as jnp
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _query_chunk_attention(query, key, value, precision, key_chunk_size: int = 4096):
|
| 24 |
+
"""Multi-head dot product attention with a limited number of queries."""
|
| 25 |
+
num_kv, num_heads, k_features = key.shape[-3:]
|
| 26 |
+
v_features = value.shape[-1]
|
| 27 |
+
key_chunk_size = min(key_chunk_size, num_kv)
|
| 28 |
+
query = query / jnp.sqrt(k_features)
|
| 29 |
+
|
| 30 |
+
@functools.partial(jax.checkpoint, prevent_cse=False)
|
| 31 |
+
def summarize_chunk(query, key, value):
|
| 32 |
+
attn_weights = jnp.einsum("...qhd,...khd->...qhk", query, key, precision=precision)
|
| 33 |
+
|
| 34 |
+
max_score = jnp.max(attn_weights, axis=-1, keepdims=True)
|
| 35 |
+
max_score = jax.lax.stop_gradient(max_score)
|
| 36 |
+
exp_weights = jnp.exp(attn_weights - max_score)
|
| 37 |
+
|
| 38 |
+
exp_values = jnp.einsum("...vhf,...qhv->...qhf", value, exp_weights, precision=precision)
|
| 39 |
+
max_score = jnp.einsum("...qhk->...qh", max_score)
|
| 40 |
+
|
| 41 |
+
return (exp_values, exp_weights.sum(axis=-1), max_score)
|
| 42 |
+
|
| 43 |
+
def chunk_scanner(chunk_idx):
|
| 44 |
+
# julienne key array
|
| 45 |
+
key_chunk = jax.lax.dynamic_slice(
|
| 46 |
+
operand=key,
|
| 47 |
+
start_indices=[0] * (key.ndim - 3) + [chunk_idx, 0, 0], # [...,k,h,d]
|
| 48 |
+
slice_sizes=list(key.shape[:-3]) + [key_chunk_size, num_heads, k_features], # [...,k,h,d]
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# julienne value array
|
| 52 |
+
value_chunk = jax.lax.dynamic_slice(
|
| 53 |
+
operand=value,
|
| 54 |
+
start_indices=[0] * (value.ndim - 3) + [chunk_idx, 0, 0], # [...,v,h,d]
|
| 55 |
+
slice_sizes=list(value.shape[:-3]) + [key_chunk_size, num_heads, v_features], # [...,v,h,d]
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
return summarize_chunk(query, key_chunk, value_chunk)
|
| 59 |
+
|
| 60 |
+
chunk_values, chunk_weights, chunk_max = jax.lax.map(f=chunk_scanner, xs=jnp.arange(0, num_kv, key_chunk_size))
|
| 61 |
+
|
| 62 |
+
global_max = jnp.max(chunk_max, axis=0, keepdims=True)
|
| 63 |
+
max_diffs = jnp.exp(chunk_max - global_max)
|
| 64 |
+
|
| 65 |
+
chunk_values *= jnp.expand_dims(max_diffs, axis=-1)
|
| 66 |
+
chunk_weights *= max_diffs
|
| 67 |
+
|
| 68 |
+
all_values = chunk_values.sum(axis=0)
|
| 69 |
+
all_weights = jnp.expand_dims(chunk_weights, -1).sum(axis=0)
|
| 70 |
+
|
| 71 |
+
return all_values / all_weights
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def jax_memory_efficient_attention(
|
| 75 |
+
query, key, value, precision=jax.lax.Precision.HIGHEST, query_chunk_size: int = 1024, key_chunk_size: int = 4096
|
| 76 |
+
):
|
| 77 |
+
r"""
|
| 78 |
+
Flax Memory-efficient multi-head dot product attention. https://arxiv.org/abs/2112.05682v2
|
| 79 |
+
https://github.com/AminRezaei0x443/memory-efficient-attention
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
query (`jnp.ndarray`): (batch..., query_length, head, query_key_depth_per_head)
|
| 83 |
+
key (`jnp.ndarray`): (batch..., key_value_length, head, query_key_depth_per_head)
|
| 84 |
+
value (`jnp.ndarray`): (batch..., key_value_length, head, value_depth_per_head)
|
| 85 |
+
precision (`jax.lax.Precision`, *optional*, defaults to `jax.lax.Precision.HIGHEST`):
|
| 86 |
+
numerical precision for computation
|
| 87 |
+
query_chunk_size (`int`, *optional*, defaults to 1024):
|
| 88 |
+
chunk size to divide query array value must divide query_length equally without remainder
|
| 89 |
+
key_chunk_size (`int`, *optional*, defaults to 4096):
|
| 90 |
+
chunk size to divide key and value array value must divide key_value_length equally without remainder
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
(`jnp.ndarray`) with shape of (batch..., query_length, head, value_depth_per_head)
|
| 94 |
+
"""
|
| 95 |
+
num_q, num_heads, q_features = query.shape[-3:]
|
| 96 |
+
|
| 97 |
+
def chunk_scanner(chunk_idx, _):
|
| 98 |
+
# julienne query array
|
| 99 |
+
query_chunk = jax.lax.dynamic_slice(
|
| 100 |
+
operand=query,
|
| 101 |
+
start_indices=([0] * (query.ndim - 3)) + [chunk_idx, 0, 0], # [...,q,h,d]
|
| 102 |
+
slice_sizes=list(query.shape[:-3]) + [min(query_chunk_size, num_q), num_heads, q_features], # [...,q,h,d]
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
return (
|
| 106 |
+
chunk_idx + query_chunk_size, # unused ignore it
|
| 107 |
+
_query_chunk_attention(
|
| 108 |
+
query=query_chunk, key=key, value=value, precision=precision, key_chunk_size=key_chunk_size
|
| 109 |
+
),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
_, res = jax.lax.scan(
|
| 113 |
+
f=chunk_scanner,
|
| 114 |
+
init=0,
|
| 115 |
+
xs=None,
|
| 116 |
+
length=math.ceil(num_q / query_chunk_size), # start counter # stop counter
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
return jnp.concatenate(res, axis=-3) # fuse the chunked result back
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class FlaxAttention(nn.Module):
|
| 123 |
+
r"""
|
| 124 |
+
A Flax multi-head attention module as described in: https://arxiv.org/abs/1706.03762
|
| 125 |
+
|
| 126 |
+
Parameters:
|
| 127 |
+
query_dim (:obj:`int`):
|
| 128 |
+
Input hidden states dimension
|
| 129 |
+
heads (:obj:`int`, *optional*, defaults to 8):
|
| 130 |
+
Number of heads
|
| 131 |
+
dim_head (:obj:`int`, *optional*, defaults to 64):
|
| 132 |
+
Hidden states dimension inside each head
|
| 133 |
+
dropout (:obj:`float`, *optional*, defaults to 0.0):
|
| 134 |
+
Dropout rate
|
| 135 |
+
use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
|
| 136 |
+
enable memory efficient attention https://arxiv.org/abs/2112.05682
|
| 137 |
+
split_head_dim (`bool`, *optional*, defaults to `False`):
|
| 138 |
+
Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
|
| 139 |
+
enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
|
| 140 |
+
dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
|
| 141 |
+
Parameters `dtype`
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
query_dim: int
|
| 146 |
+
heads: int = 8
|
| 147 |
+
dim_head: int = 64
|
| 148 |
+
dropout: float = 0.0
|
| 149 |
+
use_memory_efficient_attention: bool = False
|
| 150 |
+
split_head_dim: bool = False
|
| 151 |
+
dtype: jnp.dtype = jnp.float32
|
| 152 |
+
|
| 153 |
+
def setup(self):
|
| 154 |
+
inner_dim = self.dim_head * self.heads
|
| 155 |
+
self.scale = self.dim_head**-0.5
|
| 156 |
+
|
| 157 |
+
# Weights were exported with old names {to_q, to_k, to_v, to_out}
|
| 158 |
+
self.query = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_q")
|
| 159 |
+
self.key = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_k")
|
| 160 |
+
self.value = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_v")
|
| 161 |
+
|
| 162 |
+
self.proj_attn = nn.Dense(self.query_dim, dtype=self.dtype, name="to_out_0")
|
| 163 |
+
self.dropout_layer = nn.Dropout(rate=self.dropout)
|
| 164 |
+
|
| 165 |
+
def reshape_heads_to_batch_dim(self, tensor):
|
| 166 |
+
batch_size, seq_len, dim = tensor.shape
|
| 167 |
+
head_size = self.heads
|
| 168 |
+
tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
|
| 169 |
+
tensor = jnp.transpose(tensor, (0, 2, 1, 3))
|
| 170 |
+
tensor = tensor.reshape(batch_size * head_size, seq_len, dim // head_size)
|
| 171 |
+
return tensor
|
| 172 |
+
|
| 173 |
+
def reshape_batch_dim_to_heads(self, tensor):
|
| 174 |
+
batch_size, seq_len, dim = tensor.shape
|
| 175 |
+
head_size = self.heads
|
| 176 |
+
tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
|
| 177 |
+
tensor = jnp.transpose(tensor, (0, 2, 1, 3))
|
| 178 |
+
tensor = tensor.reshape(batch_size // head_size, seq_len, dim * head_size)
|
| 179 |
+
return tensor
|
| 180 |
+
|
| 181 |
+
def __call__(self, hidden_states, context=None, deterministic=True):
|
| 182 |
+
context = hidden_states if context is None else context
|
| 183 |
+
|
| 184 |
+
query_proj = self.query(hidden_states)
|
| 185 |
+
key_proj = self.key(context)
|
| 186 |
+
value_proj = self.value(context)
|
| 187 |
+
|
| 188 |
+
if self.split_head_dim:
|
| 189 |
+
b = hidden_states.shape[0]
|
| 190 |
+
query_states = jnp.reshape(query_proj, (b, -1, self.heads, self.dim_head))
|
| 191 |
+
key_states = jnp.reshape(key_proj, (b, -1, self.heads, self.dim_head))
|
| 192 |
+
value_states = jnp.reshape(value_proj, (b, -1, self.heads, self.dim_head))
|
| 193 |
+
else:
|
| 194 |
+
query_states = self.reshape_heads_to_batch_dim(query_proj)
|
| 195 |
+
key_states = self.reshape_heads_to_batch_dim(key_proj)
|
| 196 |
+
value_states = self.reshape_heads_to_batch_dim(value_proj)
|
| 197 |
+
|
| 198 |
+
if self.use_memory_efficient_attention:
|
| 199 |
+
query_states = query_states.transpose(1, 0, 2)
|
| 200 |
+
key_states = key_states.transpose(1, 0, 2)
|
| 201 |
+
value_states = value_states.transpose(1, 0, 2)
|
| 202 |
+
|
| 203 |
+
# this if statement create a chunk size for each layer of the unet
|
| 204 |
+
# the chunk size is equal to the query_length dimension of the deepest layer of the unet
|
| 205 |
+
|
| 206 |
+
flatten_latent_dim = query_states.shape[-3]
|
| 207 |
+
if flatten_latent_dim % 64 == 0:
|
| 208 |
+
query_chunk_size = int(flatten_latent_dim / 64)
|
| 209 |
+
elif flatten_latent_dim % 16 == 0:
|
| 210 |
+
query_chunk_size = int(flatten_latent_dim / 16)
|
| 211 |
+
elif flatten_latent_dim % 4 == 0:
|
| 212 |
+
query_chunk_size = int(flatten_latent_dim / 4)
|
| 213 |
+
else:
|
| 214 |
+
query_chunk_size = int(flatten_latent_dim)
|
| 215 |
+
|
| 216 |
+
hidden_states = jax_memory_efficient_attention(
|
| 217 |
+
query_states, key_states, value_states, query_chunk_size=query_chunk_size, key_chunk_size=4096 * 4
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
hidden_states = hidden_states.transpose(1, 0, 2)
|
| 221 |
+
else:
|
| 222 |
+
# compute attentions
|
| 223 |
+
if self.split_head_dim:
|
| 224 |
+
attention_scores = jnp.einsum("b t n h, b f n h -> b n f t", key_states, query_states)
|
| 225 |
+
else:
|
| 226 |
+
attention_scores = jnp.einsum("b i d, b j d->b i j", query_states, key_states)
|
| 227 |
+
|
| 228 |
+
attention_scores = attention_scores * self.scale
|
| 229 |
+
attention_probs = nn.softmax(attention_scores, axis=-1 if self.split_head_dim else 2)
|
| 230 |
+
|
| 231 |
+
# attend to values
|
| 232 |
+
if self.split_head_dim:
|
| 233 |
+
hidden_states = jnp.einsum("b n f t, b t n h -> b f n h", attention_probs, value_states)
|
| 234 |
+
b = hidden_states.shape[0]
|
| 235 |
+
hidden_states = jnp.reshape(hidden_states, (b, -1, self.heads * self.dim_head))
|
| 236 |
+
else:
|
| 237 |
+
hidden_states = jnp.einsum("b i j, b j d -> b i d", attention_probs, value_states)
|
| 238 |
+
hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
|
| 239 |
+
|
| 240 |
+
hidden_states = self.proj_attn(hidden_states)
|
| 241 |
+
return self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class FlaxBasicTransformerBlock(nn.Module):
|
| 245 |
+
r"""
|
| 246 |
+
A Flax transformer block layer with `GLU` (Gated Linear Unit) activation function as described in:
|
| 247 |
+
https://arxiv.org/abs/1706.03762
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
Parameters:
|
| 251 |
+
dim (:obj:`int`):
|
| 252 |
+
Inner hidden states dimension
|
| 253 |
+
n_heads (:obj:`int`):
|
| 254 |
+
Number of heads
|
| 255 |
+
d_head (:obj:`int`):
|
| 256 |
+
Hidden states dimension inside each head
|
| 257 |
+
dropout (:obj:`float`, *optional*, defaults to 0.0):
|
| 258 |
+
Dropout rate
|
| 259 |
+
only_cross_attention (`bool`, defaults to `False`):
|
| 260 |
+
Whether to only apply cross attention.
|
| 261 |
+
dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
|
| 262 |
+
Parameters `dtype`
|
| 263 |
+
use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
|
| 264 |
+
enable memory efficient attention https://arxiv.org/abs/2112.05682
|
| 265 |
+
split_head_dim (`bool`, *optional*, defaults to `False`):
|
| 266 |
+
Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
|
| 267 |
+
enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
dim: int
|
| 271 |
+
n_heads: int
|
| 272 |
+
d_head: int
|
| 273 |
+
dropout: float = 0.0
|
| 274 |
+
only_cross_attention: bool = False
|
| 275 |
+
dtype: jnp.dtype = jnp.float32
|
| 276 |
+
use_memory_efficient_attention: bool = False
|
| 277 |
+
split_head_dim: bool = False
|
| 278 |
+
|
| 279 |
+
def setup(self):
|
| 280 |
+
# self attention (or cross_attention if only_cross_attention is True)
|
| 281 |
+
self.attn1 = FlaxAttention(
|
| 282 |
+
self.dim,
|
| 283 |
+
self.n_heads,
|
| 284 |
+
self.d_head,
|
| 285 |
+
self.dropout,
|
| 286 |
+
self.use_memory_efficient_attention,
|
| 287 |
+
self.split_head_dim,
|
| 288 |
+
dtype=self.dtype,
|
| 289 |
+
)
|
| 290 |
+
# cross attention
|
| 291 |
+
self.attn2 = FlaxAttention(
|
| 292 |
+
self.dim,
|
| 293 |
+
self.n_heads,
|
| 294 |
+
self.d_head,
|
| 295 |
+
self.dropout,
|
| 296 |
+
self.use_memory_efficient_attention,
|
| 297 |
+
self.split_head_dim,
|
| 298 |
+
dtype=self.dtype,
|
| 299 |
+
)
|
| 300 |
+
self.ff = FlaxFeedForward(dim=self.dim, dropout=self.dropout, dtype=self.dtype)
|
| 301 |
+
self.norm1 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
|
| 302 |
+
self.norm2 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
|
| 303 |
+
self.norm3 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
|
| 304 |
+
self.dropout_layer = nn.Dropout(rate=self.dropout)
|
| 305 |
+
|
| 306 |
+
def __call__(self, hidden_states, context, deterministic=True):
|
| 307 |
+
# self attention
|
| 308 |
+
residual = hidden_states
|
| 309 |
+
if self.only_cross_attention:
|
| 310 |
+
hidden_states = self.attn1(self.norm1(hidden_states), context, deterministic=deterministic)
|
| 311 |
+
else:
|
| 312 |
+
hidden_states = self.attn1(self.norm1(hidden_states), deterministic=deterministic)
|
| 313 |
+
hidden_states = hidden_states + residual
|
| 314 |
+
|
| 315 |
+
# cross attention
|
| 316 |
+
residual = hidden_states
|
| 317 |
+
hidden_states = self.attn2(self.norm2(hidden_states), context, deterministic=deterministic)
|
| 318 |
+
hidden_states = hidden_states + residual
|
| 319 |
+
|
| 320 |
+
# feed forward
|
| 321 |
+
residual = hidden_states
|
| 322 |
+
hidden_states = self.ff(self.norm3(hidden_states), deterministic=deterministic)
|
| 323 |
+
hidden_states = hidden_states + residual
|
| 324 |
+
|
| 325 |
+
return self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class FlaxTransformer2DModel(nn.Module):
|
| 329 |
+
r"""
|
| 330 |
+
A Spatial Transformer layer with Gated Linear Unit (GLU) activation function as described in:
|
| 331 |
+
https://arxiv.org/pdf/1506.02025.pdf
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
Parameters:
|
| 335 |
+
in_channels (:obj:`int`):
|
| 336 |
+
Input number of channels
|
| 337 |
+
n_heads (:obj:`int`):
|
| 338 |
+
Number of heads
|
| 339 |
+
d_head (:obj:`int`):
|
| 340 |
+
Hidden states dimension inside each head
|
| 341 |
+
depth (:obj:`int`, *optional*, defaults to 1):
|
| 342 |
+
Number of transformers block
|
| 343 |
+
dropout (:obj:`float`, *optional*, defaults to 0.0):
|
| 344 |
+
Dropout rate
|
| 345 |
+
use_linear_projection (`bool`, defaults to `False`): tbd
|
| 346 |
+
only_cross_attention (`bool`, defaults to `False`): tbd
|
| 347 |
+
dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
|
| 348 |
+
Parameters `dtype`
|
| 349 |
+
use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
|
| 350 |
+
enable memory efficient attention https://arxiv.org/abs/2112.05682
|
| 351 |
+
split_head_dim (`bool`, *optional*, defaults to `False`):
|
| 352 |
+
Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
|
| 353 |
+
enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
in_channels: int
|
| 357 |
+
n_heads: int
|
| 358 |
+
d_head: int
|
| 359 |
+
depth: int = 1
|
| 360 |
+
dropout: float = 0.0
|
| 361 |
+
use_linear_projection: bool = False
|
| 362 |
+
only_cross_attention: bool = False
|
| 363 |
+
dtype: jnp.dtype = jnp.float32
|
| 364 |
+
use_memory_efficient_attention: bool = False
|
| 365 |
+
split_head_dim: bool = False
|
| 366 |
+
|
| 367 |
+
def setup(self):
|
| 368 |
+
self.norm = nn.GroupNorm(num_groups=32, epsilon=1e-5)
|
| 369 |
+
|
| 370 |
+
inner_dim = self.n_heads * self.d_head
|
| 371 |
+
if self.use_linear_projection:
|
| 372 |
+
self.proj_in = nn.Dense(inner_dim, dtype=self.dtype)
|
| 373 |
+
else:
|
| 374 |
+
self.proj_in = nn.Conv(
|
| 375 |
+
inner_dim,
|
| 376 |
+
kernel_size=(1, 1),
|
| 377 |
+
strides=(1, 1),
|
| 378 |
+
padding="VALID",
|
| 379 |
+
dtype=self.dtype,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
self.transformer_blocks = [
|
| 383 |
+
FlaxBasicTransformerBlock(
|
| 384 |
+
inner_dim,
|
| 385 |
+
self.n_heads,
|
| 386 |
+
self.d_head,
|
| 387 |
+
dropout=self.dropout,
|
| 388 |
+
only_cross_attention=self.only_cross_attention,
|
| 389 |
+
dtype=self.dtype,
|
| 390 |
+
use_memory_efficient_attention=self.use_memory_efficient_attention,
|
| 391 |
+
split_head_dim=self.split_head_dim,
|
| 392 |
+
)
|
| 393 |
+
for _ in range(self.depth)
|
| 394 |
+
]
|
| 395 |
+
|
| 396 |
+
if self.use_linear_projection:
|
| 397 |
+
self.proj_out = nn.Dense(inner_dim, dtype=self.dtype)
|
| 398 |
+
else:
|
| 399 |
+
self.proj_out = nn.Conv(
|
| 400 |
+
inner_dim,
|
| 401 |
+
kernel_size=(1, 1),
|
| 402 |
+
strides=(1, 1),
|
| 403 |
+
padding="VALID",
|
| 404 |
+
dtype=self.dtype,
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
self.dropout_layer = nn.Dropout(rate=self.dropout)
|
| 408 |
+
|
| 409 |
+
def __call__(self, hidden_states, context, deterministic=True):
|
| 410 |
+
batch, height, width, channels = hidden_states.shape
|
| 411 |
+
residual = hidden_states
|
| 412 |
+
hidden_states = self.norm(hidden_states)
|
| 413 |
+
if self.use_linear_projection:
|
| 414 |
+
hidden_states = hidden_states.reshape(batch, height * width, channels)
|
| 415 |
+
hidden_states = self.proj_in(hidden_states)
|
| 416 |
+
else:
|
| 417 |
+
hidden_states = self.proj_in(hidden_states)
|
| 418 |
+
hidden_states = hidden_states.reshape(batch, height * width, channels)
|
| 419 |
+
|
| 420 |
+
for transformer_block in self.transformer_blocks:
|
| 421 |
+
hidden_states = transformer_block(hidden_states, context, deterministic=deterministic)
|
| 422 |
+
|
| 423 |
+
if self.use_linear_projection:
|
| 424 |
+
hidden_states = self.proj_out(hidden_states)
|
| 425 |
+
hidden_states = hidden_states.reshape(batch, height, width, channels)
|
| 426 |
+
else:
|
| 427 |
+
hidden_states = hidden_states.reshape(batch, height, width, channels)
|
| 428 |
+
hidden_states = self.proj_out(hidden_states)
|
| 429 |
+
|
| 430 |
+
hidden_states = hidden_states + residual
|
| 431 |
+
return self.dropout_layer(hidden_states, deterministic=deterministic)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
class FlaxFeedForward(nn.Module):
|
| 435 |
+
r"""
|
| 436 |
+
Flax module that encapsulates two Linear layers separated by a non-linearity. It is the counterpart of PyTorch's
|
| 437 |
+
[`FeedForward`] class, with the following simplifications:
|
| 438 |
+
- The activation function is currently hardcoded to a gated linear unit from:
|
| 439 |
+
https://arxiv.org/abs/2002.05202
|
| 440 |
+
- `dim_out` is equal to `dim`.
|
| 441 |
+
- The number of hidden dimensions is hardcoded to `dim * 4` in [`FlaxGELU`].
|
| 442 |
+
|
| 443 |
+
Parameters:
|
| 444 |
+
dim (:obj:`int`):
|
| 445 |
+
Inner hidden states dimension
|
| 446 |
+
dropout (:obj:`float`, *optional*, defaults to 0.0):
|
| 447 |
+
Dropout rate
|
| 448 |
+
dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
|
| 449 |
+
Parameters `dtype`
|
| 450 |
+
"""
|
| 451 |
+
|
| 452 |
+
dim: int
|
| 453 |
+
dropout: float = 0.0
|
| 454 |
+
dtype: jnp.dtype = jnp.float32
|
| 455 |
+
|
| 456 |
+
def setup(self):
|
| 457 |
+
# The second linear layer needs to be called
|
| 458 |
+
# net_2 for now to match the index of the Sequential layer
|
| 459 |
+
self.net_0 = FlaxGEGLU(self.dim, self.dropout, self.dtype)
|
| 460 |
+
self.net_2 = nn.Dense(self.dim, dtype=self.dtype)
|
| 461 |
+
|
| 462 |
+
def __call__(self, hidden_states, deterministic=True):
|
| 463 |
+
hidden_states = self.net_0(hidden_states, deterministic=deterministic)
|
| 464 |
+
hidden_states = self.net_2(hidden_states)
|
| 465 |
+
return hidden_states
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class FlaxGEGLU(nn.Module):
|
| 469 |
+
r"""
|
| 470 |
+
Flax implementation of a Linear layer followed by the variant of the gated linear unit activation function from
|
| 471 |
+
https://arxiv.org/abs/2002.05202.
|
| 472 |
+
|
| 473 |
+
Parameters:
|
| 474 |
+
dim (:obj:`int`):
|
| 475 |
+
Input hidden states dimension
|
| 476 |
+
dropout (:obj:`float`, *optional*, defaults to 0.0):
|
| 477 |
+
Dropout rate
|
| 478 |
+
dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
|
| 479 |
+
Parameters `dtype`
|
| 480 |
+
"""
|
| 481 |
+
|
| 482 |
+
dim: int
|
| 483 |
+
dropout: float = 0.0
|
| 484 |
+
dtype: jnp.dtype = jnp.float32
|
| 485 |
+
|
| 486 |
+
def setup(self):
|
| 487 |
+
inner_dim = self.dim * 4
|
| 488 |
+
self.proj = nn.Dense(inner_dim * 2, dtype=self.dtype)
|
| 489 |
+
self.dropout_layer = nn.Dropout(rate=self.dropout)
|
| 490 |
+
|
| 491 |
+
def __call__(self, hidden_states, deterministic=True):
|
| 492 |
+
hidden_states = self.proj(hidden_states)
|
| 493 |
+
hidden_linear, hidden_gelu = jnp.split(hidden_states, 2, axis=2)
|
| 494 |
+
return self.dropout_layer(hidden_linear * nn.gelu(hidden_gelu), deterministic=deterministic)
|
diffusers/models/attention_processor.py
ADDED
|
@@ -0,0 +1,2305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from importlib import import_module
|
| 15 |
+
from typing import Callable, Optional, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from torch import einsum, nn
|
| 20 |
+
|
| 21 |
+
from ..utils import USE_PEFT_BACKEND, deprecate, logging
|
| 22 |
+
from ..utils.import_utils import is_xformers_available
|
| 23 |
+
from ..utils.torch_utils import maybe_allow_in_graph
|
| 24 |
+
from .lora import LoRACompatibleLinear, LoRALinearLayer
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_xformers_available():
|
| 31 |
+
import xformers
|
| 32 |
+
import xformers.ops
|
| 33 |
+
else:
|
| 34 |
+
xformers = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@maybe_allow_in_graph
|
| 38 |
+
class Attention(nn.Module):
|
| 39 |
+
r"""
|
| 40 |
+
A cross attention layer.
|
| 41 |
+
|
| 42 |
+
Parameters:
|
| 43 |
+
query_dim (`int`):
|
| 44 |
+
The number of channels in the query.
|
| 45 |
+
cross_attention_dim (`int`, *optional*):
|
| 46 |
+
The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`.
|
| 47 |
+
heads (`int`, *optional*, defaults to 8):
|
| 48 |
+
The number of heads to use for multi-head attention.
|
| 49 |
+
dim_head (`int`, *optional*, defaults to 64):
|
| 50 |
+
The number of channels in each head.
|
| 51 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
| 52 |
+
The dropout probability to use.
|
| 53 |
+
bias (`bool`, *optional*, defaults to False):
|
| 54 |
+
Set to `True` for the query, key, and value linear layers to contain a bias parameter.
|
| 55 |
+
upcast_attention (`bool`, *optional*, defaults to False):
|
| 56 |
+
Set to `True` to upcast the attention computation to `float32`.
|
| 57 |
+
upcast_softmax (`bool`, *optional*, defaults to False):
|
| 58 |
+
Set to `True` to upcast the softmax computation to `float32`.
|
| 59 |
+
cross_attention_norm (`str`, *optional*, defaults to `None`):
|
| 60 |
+
The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
|
| 61 |
+
cross_attention_norm_num_groups (`int`, *optional*, defaults to 32):
|
| 62 |
+
The number of groups to use for the group norm in the cross attention.
|
| 63 |
+
added_kv_proj_dim (`int`, *optional*, defaults to `None`):
|
| 64 |
+
The number of channels to use for the added key and value projections. If `None`, no projection is used.
|
| 65 |
+
norm_num_groups (`int`, *optional*, defaults to `None`):
|
| 66 |
+
The number of groups to use for the group norm in the attention.
|
| 67 |
+
spatial_norm_dim (`int`, *optional*, defaults to `None`):
|
| 68 |
+
The number of channels to use for the spatial normalization.
|
| 69 |
+
out_bias (`bool`, *optional*, defaults to `True`):
|
| 70 |
+
Set to `True` to use a bias in the output linear layer.
|
| 71 |
+
scale_qk (`bool`, *optional*, defaults to `True`):
|
| 72 |
+
Set to `True` to scale the query and key by `1 / sqrt(dim_head)`.
|
| 73 |
+
only_cross_attention (`bool`, *optional*, defaults to `False`):
|
| 74 |
+
Set to `True` to only use cross attention and not added_kv_proj_dim. Can only be set to `True` if
|
| 75 |
+
`added_kv_proj_dim` is not `None`.
|
| 76 |
+
eps (`float`, *optional*, defaults to 1e-5):
|
| 77 |
+
An additional value added to the denominator in group normalization that is used for numerical stability.
|
| 78 |
+
rescale_output_factor (`float`, *optional*, defaults to 1.0):
|
| 79 |
+
A factor to rescale the output by dividing it with this value.
|
| 80 |
+
residual_connection (`bool`, *optional*, defaults to `False`):
|
| 81 |
+
Set to `True` to add the residual connection to the output.
|
| 82 |
+
_from_deprecated_attn_block (`bool`, *optional*, defaults to `False`):
|
| 83 |
+
Set to `True` if the attention block is loaded from a deprecated state dict.
|
| 84 |
+
processor (`AttnProcessor`, *optional*, defaults to `None`):
|
| 85 |
+
The attention processor to use. If `None`, defaults to `AttnProcessor2_0` if `torch 2.x` is used and
|
| 86 |
+
`AttnProcessor` otherwise.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
query_dim: int,
|
| 92 |
+
cross_attention_dim: Optional[int] = None,
|
| 93 |
+
heads: int = 8,
|
| 94 |
+
dim_head: int = 64,
|
| 95 |
+
dropout: float = 0.0,
|
| 96 |
+
bias: bool = False,
|
| 97 |
+
upcast_attention: bool = False,
|
| 98 |
+
upcast_softmax: bool = False,
|
| 99 |
+
cross_attention_norm: Optional[str] = None,
|
| 100 |
+
cross_attention_norm_num_groups: int = 32,
|
| 101 |
+
added_kv_proj_dim: Optional[int] = None,
|
| 102 |
+
norm_num_groups: Optional[int] = None,
|
| 103 |
+
spatial_norm_dim: Optional[int] = None,
|
| 104 |
+
out_bias: bool = True,
|
| 105 |
+
scale_qk: bool = True,
|
| 106 |
+
only_cross_attention: bool = False,
|
| 107 |
+
eps: float = 1e-5,
|
| 108 |
+
rescale_output_factor: float = 1.0,
|
| 109 |
+
residual_connection: bool = False,
|
| 110 |
+
_from_deprecated_attn_block: bool = False,
|
| 111 |
+
processor: Optional["AttnProcessor"] = None,
|
| 112 |
+
):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.inner_dim = dim_head * heads
|
| 115 |
+
self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
|
| 116 |
+
self.upcast_attention = upcast_attention
|
| 117 |
+
self.upcast_softmax = upcast_softmax
|
| 118 |
+
self.rescale_output_factor = rescale_output_factor
|
| 119 |
+
self.residual_connection = residual_connection
|
| 120 |
+
self.dropout = dropout
|
| 121 |
+
|
| 122 |
+
# we make use of this private variable to know whether this class is loaded
|
| 123 |
+
# with an deprecated state dict so that we can convert it on the fly
|
| 124 |
+
self._from_deprecated_attn_block = _from_deprecated_attn_block
|
| 125 |
+
|
| 126 |
+
self.scale_qk = scale_qk
|
| 127 |
+
self.scale = dim_head**-0.5 if self.scale_qk else 1.0
|
| 128 |
+
|
| 129 |
+
self.heads = heads
|
| 130 |
+
# for slice_size > 0 the attention score computation
|
| 131 |
+
# is split across the batch axis to save memory
|
| 132 |
+
# You can set slice_size with `set_attention_slice`
|
| 133 |
+
self.sliceable_head_dim = heads
|
| 134 |
+
|
| 135 |
+
self.added_kv_proj_dim = added_kv_proj_dim
|
| 136 |
+
self.only_cross_attention = only_cross_attention
|
| 137 |
+
|
| 138 |
+
if self.added_kv_proj_dim is None and self.only_cross_attention:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
"`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
if norm_num_groups is not None:
|
| 144 |
+
self.group_norm = nn.GroupNorm(num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True)
|
| 145 |
+
else:
|
| 146 |
+
self.group_norm = None
|
| 147 |
+
|
| 148 |
+
if spatial_norm_dim is not None:
|
| 149 |
+
self.spatial_norm = SpatialNorm(f_channels=query_dim, zq_channels=spatial_norm_dim)
|
| 150 |
+
else:
|
| 151 |
+
self.spatial_norm = None
|
| 152 |
+
|
| 153 |
+
if cross_attention_norm is None:
|
| 154 |
+
self.norm_cross = None
|
| 155 |
+
elif cross_attention_norm == "layer_norm":
|
| 156 |
+
self.norm_cross = nn.LayerNorm(self.cross_attention_dim)
|
| 157 |
+
elif cross_attention_norm == "group_norm":
|
| 158 |
+
if self.added_kv_proj_dim is not None:
|
| 159 |
+
# The given `encoder_hidden_states` are initially of shape
|
| 160 |
+
# (batch_size, seq_len, added_kv_proj_dim) before being projected
|
| 161 |
+
# to (batch_size, seq_len, cross_attention_dim). The norm is applied
|
| 162 |
+
# before the projection, so we need to use `added_kv_proj_dim` as
|
| 163 |
+
# the number of channels for the group norm.
|
| 164 |
+
norm_cross_num_channels = added_kv_proj_dim
|
| 165 |
+
else:
|
| 166 |
+
norm_cross_num_channels = self.cross_attention_dim
|
| 167 |
+
|
| 168 |
+
self.norm_cross = nn.GroupNorm(
|
| 169 |
+
num_channels=norm_cross_num_channels, num_groups=cross_attention_norm_num_groups, eps=1e-5, affine=True
|
| 170 |
+
)
|
| 171 |
+
else:
|
| 172 |
+
raise ValueError(
|
| 173 |
+
f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
if USE_PEFT_BACKEND:
|
| 177 |
+
linear_cls = nn.Linear
|
| 178 |
+
else:
|
| 179 |
+
linear_cls = LoRACompatibleLinear
|
| 180 |
+
|
| 181 |
+
self.to_q = linear_cls(query_dim, self.inner_dim, bias=bias)
|
| 182 |
+
|
| 183 |
+
if not self.only_cross_attention:
|
| 184 |
+
# only relevant for the `AddedKVProcessor` classes
|
| 185 |
+
self.to_k = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
|
| 186 |
+
self.to_v = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
|
| 187 |
+
else:
|
| 188 |
+
self.to_k = None
|
| 189 |
+
self.to_v = None
|
| 190 |
+
|
| 191 |
+
if self.added_kv_proj_dim is not None:
|
| 192 |
+
self.add_k_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
|
| 193 |
+
self.add_v_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
|
| 194 |
+
|
| 195 |
+
self.to_out = nn.ModuleList([])
|
| 196 |
+
self.to_out.append(linear_cls(self.inner_dim, query_dim, bias=out_bias))
|
| 197 |
+
self.to_out.append(nn.Dropout(dropout))
|
| 198 |
+
|
| 199 |
+
# set attention processor
|
| 200 |
+
# We use the AttnProcessor2_0 by default when torch 2.x is used which uses
|
| 201 |
+
# torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
|
| 202 |
+
# but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
|
| 203 |
+
if processor is None:
|
| 204 |
+
processor = (
|
| 205 |
+
AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
|
| 206 |
+
)
|
| 207 |
+
self.set_processor(processor)
|
| 208 |
+
|
| 209 |
+
def set_use_memory_efficient_attention_xformers(
|
| 210 |
+
self, use_memory_efficient_attention_xformers: bool, attention_op: Optional[Callable] = None
|
| 211 |
+
) -> None:
|
| 212 |
+
r"""
|
| 213 |
+
Set whether to use memory efficient attention from `xformers` or not.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
use_memory_efficient_attention_xformers (`bool`):
|
| 217 |
+
Whether to use memory efficient attention from `xformers` or not.
|
| 218 |
+
attention_op (`Callable`, *optional*):
|
| 219 |
+
The attention operation to use. Defaults to `None` which uses the default attention operation from
|
| 220 |
+
`xformers`.
|
| 221 |
+
"""
|
| 222 |
+
is_lora = hasattr(self, "processor") and isinstance(
|
| 223 |
+
self.processor,
|
| 224 |
+
LORA_ATTENTION_PROCESSORS,
|
| 225 |
+
)
|
| 226 |
+
is_custom_diffusion = hasattr(self, "processor") and isinstance(
|
| 227 |
+
self.processor,
|
| 228 |
+
(CustomDiffusionAttnProcessor, CustomDiffusionXFormersAttnProcessor, CustomDiffusionAttnProcessor2_0),
|
| 229 |
+
)
|
| 230 |
+
is_added_kv_processor = hasattr(self, "processor") and isinstance(
|
| 231 |
+
self.processor,
|
| 232 |
+
(
|
| 233 |
+
AttnAddedKVProcessor,
|
| 234 |
+
AttnAddedKVProcessor2_0,
|
| 235 |
+
SlicedAttnAddedKVProcessor,
|
| 236 |
+
XFormersAttnAddedKVProcessor,
|
| 237 |
+
LoRAAttnAddedKVProcessor,
|
| 238 |
+
),
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
if use_memory_efficient_attention_xformers:
|
| 242 |
+
if is_added_kv_processor and (is_lora or is_custom_diffusion):
|
| 243 |
+
raise NotImplementedError(
|
| 244 |
+
f"Memory efficient attention is currently not supported for LoRA or custom diffusion for attention processor type {self.processor}"
|
| 245 |
+
)
|
| 246 |
+
if not is_xformers_available():
|
| 247 |
+
raise ModuleNotFoundError(
|
| 248 |
+
(
|
| 249 |
+
"Refer to https://github.com/facebookresearch/xformers for more information on how to install"
|
| 250 |
+
" xformers"
|
| 251 |
+
),
|
| 252 |
+
name="xformers",
|
| 253 |
+
)
|
| 254 |
+
elif not torch.cuda.is_available():
|
| 255 |
+
raise ValueError(
|
| 256 |
+
"torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is"
|
| 257 |
+
" only available for GPU "
|
| 258 |
+
)
|
| 259 |
+
else:
|
| 260 |
+
try:
|
| 261 |
+
# Make sure we can run the memory efficient attention
|
| 262 |
+
_ = xformers.ops.memory_efficient_attention(
|
| 263 |
+
torch.randn((1, 2, 40), device="cuda"),
|
| 264 |
+
torch.randn((1, 2, 40), device="cuda"),
|
| 265 |
+
torch.randn((1, 2, 40), device="cuda"),
|
| 266 |
+
)
|
| 267 |
+
except Exception as e:
|
| 268 |
+
raise e
|
| 269 |
+
|
| 270 |
+
if is_lora:
|
| 271 |
+
# TODO (sayakpaul): should we throw a warning if someone wants to use the xformers
|
| 272 |
+
# variant when using PT 2.0 now that we have LoRAAttnProcessor2_0?
|
| 273 |
+
processor = LoRAXFormersAttnProcessor(
|
| 274 |
+
hidden_size=self.processor.hidden_size,
|
| 275 |
+
cross_attention_dim=self.processor.cross_attention_dim,
|
| 276 |
+
rank=self.processor.rank,
|
| 277 |
+
attention_op=attention_op,
|
| 278 |
+
)
|
| 279 |
+
processor.load_state_dict(self.processor.state_dict())
|
| 280 |
+
processor.to(self.processor.to_q_lora.up.weight.device)
|
| 281 |
+
elif is_custom_diffusion:
|
| 282 |
+
processor = CustomDiffusionXFormersAttnProcessor(
|
| 283 |
+
train_kv=self.processor.train_kv,
|
| 284 |
+
train_q_out=self.processor.train_q_out,
|
| 285 |
+
hidden_size=self.processor.hidden_size,
|
| 286 |
+
cross_attention_dim=self.processor.cross_attention_dim,
|
| 287 |
+
attention_op=attention_op,
|
| 288 |
+
)
|
| 289 |
+
processor.load_state_dict(self.processor.state_dict())
|
| 290 |
+
if hasattr(self.processor, "to_k_custom_diffusion"):
|
| 291 |
+
processor.to(self.processor.to_k_custom_diffusion.weight.device)
|
| 292 |
+
elif is_added_kv_processor:
|
| 293 |
+
# TODO(Patrick, Suraj, William) - currently xformers doesn't work for UnCLIP
|
| 294 |
+
# which uses this type of cross attention ONLY because the attention mask of format
|
| 295 |
+
# [0, ..., -10.000, ..., 0, ...,] is not supported
|
| 296 |
+
# throw warning
|
| 297 |
+
logger.info(
|
| 298 |
+
"Memory efficient attention with `xformers` might currently not work correctly if an attention mask is required for the attention operation."
|
| 299 |
+
)
|
| 300 |
+
processor = XFormersAttnAddedKVProcessor(attention_op=attention_op)
|
| 301 |
+
else:
|
| 302 |
+
processor = XFormersAttnProcessor(attention_op=attention_op)
|
| 303 |
+
else:
|
| 304 |
+
if is_lora:
|
| 305 |
+
attn_processor_class = (
|
| 306 |
+
LoRAAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else LoRAAttnProcessor
|
| 307 |
+
)
|
| 308 |
+
processor = attn_processor_class(
|
| 309 |
+
hidden_size=self.processor.hidden_size,
|
| 310 |
+
cross_attention_dim=self.processor.cross_attention_dim,
|
| 311 |
+
rank=self.processor.rank,
|
| 312 |
+
)
|
| 313 |
+
processor.load_state_dict(self.processor.state_dict())
|
| 314 |
+
processor.to(self.processor.to_q_lora.up.weight.device)
|
| 315 |
+
elif is_custom_diffusion:
|
| 316 |
+
attn_processor_class = (
|
| 317 |
+
CustomDiffusionAttnProcessor2_0
|
| 318 |
+
if hasattr(F, "scaled_dot_product_attention")
|
| 319 |
+
else CustomDiffusionAttnProcessor
|
| 320 |
+
)
|
| 321 |
+
processor = attn_processor_class(
|
| 322 |
+
train_kv=self.processor.train_kv,
|
| 323 |
+
train_q_out=self.processor.train_q_out,
|
| 324 |
+
hidden_size=self.processor.hidden_size,
|
| 325 |
+
cross_attention_dim=self.processor.cross_attention_dim,
|
| 326 |
+
)
|
| 327 |
+
processor.load_state_dict(self.processor.state_dict())
|
| 328 |
+
if hasattr(self.processor, "to_k_custom_diffusion"):
|
| 329 |
+
processor.to(self.processor.to_k_custom_diffusion.weight.device)
|
| 330 |
+
else:
|
| 331 |
+
# set attention processor
|
| 332 |
+
# We use the AttnProcessor2_0 by default when torch 2.x is used which uses
|
| 333 |
+
# torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
|
| 334 |
+
# but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
|
| 335 |
+
processor = (
|
| 336 |
+
AttnProcessor2_0()
|
| 337 |
+
if hasattr(F, "scaled_dot_product_attention") and self.scale_qk
|
| 338 |
+
else AttnProcessor()
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
self.set_processor(processor)
|
| 342 |
+
|
| 343 |
+
def set_attention_slice(self, slice_size: int) -> None:
|
| 344 |
+
r"""
|
| 345 |
+
Set the slice size for attention computation.
|
| 346 |
+
|
| 347 |
+
Args:
|
| 348 |
+
slice_size (`int`):
|
| 349 |
+
The slice size for attention computation.
|
| 350 |
+
"""
|
| 351 |
+
if slice_size is not None and slice_size > self.sliceable_head_dim:
|
| 352 |
+
raise ValueError(f"slice_size {slice_size} has to be smaller or equal to {self.sliceable_head_dim}.")
|
| 353 |
+
|
| 354 |
+
if slice_size is not None and self.added_kv_proj_dim is not None:
|
| 355 |
+
processor = SlicedAttnAddedKVProcessor(slice_size)
|
| 356 |
+
elif slice_size is not None:
|
| 357 |
+
processor = SlicedAttnProcessor(slice_size)
|
| 358 |
+
elif self.added_kv_proj_dim is not None:
|
| 359 |
+
processor = AttnAddedKVProcessor()
|
| 360 |
+
else:
|
| 361 |
+
# set attention processor
|
| 362 |
+
# We use the AttnProcessor2_0 by default when torch 2.x is used which uses
|
| 363 |
+
# torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
|
| 364 |
+
# but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
|
| 365 |
+
processor = (
|
| 366 |
+
AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
self.set_processor(processor)
|
| 370 |
+
|
| 371 |
+
def set_processor(self, processor: "AttnProcessor", _remove_lora: bool = False) -> None:
|
| 372 |
+
r"""
|
| 373 |
+
Set the attention processor to use.
|
| 374 |
+
|
| 375 |
+
Args:
|
| 376 |
+
processor (`AttnProcessor`):
|
| 377 |
+
The attention processor to use.
|
| 378 |
+
_remove_lora (`bool`, *optional*, defaults to `False`):
|
| 379 |
+
Set to `True` to remove LoRA layers from the model.
|
| 380 |
+
"""
|
| 381 |
+
if not USE_PEFT_BACKEND and hasattr(self, "processor") and _remove_lora and self.to_q.lora_layer is not None:
|
| 382 |
+
deprecate(
|
| 383 |
+
"set_processor to offload LoRA",
|
| 384 |
+
"0.26.0",
|
| 385 |
+
"In detail, removing LoRA layers via calling `set_default_attn_processor` is deprecated. Please make sure to call `pipe.unload_lora_weights()` instead.",
|
| 386 |
+
)
|
| 387 |
+
# TODO(Patrick, Sayak) - this can be deprecated once PEFT LoRA integration is complete
|
| 388 |
+
# We need to remove all LoRA layers
|
| 389 |
+
# Don't forget to remove ALL `_remove_lora` from the codebase
|
| 390 |
+
for module in self.modules():
|
| 391 |
+
if hasattr(module, "set_lora_layer"):
|
| 392 |
+
module.set_lora_layer(None)
|
| 393 |
+
|
| 394 |
+
# if current processor is in `self._modules` and if passed `processor` is not, we need to
|
| 395 |
+
# pop `processor` from `self._modules`
|
| 396 |
+
if (
|
| 397 |
+
hasattr(self, "processor")
|
| 398 |
+
and isinstance(self.processor, torch.nn.Module)
|
| 399 |
+
and not isinstance(processor, torch.nn.Module)
|
| 400 |
+
):
|
| 401 |
+
logger.info(f"You are removing possibly trained weights of {self.processor} with {processor}")
|
| 402 |
+
self._modules.pop("processor")
|
| 403 |
+
|
| 404 |
+
self.processor = processor
|
| 405 |
+
|
| 406 |
+
def get_processor(self, return_deprecated_lora: bool = False) -> "AttentionProcessor":
|
| 407 |
+
r"""
|
| 408 |
+
Get the attention processor in use.
|
| 409 |
+
|
| 410 |
+
Args:
|
| 411 |
+
return_deprecated_lora (`bool`, *optional*, defaults to `False`):
|
| 412 |
+
Set to `True` to return the deprecated LoRA attention processor.
|
| 413 |
+
|
| 414 |
+
Returns:
|
| 415 |
+
"AttentionProcessor": The attention processor in use.
|
| 416 |
+
"""
|
| 417 |
+
if not return_deprecated_lora:
|
| 418 |
+
return self.processor
|
| 419 |
+
|
| 420 |
+
# TODO(Sayak, Patrick). The rest of the function is needed to ensure backwards compatible
|
| 421 |
+
# serialization format for LoRA Attention Processors. It should be deleted once the integration
|
| 422 |
+
# with PEFT is completed.
|
| 423 |
+
is_lora_activated = {
|
| 424 |
+
name: module.lora_layer is not None
|
| 425 |
+
for name, module in self.named_modules()
|
| 426 |
+
if hasattr(module, "lora_layer")
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
# 1. if no layer has a LoRA activated we can return the processor as usual
|
| 430 |
+
if not any(is_lora_activated.values()):
|
| 431 |
+
return self.processor
|
| 432 |
+
|
| 433 |
+
# If doesn't apply LoRA do `add_k_proj` or `add_v_proj`
|
| 434 |
+
is_lora_activated.pop("add_k_proj", None)
|
| 435 |
+
is_lora_activated.pop("add_v_proj", None)
|
| 436 |
+
# 2. else it is not posssible that only some layers have LoRA activated
|
| 437 |
+
if not all(is_lora_activated.values()):
|
| 438 |
+
raise ValueError(
|
| 439 |
+
f"Make sure that either all layers or no layers have LoRA activated, but have {is_lora_activated}"
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# 3. And we need to merge the current LoRA layers into the corresponding LoRA attention processor
|
| 443 |
+
non_lora_processor_cls_name = self.processor.__class__.__name__
|
| 444 |
+
lora_processor_cls = getattr(import_module(__name__), "LoRA" + non_lora_processor_cls_name)
|
| 445 |
+
|
| 446 |
+
hidden_size = self.inner_dim
|
| 447 |
+
|
| 448 |
+
# now create a LoRA attention processor from the LoRA layers
|
| 449 |
+
if lora_processor_cls in [LoRAAttnProcessor, LoRAAttnProcessor2_0, LoRAXFormersAttnProcessor]:
|
| 450 |
+
kwargs = {
|
| 451 |
+
"cross_attention_dim": self.cross_attention_dim,
|
| 452 |
+
"rank": self.to_q.lora_layer.rank,
|
| 453 |
+
"network_alpha": self.to_q.lora_layer.network_alpha,
|
| 454 |
+
"q_rank": self.to_q.lora_layer.rank,
|
| 455 |
+
"q_hidden_size": self.to_q.lora_layer.out_features,
|
| 456 |
+
"k_rank": self.to_k.lora_layer.rank,
|
| 457 |
+
"k_hidden_size": self.to_k.lora_layer.out_features,
|
| 458 |
+
"v_rank": self.to_v.lora_layer.rank,
|
| 459 |
+
"v_hidden_size": self.to_v.lora_layer.out_features,
|
| 460 |
+
"out_rank": self.to_out[0].lora_layer.rank,
|
| 461 |
+
"out_hidden_size": self.to_out[0].lora_layer.out_features,
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
if hasattr(self.processor, "attention_op"):
|
| 465 |
+
kwargs["attention_op"] = self.processor.attention_op
|
| 466 |
+
|
| 467 |
+
lora_processor = lora_processor_cls(hidden_size, **kwargs)
|
| 468 |
+
lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
|
| 469 |
+
lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
|
| 470 |
+
lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
|
| 471 |
+
lora_processor.to_out_lora.load_state_dict(self.to_out[0].lora_layer.state_dict())
|
| 472 |
+
elif lora_processor_cls == LoRAAttnAddedKVProcessor:
|
| 473 |
+
lora_processor = lora_processor_cls(
|
| 474 |
+
hidden_size,
|
| 475 |
+
cross_attention_dim=self.add_k_proj.weight.shape[0],
|
| 476 |
+
rank=self.to_q.lora_layer.rank,
|
| 477 |
+
network_alpha=self.to_q.lora_layer.network_alpha,
|
| 478 |
+
)
|
| 479 |
+
lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
|
| 480 |
+
lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
|
| 481 |
+
lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
|
| 482 |
+
lora_processor.to_out_lora.load_state_dict(self.to_out[0].lora_layer.state_dict())
|
| 483 |
+
|
| 484 |
+
# only save if used
|
| 485 |
+
if self.add_k_proj.lora_layer is not None:
|
| 486 |
+
lora_processor.add_k_proj_lora.load_state_dict(self.add_k_proj.lora_layer.state_dict())
|
| 487 |
+
lora_processor.add_v_proj_lora.load_state_dict(self.add_v_proj.lora_layer.state_dict())
|
| 488 |
+
else:
|
| 489 |
+
lora_processor.add_k_proj_lora = None
|
| 490 |
+
lora_processor.add_v_proj_lora = None
|
| 491 |
+
else:
|
| 492 |
+
raise ValueError(f"{lora_processor_cls} does not exist.")
|
| 493 |
+
|
| 494 |
+
return lora_processor
|
| 495 |
+
|
| 496 |
+
def forward(
|
| 497 |
+
self,
|
| 498 |
+
hidden_states: torch.FloatTensor,
|
| 499 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 500 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 501 |
+
**cross_attention_kwargs,
|
| 502 |
+
) -> torch.Tensor:
|
| 503 |
+
r"""
|
| 504 |
+
The forward method of the `Attention` class.
|
| 505 |
+
|
| 506 |
+
Args:
|
| 507 |
+
hidden_states (`torch.Tensor`):
|
| 508 |
+
The hidden states of the query.
|
| 509 |
+
encoder_hidden_states (`torch.Tensor`, *optional*):
|
| 510 |
+
The hidden states of the encoder.
|
| 511 |
+
attention_mask (`torch.Tensor`, *optional*):
|
| 512 |
+
The attention mask to use. If `None`, no mask is applied.
|
| 513 |
+
**cross_attention_kwargs:
|
| 514 |
+
Additional keyword arguments to pass along to the cross attention.
|
| 515 |
+
|
| 516 |
+
Returns:
|
| 517 |
+
`torch.Tensor`: The output of the attention layer.
|
| 518 |
+
"""
|
| 519 |
+
# The `Attention` class can call different attention processors / attention functions
|
| 520 |
+
# here we simply pass along all tensors to the selected processor class
|
| 521 |
+
# For standard processors that are defined here, `**cross_attention_kwargs` is empty
|
| 522 |
+
return self.processor(
|
| 523 |
+
self,
|
| 524 |
+
hidden_states,
|
| 525 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 526 |
+
attention_mask=attention_mask,
|
| 527 |
+
**cross_attention_kwargs,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
|
| 531 |
+
r"""
|
| 532 |
+
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
|
| 533 |
+
is the number of heads initialized while constructing the `Attention` class.
|
| 534 |
+
|
| 535 |
+
Args:
|
| 536 |
+
tensor (`torch.Tensor`): The tensor to reshape.
|
| 537 |
+
|
| 538 |
+
Returns:
|
| 539 |
+
`torch.Tensor`: The reshaped tensor.
|
| 540 |
+
"""
|
| 541 |
+
head_size = self.heads
|
| 542 |
+
batch_size, seq_len, dim = tensor.shape
|
| 543 |
+
tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
|
| 544 |
+
tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
|
| 545 |
+
return tensor
|
| 546 |
+
|
| 547 |
+
def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
|
| 548 |
+
r"""
|
| 549 |
+
Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
|
| 550 |
+
the number of heads initialized while constructing the `Attention` class.
|
| 551 |
+
|
| 552 |
+
Args:
|
| 553 |
+
tensor (`torch.Tensor`): The tensor to reshape.
|
| 554 |
+
out_dim (`int`, *optional*, defaults to `3`): The output dimension of the tensor. If `3`, the tensor is
|
| 555 |
+
reshaped to `[batch_size * heads, seq_len, dim // heads]`.
|
| 556 |
+
|
| 557 |
+
Returns:
|
| 558 |
+
`torch.Tensor`: The reshaped tensor.
|
| 559 |
+
"""
|
| 560 |
+
head_size = self.heads
|
| 561 |
+
batch_size, seq_len, dim = tensor.shape
|
| 562 |
+
tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
|
| 563 |
+
tensor = tensor.permute(0, 2, 1, 3)
|
| 564 |
+
|
| 565 |
+
if out_dim == 3:
|
| 566 |
+
tensor = tensor.reshape(batch_size * head_size, seq_len, dim // head_size)
|
| 567 |
+
|
| 568 |
+
return tensor
|
| 569 |
+
|
| 570 |
+
def get_attention_scores(
|
| 571 |
+
self, query: torch.Tensor, key: torch.Tensor, attention_mask: torch.Tensor = None
|
| 572 |
+
) -> torch.Tensor:
|
| 573 |
+
r"""
|
| 574 |
+
Compute the attention scores.
|
| 575 |
+
|
| 576 |
+
Args:
|
| 577 |
+
query (`torch.Tensor`): The query tensor.
|
| 578 |
+
key (`torch.Tensor`): The key tensor.
|
| 579 |
+
attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
|
| 580 |
+
|
| 581 |
+
Returns:
|
| 582 |
+
`torch.Tensor`: The attention probabilities/scores.
|
| 583 |
+
"""
|
| 584 |
+
dtype = query.dtype
|
| 585 |
+
if self.upcast_attention:
|
| 586 |
+
query = query.float()
|
| 587 |
+
key = key.float()
|
| 588 |
+
|
| 589 |
+
if attention_mask is None:
|
| 590 |
+
baddbmm_input = torch.empty(
|
| 591 |
+
query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
|
| 592 |
+
)
|
| 593 |
+
beta = 0
|
| 594 |
+
else:
|
| 595 |
+
baddbmm_input = attention_mask
|
| 596 |
+
beta = 1
|
| 597 |
+
|
| 598 |
+
attention_scores = torch.baddbmm(
|
| 599 |
+
baddbmm_input,
|
| 600 |
+
query,
|
| 601 |
+
key.transpose(-1, -2),
|
| 602 |
+
beta=beta,
|
| 603 |
+
alpha=self.scale,
|
| 604 |
+
)
|
| 605 |
+
del baddbmm_input
|
| 606 |
+
|
| 607 |
+
if self.upcast_softmax:
|
| 608 |
+
attention_scores = attention_scores.float()
|
| 609 |
+
|
| 610 |
+
attention_probs = attention_scores.softmax(dim=-1)
|
| 611 |
+
del attention_scores
|
| 612 |
+
|
| 613 |
+
attention_probs = attention_probs.to(dtype)
|
| 614 |
+
|
| 615 |
+
return attention_probs
|
| 616 |
+
|
| 617 |
+
def prepare_attention_mask(
|
| 618 |
+
self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3
|
| 619 |
+
) -> torch.Tensor:
|
| 620 |
+
r"""
|
| 621 |
+
Prepare the attention mask for the attention computation.
|
| 622 |
+
|
| 623 |
+
Args:
|
| 624 |
+
attention_mask (`torch.Tensor`):
|
| 625 |
+
The attention mask to prepare.
|
| 626 |
+
target_length (`int`):
|
| 627 |
+
The target length of the attention mask. This is the length of the attention mask after padding.
|
| 628 |
+
batch_size (`int`):
|
| 629 |
+
The batch size, which is used to repeat the attention mask.
|
| 630 |
+
out_dim (`int`, *optional*, defaults to `3`):
|
| 631 |
+
The output dimension of the attention mask. Can be either `3` or `4`.
|
| 632 |
+
|
| 633 |
+
Returns:
|
| 634 |
+
`torch.Tensor`: The prepared attention mask.
|
| 635 |
+
"""
|
| 636 |
+
head_size = self.heads
|
| 637 |
+
if attention_mask is None:
|
| 638 |
+
return attention_mask
|
| 639 |
+
|
| 640 |
+
current_length: int = attention_mask.shape[-1]
|
| 641 |
+
if current_length != target_length:
|
| 642 |
+
if attention_mask.device.type == "mps":
|
| 643 |
+
# HACK: MPS: Does not support padding by greater than dimension of input tensor.
|
| 644 |
+
# Instead, we can manually construct the padding tensor.
|
| 645 |
+
padding_shape = (attention_mask.shape[0], attention_mask.shape[1], target_length)
|
| 646 |
+
padding = torch.zeros(padding_shape, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 647 |
+
attention_mask = torch.cat([attention_mask, padding], dim=2)
|
| 648 |
+
else:
|
| 649 |
+
# TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
|
| 650 |
+
# we want to instead pad by (0, remaining_length), where remaining_length is:
|
| 651 |
+
# remaining_length: int = target_length - current_length
|
| 652 |
+
# TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
|
| 653 |
+
attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
|
| 654 |
+
|
| 655 |
+
if out_dim == 3:
|
| 656 |
+
if attention_mask.shape[0] < batch_size * head_size:
|
| 657 |
+
attention_mask = attention_mask.repeat_interleave(head_size, dim=0)
|
| 658 |
+
elif out_dim == 4:
|
| 659 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 660 |
+
attention_mask = attention_mask.repeat_interleave(head_size, dim=1)
|
| 661 |
+
|
| 662 |
+
return attention_mask
|
| 663 |
+
|
| 664 |
+
def norm_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
|
| 665 |
+
r"""
|
| 666 |
+
Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
|
| 667 |
+
`Attention` class.
|
| 668 |
+
|
| 669 |
+
Args:
|
| 670 |
+
encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
|
| 671 |
+
|
| 672 |
+
Returns:
|
| 673 |
+
`torch.Tensor`: The normalized encoder hidden states.
|
| 674 |
+
"""
|
| 675 |
+
assert self.norm_cross is not None, "self.norm_cross must be defined to call self.norm_encoder_hidden_states"
|
| 676 |
+
|
| 677 |
+
if isinstance(self.norm_cross, nn.LayerNorm):
|
| 678 |
+
encoder_hidden_states = self.norm_cross(encoder_hidden_states)
|
| 679 |
+
elif isinstance(self.norm_cross, nn.GroupNorm):
|
| 680 |
+
# Group norm norms along the channels dimension and expects
|
| 681 |
+
# input to be in the shape of (N, C, *). In this case, we want
|
| 682 |
+
# to norm along the hidden dimension, so we need to move
|
| 683 |
+
# (batch_size, sequence_length, hidden_size) ->
|
| 684 |
+
# (batch_size, hidden_size, sequence_length)
|
| 685 |
+
encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
|
| 686 |
+
encoder_hidden_states = self.norm_cross(encoder_hidden_states)
|
| 687 |
+
encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
|
| 688 |
+
else:
|
| 689 |
+
assert False
|
| 690 |
+
|
| 691 |
+
return encoder_hidden_states
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
class AttnProcessor:
|
| 695 |
+
r"""
|
| 696 |
+
Default processor for performing attention-related computations.
|
| 697 |
+
"""
|
| 698 |
+
|
| 699 |
+
def __call__(
|
| 700 |
+
self,
|
| 701 |
+
attn: Attention,
|
| 702 |
+
hidden_states: torch.FloatTensor,
|
| 703 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 704 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 705 |
+
temb: Optional[torch.FloatTensor] = None,
|
| 706 |
+
scale: float = 1.0,
|
| 707 |
+
) -> torch.Tensor:
|
| 708 |
+
residual = hidden_states
|
| 709 |
+
|
| 710 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
| 711 |
+
|
| 712 |
+
if attn.spatial_norm is not None:
|
| 713 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 714 |
+
|
| 715 |
+
input_ndim = hidden_states.ndim
|
| 716 |
+
|
| 717 |
+
if input_ndim == 4:
|
| 718 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 719 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 720 |
+
|
| 721 |
+
batch_size, sequence_length, _ = (
|
| 722 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 723 |
+
)
|
| 724 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 725 |
+
|
| 726 |
+
if attn.group_norm is not None:
|
| 727 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 728 |
+
|
| 729 |
+
query = attn.to_q(hidden_states, *args)
|
| 730 |
+
|
| 731 |
+
if encoder_hidden_states is None:
|
| 732 |
+
encoder_hidden_states = hidden_states
|
| 733 |
+
elif attn.norm_cross:
|
| 734 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 735 |
+
|
| 736 |
+
key = attn.to_k(encoder_hidden_states, *args)
|
| 737 |
+
value = attn.to_v(encoder_hidden_states, *args)
|
| 738 |
+
|
| 739 |
+
query = attn.head_to_batch_dim(query)
|
| 740 |
+
key = attn.head_to_batch_dim(key)
|
| 741 |
+
value = attn.head_to_batch_dim(value)
|
| 742 |
+
|
| 743 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 744 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 745 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 746 |
+
|
| 747 |
+
# linear proj
|
| 748 |
+
hidden_states = attn.to_out[0](hidden_states, *args)
|
| 749 |
+
# dropout
|
| 750 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 751 |
+
|
| 752 |
+
if input_ndim == 4:
|
| 753 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 754 |
+
|
| 755 |
+
if attn.residual_connection:
|
| 756 |
+
hidden_states = hidden_states + residual
|
| 757 |
+
|
| 758 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 759 |
+
|
| 760 |
+
return hidden_states
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class CustomDiffusionAttnProcessor(nn.Module):
|
| 764 |
+
r"""
|
| 765 |
+
Processor for implementing attention for the Custom Diffusion method.
|
| 766 |
+
|
| 767 |
+
Args:
|
| 768 |
+
train_kv (`bool`, defaults to `True`):
|
| 769 |
+
Whether to newly train the key and value matrices corresponding to the text features.
|
| 770 |
+
train_q_out (`bool`, defaults to `True`):
|
| 771 |
+
Whether to newly train query matrices corresponding to the latent image features.
|
| 772 |
+
hidden_size (`int`, *optional*, defaults to `None`):
|
| 773 |
+
The hidden size of the attention layer.
|
| 774 |
+
cross_attention_dim (`int`, *optional*, defaults to `None`):
|
| 775 |
+
The number of channels in the `encoder_hidden_states`.
|
| 776 |
+
out_bias (`bool`, defaults to `True`):
|
| 777 |
+
Whether to include the bias parameter in `train_q_out`.
|
| 778 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
| 779 |
+
The dropout probability to use.
|
| 780 |
+
"""
|
| 781 |
+
|
| 782 |
+
def __init__(
|
| 783 |
+
self,
|
| 784 |
+
train_kv: bool = True,
|
| 785 |
+
train_q_out: bool = True,
|
| 786 |
+
hidden_size: Optional[int] = None,
|
| 787 |
+
cross_attention_dim: Optional[int] = None,
|
| 788 |
+
out_bias: bool = True,
|
| 789 |
+
dropout: float = 0.0,
|
| 790 |
+
):
|
| 791 |
+
super().__init__()
|
| 792 |
+
self.train_kv = train_kv
|
| 793 |
+
self.train_q_out = train_q_out
|
| 794 |
+
|
| 795 |
+
self.hidden_size = hidden_size
|
| 796 |
+
self.cross_attention_dim = cross_attention_dim
|
| 797 |
+
|
| 798 |
+
# `_custom_diffusion` id for easy serialization and loading.
|
| 799 |
+
if self.train_kv:
|
| 800 |
+
self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 801 |
+
self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 802 |
+
if self.train_q_out:
|
| 803 |
+
self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
|
| 804 |
+
self.to_out_custom_diffusion = nn.ModuleList([])
|
| 805 |
+
self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
|
| 806 |
+
self.to_out_custom_diffusion.append(nn.Dropout(dropout))
|
| 807 |
+
|
| 808 |
+
def __call__(
|
| 809 |
+
self,
|
| 810 |
+
attn: Attention,
|
| 811 |
+
hidden_states: torch.FloatTensor,
|
| 812 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 813 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 814 |
+
) -> torch.Tensor:
|
| 815 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 816 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 817 |
+
if self.train_q_out:
|
| 818 |
+
query = self.to_q_custom_diffusion(hidden_states).to(attn.to_q.weight.dtype)
|
| 819 |
+
else:
|
| 820 |
+
query = attn.to_q(hidden_states.to(attn.to_q.weight.dtype))
|
| 821 |
+
|
| 822 |
+
if encoder_hidden_states is None:
|
| 823 |
+
crossattn = False
|
| 824 |
+
encoder_hidden_states = hidden_states
|
| 825 |
+
else:
|
| 826 |
+
crossattn = True
|
| 827 |
+
if attn.norm_cross:
|
| 828 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 829 |
+
|
| 830 |
+
if self.train_kv:
|
| 831 |
+
key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
|
| 832 |
+
value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
|
| 833 |
+
key = key.to(attn.to_q.weight.dtype)
|
| 834 |
+
value = value.to(attn.to_q.weight.dtype)
|
| 835 |
+
else:
|
| 836 |
+
key = attn.to_k(encoder_hidden_states)
|
| 837 |
+
value = attn.to_v(encoder_hidden_states)
|
| 838 |
+
|
| 839 |
+
if crossattn:
|
| 840 |
+
detach = torch.ones_like(key)
|
| 841 |
+
detach[:, :1, :] = detach[:, :1, :] * 0.0
|
| 842 |
+
key = detach * key + (1 - detach) * key.detach()
|
| 843 |
+
value = detach * value + (1 - detach) * value.detach()
|
| 844 |
+
|
| 845 |
+
query = attn.head_to_batch_dim(query)
|
| 846 |
+
key = attn.head_to_batch_dim(key)
|
| 847 |
+
value = attn.head_to_batch_dim(value)
|
| 848 |
+
|
| 849 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 850 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 851 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 852 |
+
|
| 853 |
+
if self.train_q_out:
|
| 854 |
+
# linear proj
|
| 855 |
+
hidden_states = self.to_out_custom_diffusion[0](hidden_states)
|
| 856 |
+
# dropout
|
| 857 |
+
hidden_states = self.to_out_custom_diffusion[1](hidden_states)
|
| 858 |
+
else:
|
| 859 |
+
# linear proj
|
| 860 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 861 |
+
# dropout
|
| 862 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 863 |
+
|
| 864 |
+
return hidden_states
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
class AttnAddedKVProcessor:
|
| 868 |
+
r"""
|
| 869 |
+
Processor for performing attention-related computations with extra learnable key and value matrices for the text
|
| 870 |
+
encoder.
|
| 871 |
+
"""
|
| 872 |
+
|
| 873 |
+
def __call__(
|
| 874 |
+
self,
|
| 875 |
+
attn: Attention,
|
| 876 |
+
hidden_states: torch.FloatTensor,
|
| 877 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 878 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 879 |
+
scale: float = 1.0,
|
| 880 |
+
) -> torch.Tensor:
|
| 881 |
+
residual = hidden_states
|
| 882 |
+
|
| 883 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
| 884 |
+
|
| 885 |
+
hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
|
| 886 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 887 |
+
|
| 888 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 889 |
+
|
| 890 |
+
if encoder_hidden_states is None:
|
| 891 |
+
encoder_hidden_states = hidden_states
|
| 892 |
+
elif attn.norm_cross:
|
| 893 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 894 |
+
|
| 895 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 896 |
+
|
| 897 |
+
query = attn.to_q(hidden_states, *args)
|
| 898 |
+
query = attn.head_to_batch_dim(query)
|
| 899 |
+
|
| 900 |
+
encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states, *args)
|
| 901 |
+
encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states, *args)
|
| 902 |
+
encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
|
| 903 |
+
encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
|
| 904 |
+
|
| 905 |
+
if not attn.only_cross_attention:
|
| 906 |
+
key = attn.to_k(hidden_states, *args)
|
| 907 |
+
value = attn.to_v(hidden_states, *args)
|
| 908 |
+
key = attn.head_to_batch_dim(key)
|
| 909 |
+
value = attn.head_to_batch_dim(value)
|
| 910 |
+
key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
|
| 911 |
+
value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
|
| 912 |
+
else:
|
| 913 |
+
key = encoder_hidden_states_key_proj
|
| 914 |
+
value = encoder_hidden_states_value_proj
|
| 915 |
+
|
| 916 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 917 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 918 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 919 |
+
|
| 920 |
+
# linear proj
|
| 921 |
+
hidden_states = attn.to_out[0](hidden_states, *args)
|
| 922 |
+
# dropout
|
| 923 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 924 |
+
|
| 925 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
|
| 926 |
+
hidden_states = hidden_states + residual
|
| 927 |
+
|
| 928 |
+
return hidden_states
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
class AttnAddedKVProcessor2_0:
|
| 932 |
+
r"""
|
| 933 |
+
Processor for performing scaled dot-product attention (enabled by default if you're using PyTorch 2.0), with extra
|
| 934 |
+
learnable key and value matrices for the text encoder.
|
| 935 |
+
"""
|
| 936 |
+
|
| 937 |
+
def __init__(self):
|
| 938 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 939 |
+
raise ImportError(
|
| 940 |
+
"AttnAddedKVProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
def __call__(
|
| 944 |
+
self,
|
| 945 |
+
attn: Attention,
|
| 946 |
+
hidden_states: torch.FloatTensor,
|
| 947 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 948 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 949 |
+
scale: float = 1.0,
|
| 950 |
+
) -> torch.Tensor:
|
| 951 |
+
residual = hidden_states
|
| 952 |
+
|
| 953 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
| 954 |
+
|
| 955 |
+
hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
|
| 956 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 957 |
+
|
| 958 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size, out_dim=4)
|
| 959 |
+
|
| 960 |
+
if encoder_hidden_states is None:
|
| 961 |
+
encoder_hidden_states = hidden_states
|
| 962 |
+
elif attn.norm_cross:
|
| 963 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 964 |
+
|
| 965 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 966 |
+
|
| 967 |
+
query = attn.to_q(hidden_states, *args)
|
| 968 |
+
query = attn.head_to_batch_dim(query, out_dim=4)
|
| 969 |
+
|
| 970 |
+
encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
|
| 971 |
+
encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
|
| 972 |
+
encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj, out_dim=4)
|
| 973 |
+
encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj, out_dim=4)
|
| 974 |
+
|
| 975 |
+
if not attn.only_cross_attention:
|
| 976 |
+
key = attn.to_k(hidden_states, *args)
|
| 977 |
+
value = attn.to_v(hidden_states, *args)
|
| 978 |
+
key = attn.head_to_batch_dim(key, out_dim=4)
|
| 979 |
+
value = attn.head_to_batch_dim(value, out_dim=4)
|
| 980 |
+
key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
|
| 981 |
+
value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
|
| 982 |
+
else:
|
| 983 |
+
key = encoder_hidden_states_key_proj
|
| 984 |
+
value = encoder_hidden_states_value_proj
|
| 985 |
+
|
| 986 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 987 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 988 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 989 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
| 990 |
+
)
|
| 991 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, residual.shape[1])
|
| 992 |
+
|
| 993 |
+
# linear proj
|
| 994 |
+
hidden_states = attn.to_out[0](hidden_states, *args)
|
| 995 |
+
# dropout
|
| 996 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 997 |
+
|
| 998 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
|
| 999 |
+
hidden_states = hidden_states + residual
|
| 1000 |
+
|
| 1001 |
+
return hidden_states
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
class XFormersAttnAddedKVProcessor:
|
| 1005 |
+
r"""
|
| 1006 |
+
Processor for implementing memory efficient attention using xFormers.
|
| 1007 |
+
|
| 1008 |
+
Args:
|
| 1009 |
+
attention_op (`Callable`, *optional*, defaults to `None`):
|
| 1010 |
+
The base
|
| 1011 |
+
[operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
|
| 1012 |
+
use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
|
| 1013 |
+
operator.
|
| 1014 |
+
"""
|
| 1015 |
+
|
| 1016 |
+
def __init__(self, attention_op: Optional[Callable] = None):
|
| 1017 |
+
self.attention_op = attention_op
|
| 1018 |
+
|
| 1019 |
+
def __call__(
|
| 1020 |
+
self,
|
| 1021 |
+
attn: Attention,
|
| 1022 |
+
hidden_states: torch.FloatTensor,
|
| 1023 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1024 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1025 |
+
) -> torch.Tensor:
|
| 1026 |
+
residual = hidden_states
|
| 1027 |
+
hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
|
| 1028 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 1029 |
+
|
| 1030 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 1031 |
+
|
| 1032 |
+
if encoder_hidden_states is None:
|
| 1033 |
+
encoder_hidden_states = hidden_states
|
| 1034 |
+
elif attn.norm_cross:
|
| 1035 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 1036 |
+
|
| 1037 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 1038 |
+
|
| 1039 |
+
query = attn.to_q(hidden_states)
|
| 1040 |
+
query = attn.head_to_batch_dim(query)
|
| 1041 |
+
|
| 1042 |
+
encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
|
| 1043 |
+
encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
|
| 1044 |
+
encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
|
| 1045 |
+
encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
|
| 1046 |
+
|
| 1047 |
+
if not attn.only_cross_attention:
|
| 1048 |
+
key = attn.to_k(hidden_states)
|
| 1049 |
+
value = attn.to_v(hidden_states)
|
| 1050 |
+
key = attn.head_to_batch_dim(key)
|
| 1051 |
+
value = attn.head_to_batch_dim(value)
|
| 1052 |
+
key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
|
| 1053 |
+
value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
|
| 1054 |
+
else:
|
| 1055 |
+
key = encoder_hidden_states_key_proj
|
| 1056 |
+
value = encoder_hidden_states_value_proj
|
| 1057 |
+
|
| 1058 |
+
hidden_states = xformers.ops.memory_efficient_attention(
|
| 1059 |
+
query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
|
| 1060 |
+
)
|
| 1061 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 1062 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 1063 |
+
|
| 1064 |
+
# linear proj
|
| 1065 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 1066 |
+
# dropout
|
| 1067 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 1068 |
+
|
| 1069 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
|
| 1070 |
+
hidden_states = hidden_states + residual
|
| 1071 |
+
|
| 1072 |
+
return hidden_states
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
class XFormersAttnProcessor:
|
| 1076 |
+
r"""
|
| 1077 |
+
Processor for implementing memory efficient attention using xFormers.
|
| 1078 |
+
|
| 1079 |
+
Args:
|
| 1080 |
+
attention_op (`Callable`, *optional*, defaults to `None`):
|
| 1081 |
+
The base
|
| 1082 |
+
[operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
|
| 1083 |
+
use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
|
| 1084 |
+
operator.
|
| 1085 |
+
"""
|
| 1086 |
+
|
| 1087 |
+
def __init__(self, attention_op: Optional[Callable] = None):
|
| 1088 |
+
self.attention_op = attention_op
|
| 1089 |
+
|
| 1090 |
+
def __call__(
|
| 1091 |
+
self,
|
| 1092 |
+
attn: Attention,
|
| 1093 |
+
hidden_states: torch.FloatTensor,
|
| 1094 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1095 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1096 |
+
temb: Optional[torch.FloatTensor] = None,
|
| 1097 |
+
scale: float = 1.0,
|
| 1098 |
+
) -> torch.FloatTensor:
|
| 1099 |
+
residual = hidden_states
|
| 1100 |
+
|
| 1101 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
| 1102 |
+
|
| 1103 |
+
if attn.spatial_norm is not None:
|
| 1104 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 1105 |
+
|
| 1106 |
+
input_ndim = hidden_states.ndim
|
| 1107 |
+
|
| 1108 |
+
if input_ndim == 4:
|
| 1109 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 1110 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 1111 |
+
|
| 1112 |
+
batch_size, key_tokens, _ = (
|
| 1113 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, key_tokens, batch_size)
|
| 1117 |
+
if attention_mask is not None:
|
| 1118 |
+
# expand our mask's singleton query_tokens dimension:
|
| 1119 |
+
# [batch*heads, 1, key_tokens] ->
|
| 1120 |
+
# [batch*heads, query_tokens, key_tokens]
|
| 1121 |
+
# so that it can be added as a bias onto the attention scores that xformers computes:
|
| 1122 |
+
# [batch*heads, query_tokens, key_tokens]
|
| 1123 |
+
# we do this explicitly because xformers doesn't broadcast the singleton dimension for us.
|
| 1124 |
+
_, query_tokens, _ = hidden_states.shape
|
| 1125 |
+
attention_mask = attention_mask.expand(-1, query_tokens, -1)
|
| 1126 |
+
|
| 1127 |
+
if attn.group_norm is not None:
|
| 1128 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 1129 |
+
|
| 1130 |
+
query = attn.to_q(hidden_states, *args)
|
| 1131 |
+
|
| 1132 |
+
if encoder_hidden_states is None:
|
| 1133 |
+
encoder_hidden_states = hidden_states
|
| 1134 |
+
elif attn.norm_cross:
|
| 1135 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 1136 |
+
|
| 1137 |
+
key = attn.to_k(encoder_hidden_states, *args)
|
| 1138 |
+
value = attn.to_v(encoder_hidden_states, *args)
|
| 1139 |
+
|
| 1140 |
+
query = attn.head_to_batch_dim(query).contiguous()
|
| 1141 |
+
key = attn.head_to_batch_dim(key).contiguous()
|
| 1142 |
+
value = attn.head_to_batch_dim(value).contiguous()
|
| 1143 |
+
|
| 1144 |
+
hidden_states = xformers.ops.memory_efficient_attention(
|
| 1145 |
+
query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
|
| 1146 |
+
)
|
| 1147 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 1148 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 1149 |
+
|
| 1150 |
+
# linear proj
|
| 1151 |
+
hidden_states = attn.to_out[0](hidden_states, *args)
|
| 1152 |
+
# dropout
|
| 1153 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 1154 |
+
|
| 1155 |
+
if input_ndim == 4:
|
| 1156 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 1157 |
+
|
| 1158 |
+
if attn.residual_connection:
|
| 1159 |
+
hidden_states = hidden_states + residual
|
| 1160 |
+
|
| 1161 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 1162 |
+
|
| 1163 |
+
return hidden_states
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
class AttnProcessor2_0:
|
| 1167 |
+
r"""
|
| 1168 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
| 1169 |
+
"""
|
| 1170 |
+
|
| 1171 |
+
def __init__(self):
|
| 1172 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 1173 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 1174 |
+
|
| 1175 |
+
def __call__(
|
| 1176 |
+
self,
|
| 1177 |
+
attn: Attention,
|
| 1178 |
+
hidden_states: torch.FloatTensor,
|
| 1179 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1180 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1181 |
+
temb: Optional[torch.FloatTensor] = None,
|
| 1182 |
+
scale: float = 1.0,
|
| 1183 |
+
) -> torch.FloatTensor:
|
| 1184 |
+
residual = hidden_states
|
| 1185 |
+
|
| 1186 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
| 1187 |
+
|
| 1188 |
+
if attn.spatial_norm is not None:
|
| 1189 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 1190 |
+
|
| 1191 |
+
input_ndim = hidden_states.ndim
|
| 1192 |
+
|
| 1193 |
+
if input_ndim == 4:
|
| 1194 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 1195 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 1196 |
+
|
| 1197 |
+
batch_size, sequence_length, _ = (
|
| 1198 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 1199 |
+
)
|
| 1200 |
+
|
| 1201 |
+
if attention_mask is not None:
|
| 1202 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 1203 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
| 1204 |
+
# (batch, heads, source_length, target_length)
|
| 1205 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
| 1206 |
+
|
| 1207 |
+
if attn.group_norm is not None:
|
| 1208 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 1209 |
+
|
| 1210 |
+
args = () if USE_PEFT_BACKEND else (scale,)
|
| 1211 |
+
query = attn.to_q(hidden_states, *args)
|
| 1212 |
+
|
| 1213 |
+
if encoder_hidden_states is None:
|
| 1214 |
+
encoder_hidden_states = hidden_states
|
| 1215 |
+
elif attn.norm_cross:
|
| 1216 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 1217 |
+
|
| 1218 |
+
key = attn.to_k(encoder_hidden_states, *args)
|
| 1219 |
+
value = attn.to_v(encoder_hidden_states, *args)
|
| 1220 |
+
|
| 1221 |
+
inner_dim = key.shape[-1]
|
| 1222 |
+
head_dim = inner_dim // attn.heads
|
| 1223 |
+
|
| 1224 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 1225 |
+
|
| 1226 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 1227 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 1228 |
+
|
| 1229 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 1230 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 1231 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 1232 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
| 1233 |
+
)
|
| 1234 |
+
|
| 1235 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 1236 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 1237 |
+
|
| 1238 |
+
# linear proj
|
| 1239 |
+
hidden_states = attn.to_out[0](hidden_states, *args)
|
| 1240 |
+
# dropout
|
| 1241 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 1242 |
+
|
| 1243 |
+
if input_ndim == 4:
|
| 1244 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 1245 |
+
|
| 1246 |
+
if attn.residual_connection:
|
| 1247 |
+
hidden_states = hidden_states + residual
|
| 1248 |
+
|
| 1249 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 1250 |
+
|
| 1251 |
+
return hidden_states
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
class CustomDiffusionXFormersAttnProcessor(nn.Module):
|
| 1255 |
+
r"""
|
| 1256 |
+
Processor for implementing memory efficient attention using xFormers for the Custom Diffusion method.
|
| 1257 |
+
|
| 1258 |
+
Args:
|
| 1259 |
+
train_kv (`bool`, defaults to `True`):
|
| 1260 |
+
Whether to newly train the key and value matrices corresponding to the text features.
|
| 1261 |
+
train_q_out (`bool`, defaults to `True`):
|
| 1262 |
+
Whether to newly train query matrices corresponding to the latent image features.
|
| 1263 |
+
hidden_size (`int`, *optional*, defaults to `None`):
|
| 1264 |
+
The hidden size of the attention layer.
|
| 1265 |
+
cross_attention_dim (`int`, *optional*, defaults to `None`):
|
| 1266 |
+
The number of channels in the `encoder_hidden_states`.
|
| 1267 |
+
out_bias (`bool`, defaults to `True`):
|
| 1268 |
+
Whether to include the bias parameter in `train_q_out`.
|
| 1269 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
| 1270 |
+
The dropout probability to use.
|
| 1271 |
+
attention_op (`Callable`, *optional*, defaults to `None`):
|
| 1272 |
+
The base
|
| 1273 |
+
[operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to use
|
| 1274 |
+
as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best operator.
|
| 1275 |
+
"""
|
| 1276 |
+
|
| 1277 |
+
def __init__(
|
| 1278 |
+
self,
|
| 1279 |
+
train_kv: bool = True,
|
| 1280 |
+
train_q_out: bool = False,
|
| 1281 |
+
hidden_size: Optional[int] = None,
|
| 1282 |
+
cross_attention_dim: Optional[int] = None,
|
| 1283 |
+
out_bias: bool = True,
|
| 1284 |
+
dropout: float = 0.0,
|
| 1285 |
+
attention_op: Optional[Callable] = None,
|
| 1286 |
+
):
|
| 1287 |
+
super().__init__()
|
| 1288 |
+
self.train_kv = train_kv
|
| 1289 |
+
self.train_q_out = train_q_out
|
| 1290 |
+
|
| 1291 |
+
self.hidden_size = hidden_size
|
| 1292 |
+
self.cross_attention_dim = cross_attention_dim
|
| 1293 |
+
self.attention_op = attention_op
|
| 1294 |
+
|
| 1295 |
+
# `_custom_diffusion` id for easy serialization and loading.
|
| 1296 |
+
if self.train_kv:
|
| 1297 |
+
self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 1298 |
+
self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 1299 |
+
if self.train_q_out:
|
| 1300 |
+
self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
|
| 1301 |
+
self.to_out_custom_diffusion = nn.ModuleList([])
|
| 1302 |
+
self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
|
| 1303 |
+
self.to_out_custom_diffusion.append(nn.Dropout(dropout))
|
| 1304 |
+
|
| 1305 |
+
def __call__(
|
| 1306 |
+
self,
|
| 1307 |
+
attn: Attention,
|
| 1308 |
+
hidden_states: torch.FloatTensor,
|
| 1309 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1310 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1311 |
+
) -> torch.FloatTensor:
|
| 1312 |
+
batch_size, sequence_length, _ = (
|
| 1313 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 1317 |
+
|
| 1318 |
+
if self.train_q_out:
|
| 1319 |
+
query = self.to_q_custom_diffusion(hidden_states).to(attn.to_q.weight.dtype)
|
| 1320 |
+
else:
|
| 1321 |
+
query = attn.to_q(hidden_states.to(attn.to_q.weight.dtype))
|
| 1322 |
+
|
| 1323 |
+
if encoder_hidden_states is None:
|
| 1324 |
+
crossattn = False
|
| 1325 |
+
encoder_hidden_states = hidden_states
|
| 1326 |
+
else:
|
| 1327 |
+
crossattn = True
|
| 1328 |
+
if attn.norm_cross:
|
| 1329 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 1330 |
+
|
| 1331 |
+
if self.train_kv:
|
| 1332 |
+
key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
|
| 1333 |
+
value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
|
| 1334 |
+
key = key.to(attn.to_q.weight.dtype)
|
| 1335 |
+
value = value.to(attn.to_q.weight.dtype)
|
| 1336 |
+
else:
|
| 1337 |
+
key = attn.to_k(encoder_hidden_states)
|
| 1338 |
+
value = attn.to_v(encoder_hidden_states)
|
| 1339 |
+
|
| 1340 |
+
if crossattn:
|
| 1341 |
+
detach = torch.ones_like(key)
|
| 1342 |
+
detach[:, :1, :] = detach[:, :1, :] * 0.0
|
| 1343 |
+
key = detach * key + (1 - detach) * key.detach()
|
| 1344 |
+
value = detach * value + (1 - detach) * value.detach()
|
| 1345 |
+
|
| 1346 |
+
query = attn.head_to_batch_dim(query).contiguous()
|
| 1347 |
+
key = attn.head_to_batch_dim(key).contiguous()
|
| 1348 |
+
value = attn.head_to_batch_dim(value).contiguous()
|
| 1349 |
+
|
| 1350 |
+
hidden_states = xformers.ops.memory_efficient_attention(
|
| 1351 |
+
query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
|
| 1352 |
+
)
|
| 1353 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 1354 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 1355 |
+
|
| 1356 |
+
if self.train_q_out:
|
| 1357 |
+
# linear proj
|
| 1358 |
+
hidden_states = self.to_out_custom_diffusion[0](hidden_states)
|
| 1359 |
+
# dropout
|
| 1360 |
+
hidden_states = self.to_out_custom_diffusion[1](hidden_states)
|
| 1361 |
+
else:
|
| 1362 |
+
# linear proj
|
| 1363 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 1364 |
+
# dropout
|
| 1365 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 1366 |
+
|
| 1367 |
+
return hidden_states
|
| 1368 |
+
|
| 1369 |
+
|
| 1370 |
+
class CustomDiffusionAttnProcessor2_0(nn.Module):
|
| 1371 |
+
r"""
|
| 1372 |
+
Processor for implementing attention for the Custom Diffusion method using PyTorch 2.0’s memory-efficient scaled
|
| 1373 |
+
dot-product attention.
|
| 1374 |
+
|
| 1375 |
+
Args:
|
| 1376 |
+
train_kv (`bool`, defaults to `True`):
|
| 1377 |
+
Whether to newly train the key and value matrices corresponding to the text features.
|
| 1378 |
+
train_q_out (`bool`, defaults to `True`):
|
| 1379 |
+
Whether to newly train query matrices corresponding to the latent image features.
|
| 1380 |
+
hidden_size (`int`, *optional*, defaults to `None`):
|
| 1381 |
+
The hidden size of the attention layer.
|
| 1382 |
+
cross_attention_dim (`int`, *optional*, defaults to `None`):
|
| 1383 |
+
The number of channels in the `encoder_hidden_states`.
|
| 1384 |
+
out_bias (`bool`, defaults to `True`):
|
| 1385 |
+
Whether to include the bias parameter in `train_q_out`.
|
| 1386 |
+
dropout (`float`, *optional*, defaults to 0.0):
|
| 1387 |
+
The dropout probability to use.
|
| 1388 |
+
"""
|
| 1389 |
+
|
| 1390 |
+
def __init__(
|
| 1391 |
+
self,
|
| 1392 |
+
train_kv: bool = True,
|
| 1393 |
+
train_q_out: bool = True,
|
| 1394 |
+
hidden_size: Optional[int] = None,
|
| 1395 |
+
cross_attention_dim: Optional[int] = None,
|
| 1396 |
+
out_bias: bool = True,
|
| 1397 |
+
dropout: float = 0.0,
|
| 1398 |
+
):
|
| 1399 |
+
super().__init__()
|
| 1400 |
+
self.train_kv = train_kv
|
| 1401 |
+
self.train_q_out = train_q_out
|
| 1402 |
+
|
| 1403 |
+
self.hidden_size = hidden_size
|
| 1404 |
+
self.cross_attention_dim = cross_attention_dim
|
| 1405 |
+
|
| 1406 |
+
# `_custom_diffusion` id for easy serialization and loading.
|
| 1407 |
+
if self.train_kv:
|
| 1408 |
+
self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 1409 |
+
self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 1410 |
+
if self.train_q_out:
|
| 1411 |
+
self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
|
| 1412 |
+
self.to_out_custom_diffusion = nn.ModuleList([])
|
| 1413 |
+
self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
|
| 1414 |
+
self.to_out_custom_diffusion.append(nn.Dropout(dropout))
|
| 1415 |
+
|
| 1416 |
+
def __call__(
|
| 1417 |
+
self,
|
| 1418 |
+
attn: Attention,
|
| 1419 |
+
hidden_states: torch.FloatTensor,
|
| 1420 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1421 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1422 |
+
) -> torch.FloatTensor:
|
| 1423 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 1424 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 1425 |
+
if self.train_q_out:
|
| 1426 |
+
query = self.to_q_custom_diffusion(hidden_states)
|
| 1427 |
+
else:
|
| 1428 |
+
query = attn.to_q(hidden_states)
|
| 1429 |
+
|
| 1430 |
+
if encoder_hidden_states is None:
|
| 1431 |
+
crossattn = False
|
| 1432 |
+
encoder_hidden_states = hidden_states
|
| 1433 |
+
else:
|
| 1434 |
+
crossattn = True
|
| 1435 |
+
if attn.norm_cross:
|
| 1436 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 1437 |
+
|
| 1438 |
+
if self.train_kv:
|
| 1439 |
+
key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
|
| 1440 |
+
value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
|
| 1441 |
+
key = key.to(attn.to_q.weight.dtype)
|
| 1442 |
+
value = value.to(attn.to_q.weight.dtype)
|
| 1443 |
+
|
| 1444 |
+
else:
|
| 1445 |
+
key = attn.to_k(encoder_hidden_states)
|
| 1446 |
+
value = attn.to_v(encoder_hidden_states)
|
| 1447 |
+
|
| 1448 |
+
if crossattn:
|
| 1449 |
+
detach = torch.ones_like(key)
|
| 1450 |
+
detach[:, :1, :] = detach[:, :1, :] * 0.0
|
| 1451 |
+
key = detach * key + (1 - detach) * key.detach()
|
| 1452 |
+
value = detach * value + (1 - detach) * value.detach()
|
| 1453 |
+
|
| 1454 |
+
inner_dim = hidden_states.shape[-1]
|
| 1455 |
+
|
| 1456 |
+
head_dim = inner_dim // attn.heads
|
| 1457 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 1458 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 1459 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 1460 |
+
|
| 1461 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 1462 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 1463 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 1464 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
| 1465 |
+
)
|
| 1466 |
+
|
| 1467 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 1468 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 1469 |
+
|
| 1470 |
+
if self.train_q_out:
|
| 1471 |
+
# linear proj
|
| 1472 |
+
hidden_states = self.to_out_custom_diffusion[0](hidden_states)
|
| 1473 |
+
# dropout
|
| 1474 |
+
hidden_states = self.to_out_custom_diffusion[1](hidden_states)
|
| 1475 |
+
else:
|
| 1476 |
+
# linear proj
|
| 1477 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 1478 |
+
# dropout
|
| 1479 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 1480 |
+
|
| 1481 |
+
return hidden_states
|
| 1482 |
+
|
| 1483 |
+
|
| 1484 |
+
class SlicedAttnProcessor:
|
| 1485 |
+
r"""
|
| 1486 |
+
Processor for implementing sliced attention.
|
| 1487 |
+
|
| 1488 |
+
Args:
|
| 1489 |
+
slice_size (`int`, *optional*):
|
| 1490 |
+
The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
|
| 1491 |
+
`attention_head_dim` must be a multiple of the `slice_size`.
|
| 1492 |
+
"""
|
| 1493 |
+
|
| 1494 |
+
def __init__(self, slice_size: int):
|
| 1495 |
+
self.slice_size = slice_size
|
| 1496 |
+
|
| 1497 |
+
def __call__(
|
| 1498 |
+
self,
|
| 1499 |
+
attn: Attention,
|
| 1500 |
+
hidden_states: torch.FloatTensor,
|
| 1501 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1502 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1503 |
+
) -> torch.FloatTensor:
|
| 1504 |
+
residual = hidden_states
|
| 1505 |
+
|
| 1506 |
+
input_ndim = hidden_states.ndim
|
| 1507 |
+
|
| 1508 |
+
if input_ndim == 4:
|
| 1509 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 1510 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 1511 |
+
|
| 1512 |
+
batch_size, sequence_length, _ = (
|
| 1513 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 1514 |
+
)
|
| 1515 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 1516 |
+
|
| 1517 |
+
if attn.group_norm is not None:
|
| 1518 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 1519 |
+
|
| 1520 |
+
query = attn.to_q(hidden_states)
|
| 1521 |
+
dim = query.shape[-1]
|
| 1522 |
+
query = attn.head_to_batch_dim(query)
|
| 1523 |
+
|
| 1524 |
+
if encoder_hidden_states is None:
|
| 1525 |
+
encoder_hidden_states = hidden_states
|
| 1526 |
+
elif attn.norm_cross:
|
| 1527 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 1528 |
+
|
| 1529 |
+
key = attn.to_k(encoder_hidden_states)
|
| 1530 |
+
value = attn.to_v(encoder_hidden_states)
|
| 1531 |
+
key = attn.head_to_batch_dim(key)
|
| 1532 |
+
value = attn.head_to_batch_dim(value)
|
| 1533 |
+
|
| 1534 |
+
batch_size_attention, query_tokens, _ = query.shape
|
| 1535 |
+
hidden_states = torch.zeros(
|
| 1536 |
+
(batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype
|
| 1537 |
+
)
|
| 1538 |
+
|
| 1539 |
+
for i in range(batch_size_attention // self.slice_size):
|
| 1540 |
+
start_idx = i * self.slice_size
|
| 1541 |
+
end_idx = (i + 1) * self.slice_size
|
| 1542 |
+
|
| 1543 |
+
query_slice = query[start_idx:end_idx]
|
| 1544 |
+
key_slice = key[start_idx:end_idx]
|
| 1545 |
+
attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None
|
| 1546 |
+
|
| 1547 |
+
attn_slice = attn.get_attention_scores(query_slice, key_slice, attn_mask_slice)
|
| 1548 |
+
|
| 1549 |
+
attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx])
|
| 1550 |
+
|
| 1551 |
+
hidden_states[start_idx:end_idx] = attn_slice
|
| 1552 |
+
|
| 1553 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 1554 |
+
|
| 1555 |
+
# linear proj
|
| 1556 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 1557 |
+
# dropout
|
| 1558 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 1559 |
+
|
| 1560 |
+
if input_ndim == 4:
|
| 1561 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 1562 |
+
|
| 1563 |
+
if attn.residual_connection:
|
| 1564 |
+
hidden_states = hidden_states + residual
|
| 1565 |
+
|
| 1566 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 1567 |
+
|
| 1568 |
+
return hidden_states
|
| 1569 |
+
|
| 1570 |
+
|
| 1571 |
+
class SlicedAttnAddedKVProcessor:
|
| 1572 |
+
r"""
|
| 1573 |
+
Processor for implementing sliced attention with extra learnable key and value matrices for the text encoder.
|
| 1574 |
+
|
| 1575 |
+
Args:
|
| 1576 |
+
slice_size (`int`, *optional*):
|
| 1577 |
+
The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
|
| 1578 |
+
`attention_head_dim` must be a multiple of the `slice_size`.
|
| 1579 |
+
"""
|
| 1580 |
+
|
| 1581 |
+
def __init__(self, slice_size):
|
| 1582 |
+
self.slice_size = slice_size
|
| 1583 |
+
|
| 1584 |
+
def __call__(
|
| 1585 |
+
self,
|
| 1586 |
+
attn: "Attention",
|
| 1587 |
+
hidden_states: torch.FloatTensor,
|
| 1588 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 1589 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 1590 |
+
temb: Optional[torch.FloatTensor] = None,
|
| 1591 |
+
) -> torch.FloatTensor:
|
| 1592 |
+
residual = hidden_states
|
| 1593 |
+
|
| 1594 |
+
if attn.spatial_norm is not None:
|
| 1595 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 1596 |
+
|
| 1597 |
+
hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
|
| 1598 |
+
|
| 1599 |
+
batch_size, sequence_length, _ = hidden_states.shape
|
| 1600 |
+
|
| 1601 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 1602 |
+
|
| 1603 |
+
if encoder_hidden_states is None:
|
| 1604 |
+
encoder_hidden_states = hidden_states
|
| 1605 |
+
elif attn.norm_cross:
|
| 1606 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 1607 |
+
|
| 1608 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 1609 |
+
|
| 1610 |
+
query = attn.to_q(hidden_states)
|
| 1611 |
+
dim = query.shape[-1]
|
| 1612 |
+
query = attn.head_to_batch_dim(query)
|
| 1613 |
+
|
| 1614 |
+
encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
|
| 1615 |
+
encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
|
| 1616 |
+
|
| 1617 |
+
encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
|
| 1618 |
+
encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
|
| 1619 |
+
|
| 1620 |
+
if not attn.only_cross_attention:
|
| 1621 |
+
key = attn.to_k(hidden_states)
|
| 1622 |
+
value = attn.to_v(hidden_states)
|
| 1623 |
+
key = attn.head_to_batch_dim(key)
|
| 1624 |
+
value = attn.head_to_batch_dim(value)
|
| 1625 |
+
key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
|
| 1626 |
+
value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
|
| 1627 |
+
else:
|
| 1628 |
+
key = encoder_hidden_states_key_proj
|
| 1629 |
+
value = encoder_hidden_states_value_proj
|
| 1630 |
+
|
| 1631 |
+
batch_size_attention, query_tokens, _ = query.shape
|
| 1632 |
+
hidden_states = torch.zeros(
|
| 1633 |
+
(batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype
|
| 1634 |
+
)
|
| 1635 |
+
|
| 1636 |
+
for i in range(batch_size_attention // self.slice_size):
|
| 1637 |
+
start_idx = i * self.slice_size
|
| 1638 |
+
end_idx = (i + 1) * self.slice_size
|
| 1639 |
+
|
| 1640 |
+
query_slice = query[start_idx:end_idx]
|
| 1641 |
+
key_slice = key[start_idx:end_idx]
|
| 1642 |
+
attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None
|
| 1643 |
+
|
| 1644 |
+
attn_slice = attn.get_attention_scores(query_slice, key_slice, attn_mask_slice)
|
| 1645 |
+
|
| 1646 |
+
attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx])
|
| 1647 |
+
|
| 1648 |
+
hidden_states[start_idx:end_idx] = attn_slice
|
| 1649 |
+
|
| 1650 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 1651 |
+
|
| 1652 |
+
# linear proj
|
| 1653 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 1654 |
+
# dropout
|
| 1655 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 1656 |
+
|
| 1657 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
|
| 1658 |
+
hidden_states = hidden_states + residual
|
| 1659 |
+
|
| 1660 |
+
return hidden_states
|
| 1661 |
+
|
| 1662 |
+
|
| 1663 |
+
class SpatialNorm(nn.Module):
|
| 1664 |
+
"""
|
| 1665 |
+
Spatially conditioned normalization as defined in https://arxiv.org/abs/2209.09002.
|
| 1666 |
+
|
| 1667 |
+
Args:
|
| 1668 |
+
f_channels (`int`):
|
| 1669 |
+
The number of channels for input to group normalization layer, and output of the spatial norm layer.
|
| 1670 |
+
zq_channels (`int`):
|
| 1671 |
+
The number of channels for the quantized vector as described in the paper.
|
| 1672 |
+
"""
|
| 1673 |
+
|
| 1674 |
+
def __init__(
|
| 1675 |
+
self,
|
| 1676 |
+
f_channels: int,
|
| 1677 |
+
zq_channels: int,
|
| 1678 |
+
):
|
| 1679 |
+
super().__init__()
|
| 1680 |
+
self.norm_layer = nn.GroupNorm(num_channels=f_channels, num_groups=32, eps=1e-6, affine=True)
|
| 1681 |
+
self.conv_y = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
|
| 1682 |
+
self.conv_b = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
|
| 1683 |
+
|
| 1684 |
+
def forward(self, f: torch.FloatTensor, zq: torch.FloatTensor) -> torch.FloatTensor:
|
| 1685 |
+
f_size = f.shape[-2:]
|
| 1686 |
+
zq = F.interpolate(zq, size=f_size, mode="nearest")
|
| 1687 |
+
norm_f = self.norm_layer(f)
|
| 1688 |
+
new_f = norm_f * self.conv_y(zq) + self.conv_b(zq)
|
| 1689 |
+
return new_f
|
| 1690 |
+
|
| 1691 |
+
|
| 1692 |
+
## Deprecated
|
| 1693 |
+
class LoRAAttnProcessor(nn.Module):
|
| 1694 |
+
r"""
|
| 1695 |
+
Processor for implementing the LoRA attention mechanism.
|
| 1696 |
+
|
| 1697 |
+
Args:
|
| 1698 |
+
hidden_size (`int`, *optional*):
|
| 1699 |
+
The hidden size of the attention layer.
|
| 1700 |
+
cross_attention_dim (`int`, *optional*):
|
| 1701 |
+
The number of channels in the `encoder_hidden_states`.
|
| 1702 |
+
rank (`int`, defaults to 4):
|
| 1703 |
+
The dimension of the LoRA update matrices.
|
| 1704 |
+
network_alpha (`int`, *optional*):
|
| 1705 |
+
Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
|
| 1706 |
+
kwargs (`dict`):
|
| 1707 |
+
Additional keyword arguments to pass to the `LoRALinearLayer` layers.
|
| 1708 |
+
"""
|
| 1709 |
+
|
| 1710 |
+
def __init__(
|
| 1711 |
+
self,
|
| 1712 |
+
hidden_size: int,
|
| 1713 |
+
cross_attention_dim: Optional[int] = None,
|
| 1714 |
+
rank: int = 4,
|
| 1715 |
+
network_alpha: Optional[int] = None,
|
| 1716 |
+
**kwargs,
|
| 1717 |
+
):
|
| 1718 |
+
super().__init__()
|
| 1719 |
+
|
| 1720 |
+
self.hidden_size = hidden_size
|
| 1721 |
+
self.cross_attention_dim = cross_attention_dim
|
| 1722 |
+
self.rank = rank
|
| 1723 |
+
|
| 1724 |
+
q_rank = kwargs.pop("q_rank", None)
|
| 1725 |
+
q_hidden_size = kwargs.pop("q_hidden_size", None)
|
| 1726 |
+
q_rank = q_rank if q_rank is not None else rank
|
| 1727 |
+
q_hidden_size = q_hidden_size if q_hidden_size is not None else hidden_size
|
| 1728 |
+
|
| 1729 |
+
v_rank = kwargs.pop("v_rank", None)
|
| 1730 |
+
v_hidden_size = kwargs.pop("v_hidden_size", None)
|
| 1731 |
+
v_rank = v_rank if v_rank is not None else rank
|
| 1732 |
+
v_hidden_size = v_hidden_size if v_hidden_size is not None else hidden_size
|
| 1733 |
+
|
| 1734 |
+
out_rank = kwargs.pop("out_rank", None)
|
| 1735 |
+
out_hidden_size = kwargs.pop("out_hidden_size", None)
|
| 1736 |
+
out_rank = out_rank if out_rank is not None else rank
|
| 1737 |
+
out_hidden_size = out_hidden_size if out_hidden_size is not None else hidden_size
|
| 1738 |
+
|
| 1739 |
+
self.to_q_lora = LoRALinearLayer(q_hidden_size, q_hidden_size, q_rank, network_alpha)
|
| 1740 |
+
self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
| 1741 |
+
self.to_v_lora = LoRALinearLayer(cross_attention_dim or v_hidden_size, v_hidden_size, v_rank, network_alpha)
|
| 1742 |
+
self.to_out_lora = LoRALinearLayer(out_hidden_size, out_hidden_size, out_rank, network_alpha)
|
| 1743 |
+
|
| 1744 |
+
def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
|
| 1745 |
+
self_cls_name = self.__class__.__name__
|
| 1746 |
+
deprecate(
|
| 1747 |
+
self_cls_name,
|
| 1748 |
+
"0.26.0",
|
| 1749 |
+
(
|
| 1750 |
+
f"Make sure use {self_cls_name[4:]} instead by setting"
|
| 1751 |
+
"LoRA layers to `self.{to_q,to_k,to_v,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
|
| 1752 |
+
" `LoraLoaderMixin.load_lora_weights`"
|
| 1753 |
+
),
|
| 1754 |
+
)
|
| 1755 |
+
attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
|
| 1756 |
+
attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
|
| 1757 |
+
attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
|
| 1758 |
+
attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
|
| 1759 |
+
|
| 1760 |
+
attn._modules.pop("processor")
|
| 1761 |
+
attn.processor = AttnProcessor()
|
| 1762 |
+
return attn.processor(attn, hidden_states, *args, **kwargs)
|
| 1763 |
+
|
| 1764 |
+
|
| 1765 |
+
class LoRAAttnProcessor2_0(nn.Module):
|
| 1766 |
+
r"""
|
| 1767 |
+
Processor for implementing the LoRA attention mechanism using PyTorch 2.0's memory-efficient scaled dot-product
|
| 1768 |
+
attention.
|
| 1769 |
+
|
| 1770 |
+
Args:
|
| 1771 |
+
hidden_size (`int`):
|
| 1772 |
+
The hidden size of the attention layer.
|
| 1773 |
+
cross_attention_dim (`int`, *optional*):
|
| 1774 |
+
The number of channels in the `encoder_hidden_states`.
|
| 1775 |
+
rank (`int`, defaults to 4):
|
| 1776 |
+
The dimension of the LoRA update matrices.
|
| 1777 |
+
network_alpha (`int`, *optional*):
|
| 1778 |
+
Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
|
| 1779 |
+
kwargs (`dict`):
|
| 1780 |
+
Additional keyword arguments to pass to the `LoRALinearLayer` layers.
|
| 1781 |
+
"""
|
| 1782 |
+
|
| 1783 |
+
def __init__(
|
| 1784 |
+
self,
|
| 1785 |
+
hidden_size: int,
|
| 1786 |
+
cross_attention_dim: Optional[int] = None,
|
| 1787 |
+
rank: int = 4,
|
| 1788 |
+
network_alpha: Optional[int] = None,
|
| 1789 |
+
**kwargs,
|
| 1790 |
+
):
|
| 1791 |
+
super().__init__()
|
| 1792 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 1793 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 1794 |
+
|
| 1795 |
+
self.hidden_size = hidden_size
|
| 1796 |
+
self.cross_attention_dim = cross_attention_dim
|
| 1797 |
+
self.rank = rank
|
| 1798 |
+
|
| 1799 |
+
q_rank = kwargs.pop("q_rank", None)
|
| 1800 |
+
q_hidden_size = kwargs.pop("q_hidden_size", None)
|
| 1801 |
+
q_rank = q_rank if q_rank is not None else rank
|
| 1802 |
+
q_hidden_size = q_hidden_size if q_hidden_size is not None else hidden_size
|
| 1803 |
+
|
| 1804 |
+
v_rank = kwargs.pop("v_rank", None)
|
| 1805 |
+
v_hidden_size = kwargs.pop("v_hidden_size", None)
|
| 1806 |
+
v_rank = v_rank if v_rank is not None else rank
|
| 1807 |
+
v_hidden_size = v_hidden_size if v_hidden_size is not None else hidden_size
|
| 1808 |
+
|
| 1809 |
+
out_rank = kwargs.pop("out_rank", None)
|
| 1810 |
+
out_hidden_size = kwargs.pop("out_hidden_size", None)
|
| 1811 |
+
out_rank = out_rank if out_rank is not None else rank
|
| 1812 |
+
out_hidden_size = out_hidden_size if out_hidden_size is not None else hidden_size
|
| 1813 |
+
|
| 1814 |
+
self.to_q_lora = LoRALinearLayer(q_hidden_size, q_hidden_size, q_rank, network_alpha)
|
| 1815 |
+
self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
| 1816 |
+
self.to_v_lora = LoRALinearLayer(cross_attention_dim or v_hidden_size, v_hidden_size, v_rank, network_alpha)
|
| 1817 |
+
self.to_out_lora = LoRALinearLayer(out_hidden_size, out_hidden_size, out_rank, network_alpha)
|
| 1818 |
+
|
| 1819 |
+
def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
|
| 1820 |
+
self_cls_name = self.__class__.__name__
|
| 1821 |
+
deprecate(
|
| 1822 |
+
self_cls_name,
|
| 1823 |
+
"0.26.0",
|
| 1824 |
+
(
|
| 1825 |
+
f"Make sure use {self_cls_name[4:]} instead by setting"
|
| 1826 |
+
"LoRA layers to `self.{to_q,to_k,to_v,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
|
| 1827 |
+
" `LoraLoaderMixin.load_lora_weights`"
|
| 1828 |
+
),
|
| 1829 |
+
)
|
| 1830 |
+
attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
|
| 1831 |
+
attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
|
| 1832 |
+
attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
|
| 1833 |
+
attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
|
| 1834 |
+
|
| 1835 |
+
attn._modules.pop("processor")
|
| 1836 |
+
attn.processor = AttnProcessor2_0()
|
| 1837 |
+
return attn.processor(attn, hidden_states, *args, **kwargs)
|
| 1838 |
+
|
| 1839 |
+
|
| 1840 |
+
class LoRAXFormersAttnProcessor(nn.Module):
|
| 1841 |
+
r"""
|
| 1842 |
+
Processor for implementing the LoRA attention mechanism with memory efficient attention using xFormers.
|
| 1843 |
+
|
| 1844 |
+
Args:
|
| 1845 |
+
hidden_size (`int`, *optional*):
|
| 1846 |
+
The hidden size of the attention layer.
|
| 1847 |
+
cross_attention_dim (`int`, *optional*):
|
| 1848 |
+
The number of channels in the `encoder_hidden_states`.
|
| 1849 |
+
rank (`int`, defaults to 4):
|
| 1850 |
+
The dimension of the LoRA update matrices.
|
| 1851 |
+
attention_op (`Callable`, *optional*, defaults to `None`):
|
| 1852 |
+
The base
|
| 1853 |
+
[operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
|
| 1854 |
+
use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
|
| 1855 |
+
operator.
|
| 1856 |
+
network_alpha (`int`, *optional*):
|
| 1857 |
+
Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
|
| 1858 |
+
kwargs (`dict`):
|
| 1859 |
+
Additional keyword arguments to pass to the `LoRALinearLayer` layers.
|
| 1860 |
+
"""
|
| 1861 |
+
|
| 1862 |
+
def __init__(
|
| 1863 |
+
self,
|
| 1864 |
+
hidden_size: int,
|
| 1865 |
+
cross_attention_dim: int,
|
| 1866 |
+
rank: int = 4,
|
| 1867 |
+
attention_op: Optional[Callable] = None,
|
| 1868 |
+
network_alpha: Optional[int] = None,
|
| 1869 |
+
**kwargs,
|
| 1870 |
+
):
|
| 1871 |
+
super().__init__()
|
| 1872 |
+
|
| 1873 |
+
self.hidden_size = hidden_size
|
| 1874 |
+
self.cross_attention_dim = cross_attention_dim
|
| 1875 |
+
self.rank = rank
|
| 1876 |
+
self.attention_op = attention_op
|
| 1877 |
+
|
| 1878 |
+
q_rank = kwargs.pop("q_rank", None)
|
| 1879 |
+
q_hidden_size = kwargs.pop("q_hidden_size", None)
|
| 1880 |
+
q_rank = q_rank if q_rank is not None else rank
|
| 1881 |
+
q_hidden_size = q_hidden_size if q_hidden_size is not None else hidden_size
|
| 1882 |
+
|
| 1883 |
+
v_rank = kwargs.pop("v_rank", None)
|
| 1884 |
+
v_hidden_size = kwargs.pop("v_hidden_size", None)
|
| 1885 |
+
v_rank = v_rank if v_rank is not None else rank
|
| 1886 |
+
v_hidden_size = v_hidden_size if v_hidden_size is not None else hidden_size
|
| 1887 |
+
|
| 1888 |
+
out_rank = kwargs.pop("out_rank", None)
|
| 1889 |
+
out_hidden_size = kwargs.pop("out_hidden_size", None)
|
| 1890 |
+
out_rank = out_rank if out_rank is not None else rank
|
| 1891 |
+
out_hidden_size = out_hidden_size if out_hidden_size is not None else hidden_size
|
| 1892 |
+
|
| 1893 |
+
self.to_q_lora = LoRALinearLayer(q_hidden_size, q_hidden_size, q_rank, network_alpha)
|
| 1894 |
+
self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
| 1895 |
+
self.to_v_lora = LoRALinearLayer(cross_attention_dim or v_hidden_size, v_hidden_size, v_rank, network_alpha)
|
| 1896 |
+
self.to_out_lora = LoRALinearLayer(out_hidden_size, out_hidden_size, out_rank, network_alpha)
|
| 1897 |
+
|
| 1898 |
+
def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
|
| 1899 |
+
self_cls_name = self.__class__.__name__
|
| 1900 |
+
deprecate(
|
| 1901 |
+
self_cls_name,
|
| 1902 |
+
"0.26.0",
|
| 1903 |
+
(
|
| 1904 |
+
f"Make sure use {self_cls_name[4:]} instead by setting"
|
| 1905 |
+
"LoRA layers to `self.{to_q,to_k,to_v,add_k_proj,add_v_proj,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
|
| 1906 |
+
" `LoraLoaderMixin.load_lora_weights`"
|
| 1907 |
+
),
|
| 1908 |
+
)
|
| 1909 |
+
attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
|
| 1910 |
+
attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
|
| 1911 |
+
attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
|
| 1912 |
+
attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
|
| 1913 |
+
|
| 1914 |
+
attn._modules.pop("processor")
|
| 1915 |
+
attn.processor = XFormersAttnProcessor()
|
| 1916 |
+
return attn.processor(attn, hidden_states, *args, **kwargs)
|
| 1917 |
+
|
| 1918 |
+
|
| 1919 |
+
class LoRAAttnAddedKVProcessor(nn.Module):
|
| 1920 |
+
r"""
|
| 1921 |
+
Processor for implementing the LoRA attention mechanism with extra learnable key and value matrices for the text
|
| 1922 |
+
encoder.
|
| 1923 |
+
|
| 1924 |
+
Args:
|
| 1925 |
+
hidden_size (`int`, *optional*):
|
| 1926 |
+
The hidden size of the attention layer.
|
| 1927 |
+
cross_attention_dim (`int`, *optional*, defaults to `None`):
|
| 1928 |
+
The number of channels in the `encoder_hidden_states`.
|
| 1929 |
+
rank (`int`, defaults to 4):
|
| 1930 |
+
The dimension of the LoRA update matrices.
|
| 1931 |
+
network_alpha (`int`, *optional*):
|
| 1932 |
+
Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
|
| 1933 |
+
kwargs (`dict`):
|
| 1934 |
+
Additional keyword arguments to pass to the `LoRALinearLayer` layers.
|
| 1935 |
+
"""
|
| 1936 |
+
|
| 1937 |
+
def __init__(
|
| 1938 |
+
self,
|
| 1939 |
+
hidden_size: int,
|
| 1940 |
+
cross_attention_dim: Optional[int] = None,
|
| 1941 |
+
rank: int = 4,
|
| 1942 |
+
network_alpha: Optional[int] = None,
|
| 1943 |
+
):
|
| 1944 |
+
super().__init__()
|
| 1945 |
+
|
| 1946 |
+
self.hidden_size = hidden_size
|
| 1947 |
+
self.cross_attention_dim = cross_attention_dim
|
| 1948 |
+
self.rank = rank
|
| 1949 |
+
|
| 1950 |
+
self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
| 1951 |
+
self.add_k_proj_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
| 1952 |
+
self.add_v_proj_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
| 1953 |
+
self.to_k_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
| 1954 |
+
self.to_v_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
| 1955 |
+
self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
| 1956 |
+
|
| 1957 |
+
def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
|
| 1958 |
+
self_cls_name = self.__class__.__name__
|
| 1959 |
+
deprecate(
|
| 1960 |
+
self_cls_name,
|
| 1961 |
+
"0.26.0",
|
| 1962 |
+
(
|
| 1963 |
+
f"Make sure use {self_cls_name[4:]} instead by setting"
|
| 1964 |
+
"LoRA layers to `self.{to_q,to_k,to_v,add_k_proj,add_v_proj,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
|
| 1965 |
+
" `LoraLoaderMixin.load_lora_weights`"
|
| 1966 |
+
),
|
| 1967 |
+
)
|
| 1968 |
+
attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
|
| 1969 |
+
attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
|
| 1970 |
+
attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
|
| 1971 |
+
attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
|
| 1972 |
+
|
| 1973 |
+
attn._modules.pop("processor")
|
| 1974 |
+
attn.processor = AttnAddedKVProcessor()
|
| 1975 |
+
return attn.processor(attn, hidden_states, *args, **kwargs)
|
| 1976 |
+
|
| 1977 |
+
|
| 1978 |
+
class IPAdapterAttnProcessor(nn.Module):
|
| 1979 |
+
r"""
|
| 1980 |
+
Attention processor for IP-Adapater.
|
| 1981 |
+
|
| 1982 |
+
Args:
|
| 1983 |
+
hidden_size (`int`):
|
| 1984 |
+
The hidden size of the attention layer.
|
| 1985 |
+
cross_attention_dim (`int`):
|
| 1986 |
+
The number of channels in the `encoder_hidden_states`.
|
| 1987 |
+
num_tokens (`int`, defaults to 4):
|
| 1988 |
+
The context length of the image features.
|
| 1989 |
+
scale (`float`, defaults to 1.0):
|
| 1990 |
+
the weight scale of image prompt.
|
| 1991 |
+
"""
|
| 1992 |
+
|
| 1993 |
+
def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=4, scale=1.0):
|
| 1994 |
+
super().__init__()
|
| 1995 |
+
|
| 1996 |
+
self.hidden_size = hidden_size
|
| 1997 |
+
self.cross_attention_dim = cross_attention_dim
|
| 1998 |
+
self.num_tokens = num_tokens
|
| 1999 |
+
self.scale = scale
|
| 2000 |
+
|
| 2001 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 2002 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 2003 |
+
|
| 2004 |
+
def __call__(
|
| 2005 |
+
self,
|
| 2006 |
+
attn,
|
| 2007 |
+
hidden_states,
|
| 2008 |
+
encoder_hidden_states=None,
|
| 2009 |
+
attention_mask=None,
|
| 2010 |
+
temb=None,
|
| 2011 |
+
scale=1.0,
|
| 2012 |
+
):
|
| 2013 |
+
if scale != 1.0:
|
| 2014 |
+
logger.warning("`scale` of IPAttnProcessor should be set with `set_ip_adapter_scale`.")
|
| 2015 |
+
residual = hidden_states
|
| 2016 |
+
|
| 2017 |
+
if attn.spatial_norm is not None:
|
| 2018 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 2019 |
+
|
| 2020 |
+
input_ndim = hidden_states.ndim
|
| 2021 |
+
|
| 2022 |
+
if input_ndim == 4:
|
| 2023 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 2024 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 2025 |
+
|
| 2026 |
+
batch_size, sequence_length, _ = (
|
| 2027 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 2028 |
+
)
|
| 2029 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 2030 |
+
|
| 2031 |
+
if attn.group_norm is not None:
|
| 2032 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 2033 |
+
|
| 2034 |
+
query = attn.to_q(hidden_states)
|
| 2035 |
+
|
| 2036 |
+
if encoder_hidden_states is None:
|
| 2037 |
+
encoder_hidden_states = hidden_states
|
| 2038 |
+
elif attn.norm_cross:
|
| 2039 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 2040 |
+
|
| 2041 |
+
# split hidden states
|
| 2042 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
| 2043 |
+
encoder_hidden_states, ip_hidden_states = (
|
| 2044 |
+
encoder_hidden_states[:, :end_pos, :],
|
| 2045 |
+
encoder_hidden_states[:, end_pos:, :],
|
| 2046 |
+
)
|
| 2047 |
+
|
| 2048 |
+
key = attn.to_k(encoder_hidden_states)
|
| 2049 |
+
value = attn.to_v(encoder_hidden_states)
|
| 2050 |
+
|
| 2051 |
+
query = attn.head_to_batch_dim(query)
|
| 2052 |
+
key = attn.head_to_batch_dim(key)
|
| 2053 |
+
value = attn.head_to_batch_dim(value)
|
| 2054 |
+
|
| 2055 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 2056 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 2057 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 2058 |
+
|
| 2059 |
+
# for ip-adapter
|
| 2060 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
| 2061 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
| 2062 |
+
|
| 2063 |
+
ip_key = attn.head_to_batch_dim(ip_key)
|
| 2064 |
+
ip_value = attn.head_to_batch_dim(ip_value)
|
| 2065 |
+
|
| 2066 |
+
ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
|
| 2067 |
+
ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
|
| 2068 |
+
ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
|
| 2069 |
+
|
| 2070 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
| 2071 |
+
|
| 2072 |
+
# linear proj
|
| 2073 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 2074 |
+
# dropout
|
| 2075 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 2076 |
+
|
| 2077 |
+
if input_ndim == 4:
|
| 2078 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 2079 |
+
|
| 2080 |
+
if attn.residual_connection:
|
| 2081 |
+
hidden_states = hidden_states + residual
|
| 2082 |
+
|
| 2083 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 2084 |
+
|
| 2085 |
+
return hidden_states
|
| 2086 |
+
|
| 2087 |
+
|
| 2088 |
+
class IPAdapterAttnProcessor2_0(torch.nn.Module):
|
| 2089 |
+
r"""
|
| 2090 |
+
Attention processor for IP-Adapater for PyTorch 2.0.
|
| 2091 |
+
|
| 2092 |
+
Args:
|
| 2093 |
+
hidden_size (`int`):
|
| 2094 |
+
The hidden size of the attention layer.
|
| 2095 |
+
cross_attention_dim (`int`):
|
| 2096 |
+
The number of channels in the `encoder_hidden_states`.
|
| 2097 |
+
num_tokens (`int`, defaults to 4):
|
| 2098 |
+
The context length of the image features.
|
| 2099 |
+
scale (`float`, defaults to 1.0):
|
| 2100 |
+
the weight scale of image prompt.
|
| 2101 |
+
"""
|
| 2102 |
+
|
| 2103 |
+
def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=4, scale=1.0):
|
| 2104 |
+
super().__init__()
|
| 2105 |
+
|
| 2106 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 2107 |
+
raise ImportError(
|
| 2108 |
+
f"{self.__class__.__name__} requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
|
| 2109 |
+
)
|
| 2110 |
+
|
| 2111 |
+
self.hidden_size = hidden_size
|
| 2112 |
+
self.cross_attention_dim = cross_attention_dim
|
| 2113 |
+
self.num_tokens = num_tokens
|
| 2114 |
+
self.scale = scale
|
| 2115 |
+
|
| 2116 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 2117 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 2118 |
+
|
| 2119 |
+
def __call__(
|
| 2120 |
+
self,
|
| 2121 |
+
attn,
|
| 2122 |
+
hidden_states,
|
| 2123 |
+
encoder_hidden_states=None,
|
| 2124 |
+
attention_mask=None,
|
| 2125 |
+
temb=None,
|
| 2126 |
+
scale=1.0,
|
| 2127 |
+
):
|
| 2128 |
+
if scale != 1.0:
|
| 2129 |
+
logger.warning("`scale` of IPAttnProcessor should be set by `set_ip_adapter_scale`.")
|
| 2130 |
+
residual = hidden_states
|
| 2131 |
+
|
| 2132 |
+
if attn.spatial_norm is not None:
|
| 2133 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 2134 |
+
|
| 2135 |
+
input_ndim = hidden_states.ndim
|
| 2136 |
+
|
| 2137 |
+
if input_ndim == 4:
|
| 2138 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 2139 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 2140 |
+
|
| 2141 |
+
batch_size, sequence_length, _ = (
|
| 2142 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 2143 |
+
)
|
| 2144 |
+
|
| 2145 |
+
if attention_mask is not None:
|
| 2146 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 2147 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
| 2148 |
+
# (batch, heads, source_length, target_length)
|
| 2149 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
| 2150 |
+
|
| 2151 |
+
if attn.group_norm is not None:
|
| 2152 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 2153 |
+
|
| 2154 |
+
query = attn.to_q(hidden_states)
|
| 2155 |
+
|
| 2156 |
+
if encoder_hidden_states is None:
|
| 2157 |
+
encoder_hidden_states = hidden_states
|
| 2158 |
+
elif attn.norm_cross:
|
| 2159 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 2160 |
+
|
| 2161 |
+
# split hidden states
|
| 2162 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
| 2163 |
+
encoder_hidden_states, ip_hidden_states = (
|
| 2164 |
+
encoder_hidden_states[:, :end_pos, :],
|
| 2165 |
+
encoder_hidden_states[:, end_pos:, :],
|
| 2166 |
+
)
|
| 2167 |
+
|
| 2168 |
+
key = attn.to_k(encoder_hidden_states)
|
| 2169 |
+
value = attn.to_v(encoder_hidden_states)
|
| 2170 |
+
|
| 2171 |
+
inner_dim = key.shape[-1]
|
| 2172 |
+
head_dim = inner_dim // attn.heads
|
| 2173 |
+
|
| 2174 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 2175 |
+
|
| 2176 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 2177 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 2178 |
+
|
| 2179 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 2180 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 2181 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 2182 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
| 2183 |
+
)
|
| 2184 |
+
|
| 2185 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 2186 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 2187 |
+
|
| 2188 |
+
# for ip-adapter
|
| 2189 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
| 2190 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
| 2191 |
+
|
| 2192 |
+
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 2193 |
+
ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 2194 |
+
|
| 2195 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 2196 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 2197 |
+
ip_hidden_states = F.scaled_dot_product_attention(
|
| 2198 |
+
query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
|
| 2199 |
+
)
|
| 2200 |
+
|
| 2201 |
+
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 2202 |
+
ip_hidden_states = ip_hidden_states.to(query.dtype)
|
| 2203 |
+
|
| 2204 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
| 2205 |
+
|
| 2206 |
+
# linear proj
|
| 2207 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 2208 |
+
# dropout
|
| 2209 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 2210 |
+
|
| 2211 |
+
if input_ndim == 4:
|
| 2212 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 2213 |
+
|
| 2214 |
+
if attn.residual_connection:
|
| 2215 |
+
hidden_states = hidden_states + residual
|
| 2216 |
+
|
| 2217 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 2218 |
+
|
| 2219 |
+
return hidden_states
|
| 2220 |
+
|
| 2221 |
+
|
| 2222 |
+
# TODO(Yiyi): This class should not exist, we can replace it with a normal attention processor I believe
|
| 2223 |
+
# this way torch.compile and co. will work as well
|
| 2224 |
+
class Kandi3AttnProcessor:
|
| 2225 |
+
r"""
|
| 2226 |
+
Default kandinsky3 proccesor for performing attention-related computations.
|
| 2227 |
+
"""
|
| 2228 |
+
|
| 2229 |
+
@staticmethod
|
| 2230 |
+
def _reshape(hid_states, h):
|
| 2231 |
+
b, n, f = hid_states.shape
|
| 2232 |
+
d = f // h
|
| 2233 |
+
return hid_states.unsqueeze(-1).reshape(b, n, h, d).permute(0, 2, 1, 3)
|
| 2234 |
+
|
| 2235 |
+
def __call__(
|
| 2236 |
+
self,
|
| 2237 |
+
attn,
|
| 2238 |
+
x,
|
| 2239 |
+
context,
|
| 2240 |
+
context_mask=None,
|
| 2241 |
+
):
|
| 2242 |
+
query = self._reshape(attn.to_q(x), h=attn.num_heads)
|
| 2243 |
+
key = self._reshape(attn.to_k(context), h=attn.num_heads)
|
| 2244 |
+
value = self._reshape(attn.to_v(context), h=attn.num_heads)
|
| 2245 |
+
|
| 2246 |
+
attention_matrix = einsum("b h i d, b h j d -> b h i j", query, key)
|
| 2247 |
+
|
| 2248 |
+
if context_mask is not None:
|
| 2249 |
+
max_neg_value = -torch.finfo(attention_matrix.dtype).max
|
| 2250 |
+
context_mask = context_mask.unsqueeze(1).unsqueeze(1)
|
| 2251 |
+
attention_matrix = attention_matrix.masked_fill(~(context_mask != 0), max_neg_value)
|
| 2252 |
+
attention_matrix = (attention_matrix * attn.scale).softmax(dim=-1)
|
| 2253 |
+
|
| 2254 |
+
out = einsum("b h i j, b h j d -> b h i d", attention_matrix, value)
|
| 2255 |
+
out = out.permute(0, 2, 1, 3).reshape(out.shape[0], out.shape[2], -1)
|
| 2256 |
+
out = attn.to_out[0](out)
|
| 2257 |
+
return out
|
| 2258 |
+
|
| 2259 |
+
|
| 2260 |
+
LORA_ATTENTION_PROCESSORS = (
|
| 2261 |
+
LoRAAttnProcessor,
|
| 2262 |
+
LoRAAttnProcessor2_0,
|
| 2263 |
+
LoRAXFormersAttnProcessor,
|
| 2264 |
+
LoRAAttnAddedKVProcessor,
|
| 2265 |
+
)
|
| 2266 |
+
|
| 2267 |
+
ADDED_KV_ATTENTION_PROCESSORS = (
|
| 2268 |
+
AttnAddedKVProcessor,
|
| 2269 |
+
SlicedAttnAddedKVProcessor,
|
| 2270 |
+
AttnAddedKVProcessor2_0,
|
| 2271 |
+
XFormersAttnAddedKVProcessor,
|
| 2272 |
+
LoRAAttnAddedKVProcessor,
|
| 2273 |
+
)
|
| 2274 |
+
|
| 2275 |
+
CROSS_ATTENTION_PROCESSORS = (
|
| 2276 |
+
AttnProcessor,
|
| 2277 |
+
AttnProcessor2_0,
|
| 2278 |
+
XFormersAttnProcessor,
|
| 2279 |
+
SlicedAttnProcessor,
|
| 2280 |
+
LoRAAttnProcessor,
|
| 2281 |
+
LoRAAttnProcessor2_0,
|
| 2282 |
+
LoRAXFormersAttnProcessor,
|
| 2283 |
+
IPAdapterAttnProcessor,
|
| 2284 |
+
IPAdapterAttnProcessor2_0,
|
| 2285 |
+
Kandi3AttnProcessor,
|
| 2286 |
+
)
|
| 2287 |
+
|
| 2288 |
+
AttentionProcessor = Union[
|
| 2289 |
+
AttnProcessor,
|
| 2290 |
+
AttnProcessor2_0,
|
| 2291 |
+
XFormersAttnProcessor,
|
| 2292 |
+
SlicedAttnProcessor,
|
| 2293 |
+
AttnAddedKVProcessor,
|
| 2294 |
+
SlicedAttnAddedKVProcessor,
|
| 2295 |
+
AttnAddedKVProcessor2_0,
|
| 2296 |
+
XFormersAttnAddedKVProcessor,
|
| 2297 |
+
CustomDiffusionAttnProcessor,
|
| 2298 |
+
CustomDiffusionXFormersAttnProcessor,
|
| 2299 |
+
CustomDiffusionAttnProcessor2_0,
|
| 2300 |
+
# deprecated
|
| 2301 |
+
LoRAAttnProcessor,
|
| 2302 |
+
LoRAAttnProcessor2_0,
|
| 2303 |
+
LoRAXFormersAttnProcessor,
|
| 2304 |
+
LoRAAttnAddedKVProcessor,
|
| 2305 |
+
]
|
diffusers/models/attention_processor_ip_face.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffusers/models/attention_processor_reference_only.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffusers/models/autoencoder_asym_kl.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Optional, Tuple, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
|
| 19 |
+
from ..configuration_utils import ConfigMixin, register_to_config
|
| 20 |
+
from ..utils.accelerate_utils import apply_forward_hook
|
| 21 |
+
from .modeling_outputs import AutoencoderKLOutput
|
| 22 |
+
from .modeling_utils import ModelMixin
|
| 23 |
+
from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder, MaskConditionDecoder
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class AsymmetricAutoencoderKL(ModelMixin, ConfigMixin):
|
| 27 |
+
r"""
|
| 28 |
+
Designing a Better Asymmetric VQGAN for StableDiffusion https://arxiv.org/abs/2306.04632 . A VAE model with KL loss
|
| 29 |
+
for encoding images into latents and decoding latent representations into images.
|
| 30 |
+
|
| 31 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
|
| 32 |
+
for all models (such as downloading or saving).
|
| 33 |
+
|
| 34 |
+
Parameters:
|
| 35 |
+
in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
|
| 36 |
+
out_channels (int, *optional*, defaults to 3): Number of channels in the output.
|
| 37 |
+
down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
|
| 38 |
+
Tuple of downsample block types.
|
| 39 |
+
down_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
|
| 40 |
+
Tuple of down block output channels.
|
| 41 |
+
layers_per_down_block (`int`, *optional*, defaults to `1`):
|
| 42 |
+
Number layers for down block.
|
| 43 |
+
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
|
| 44 |
+
Tuple of upsample block types.
|
| 45 |
+
up_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
|
| 46 |
+
Tuple of up block output channels.
|
| 47 |
+
layers_per_up_block (`int`, *optional*, defaults to `1`):
|
| 48 |
+
Number layers for up block.
|
| 49 |
+
act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
|
| 50 |
+
latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
|
| 51 |
+
sample_size (`int`, *optional*, defaults to `32`): Sample input size.
|
| 52 |
+
norm_num_groups (`int`, *optional*, defaults to `32`):
|
| 53 |
+
Number of groups to use for the first normalization layer in ResNet blocks.
|
| 54 |
+
scaling_factor (`float`, *optional*, defaults to 0.18215):
|
| 55 |
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
| 56 |
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
| 57 |
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
| 58 |
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
|
| 59 |
+
/ scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
|
| 60 |
+
Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
@register_to_config
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
in_channels: int = 3,
|
| 67 |
+
out_channels: int = 3,
|
| 68 |
+
down_block_types: Tuple[str, ...] = ("DownEncoderBlock2D",),
|
| 69 |
+
down_block_out_channels: Tuple[int, ...] = (64,),
|
| 70 |
+
layers_per_down_block: int = 1,
|
| 71 |
+
up_block_types: Tuple[str, ...] = ("UpDecoderBlock2D",),
|
| 72 |
+
up_block_out_channels: Tuple[int, ...] = (64,),
|
| 73 |
+
layers_per_up_block: int = 1,
|
| 74 |
+
act_fn: str = "silu",
|
| 75 |
+
latent_channels: int = 4,
|
| 76 |
+
norm_num_groups: int = 32,
|
| 77 |
+
sample_size: int = 32,
|
| 78 |
+
scaling_factor: float = 0.18215,
|
| 79 |
+
) -> None:
|
| 80 |
+
super().__init__()
|
| 81 |
+
|
| 82 |
+
# pass init params to Encoder
|
| 83 |
+
self.encoder = Encoder(
|
| 84 |
+
in_channels=in_channels,
|
| 85 |
+
out_channels=latent_channels,
|
| 86 |
+
down_block_types=down_block_types,
|
| 87 |
+
block_out_channels=down_block_out_channels,
|
| 88 |
+
layers_per_block=layers_per_down_block,
|
| 89 |
+
act_fn=act_fn,
|
| 90 |
+
norm_num_groups=norm_num_groups,
|
| 91 |
+
double_z=True,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# pass init params to Decoder
|
| 95 |
+
self.decoder = MaskConditionDecoder(
|
| 96 |
+
in_channels=latent_channels,
|
| 97 |
+
out_channels=out_channels,
|
| 98 |
+
up_block_types=up_block_types,
|
| 99 |
+
block_out_channels=up_block_out_channels,
|
| 100 |
+
layers_per_block=layers_per_up_block,
|
| 101 |
+
act_fn=act_fn,
|
| 102 |
+
norm_num_groups=norm_num_groups,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
|
| 106 |
+
self.post_quant_conv = nn.Conv2d(latent_channels, latent_channels, 1)
|
| 107 |
+
|
| 108 |
+
self.use_slicing = False
|
| 109 |
+
self.use_tiling = False
|
| 110 |
+
|
| 111 |
+
self.register_to_config(block_out_channels=up_block_out_channels)
|
| 112 |
+
self.register_to_config(force_upcast=False)
|
| 113 |
+
|
| 114 |
+
@apply_forward_hook
|
| 115 |
+
def encode(
|
| 116 |
+
self, x: torch.FloatTensor, return_dict: bool = True
|
| 117 |
+
) -> Union[AutoencoderKLOutput, Tuple[torch.FloatTensor]]:
|
| 118 |
+
h = self.encoder(x)
|
| 119 |
+
moments = self.quant_conv(h)
|
| 120 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 121 |
+
|
| 122 |
+
if not return_dict:
|
| 123 |
+
return (posterior,)
|
| 124 |
+
|
| 125 |
+
return AutoencoderKLOutput(latent_dist=posterior)
|
| 126 |
+
|
| 127 |
+
def _decode(
|
| 128 |
+
self,
|
| 129 |
+
z: torch.FloatTensor,
|
| 130 |
+
image: Optional[torch.FloatTensor] = None,
|
| 131 |
+
mask: Optional[torch.FloatTensor] = None,
|
| 132 |
+
return_dict: bool = True,
|
| 133 |
+
) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
|
| 134 |
+
z = self.post_quant_conv(z)
|
| 135 |
+
dec = self.decoder(z, image, mask)
|
| 136 |
+
|
| 137 |
+
if not return_dict:
|
| 138 |
+
return (dec,)
|
| 139 |
+
|
| 140 |
+
return DecoderOutput(sample=dec)
|
| 141 |
+
|
| 142 |
+
@apply_forward_hook
|
| 143 |
+
def decode(
|
| 144 |
+
self,
|
| 145 |
+
z: torch.FloatTensor,
|
| 146 |
+
generator: Optional[torch.Generator] = None,
|
| 147 |
+
image: Optional[torch.FloatTensor] = None,
|
| 148 |
+
mask: Optional[torch.FloatTensor] = None,
|
| 149 |
+
return_dict: bool = True,
|
| 150 |
+
) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
|
| 151 |
+
decoded = self._decode(z, image, mask).sample
|
| 152 |
+
|
| 153 |
+
if not return_dict:
|
| 154 |
+
return (decoded,)
|
| 155 |
+
|
| 156 |
+
return DecoderOutput(sample=decoded)
|
| 157 |
+
|
| 158 |
+
def forward(
|
| 159 |
+
self,
|
| 160 |
+
sample: torch.FloatTensor,
|
| 161 |
+
mask: Optional[torch.FloatTensor] = None,
|
| 162 |
+
sample_posterior: bool = False,
|
| 163 |
+
return_dict: bool = True,
|
| 164 |
+
generator: Optional[torch.Generator] = None,
|
| 165 |
+
) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
|
| 166 |
+
r"""
|
| 167 |
+
Args:
|
| 168 |
+
sample (`torch.FloatTensor`): Input sample.
|
| 169 |
+
mask (`torch.FloatTensor`, *optional*, defaults to `None`): Optional inpainting mask.
|
| 170 |
+
sample_posterior (`bool`, *optional*, defaults to `False`):
|
| 171 |
+
Whether to sample from the posterior.
|
| 172 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 173 |
+
Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
|
| 174 |
+
"""
|
| 175 |
+
x = sample
|
| 176 |
+
posterior = self.encode(x).latent_dist
|
| 177 |
+
if sample_posterior:
|
| 178 |
+
z = posterior.sample(generator=generator)
|
| 179 |
+
else:
|
| 180 |
+
z = posterior.mode()
|
| 181 |
+
dec = self.decode(z, sample, mask).sample
|
| 182 |
+
|
| 183 |
+
if not return_dict:
|
| 184 |
+
return (dec,)
|
| 185 |
+
|
| 186 |
+
return DecoderOutput(sample=dec)
|
diffusers/models/autoencoder_kl.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Dict, Optional, Tuple, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
|
| 19 |
+
from ..configuration_utils import ConfigMixin, register_to_config
|
| 20 |
+
from ..loaders import FromOriginalVAEMixin
|
| 21 |
+
from ..utils.accelerate_utils import apply_forward_hook
|
| 22 |
+
from .attention_processor import (
|
| 23 |
+
ADDED_KV_ATTENTION_PROCESSORS,
|
| 24 |
+
CROSS_ATTENTION_PROCESSORS,
|
| 25 |
+
AttentionProcessor,
|
| 26 |
+
AttnAddedKVProcessor,
|
| 27 |
+
AttnProcessor,
|
| 28 |
+
)
|
| 29 |
+
from .modeling_outputs import AutoencoderKLOutput
|
| 30 |
+
from .modeling_utils import ModelMixin
|
| 31 |
+
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class AutoencoderKL(ModelMixin, ConfigMixin, FromOriginalVAEMixin):
|
| 35 |
+
r"""
|
| 36 |
+
A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
|
| 37 |
+
|
| 38 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
|
| 39 |
+
for all models (such as downloading or saving).
|
| 40 |
+
|
| 41 |
+
Parameters:
|
| 42 |
+
in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
|
| 43 |
+
out_channels (int, *optional*, defaults to 3): Number of channels in the output.
|
| 44 |
+
down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
|
| 45 |
+
Tuple of downsample block types.
|
| 46 |
+
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
|
| 47 |
+
Tuple of upsample block types.
|
| 48 |
+
block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
|
| 49 |
+
Tuple of block output channels.
|
| 50 |
+
act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
|
| 51 |
+
latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
|
| 52 |
+
sample_size (`int`, *optional*, defaults to `32`): Sample input size.
|
| 53 |
+
scaling_factor (`float`, *optional*, defaults to 0.18215):
|
| 54 |
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
| 55 |
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
| 56 |
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
| 57 |
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
|
| 58 |
+
/ scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
|
| 59 |
+
Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
| 60 |
+
force_upcast (`bool`, *optional*, default to `True`):
|
| 61 |
+
If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
|
| 62 |
+
can be fine-tuned / trained to a lower range without loosing too much precision in which case
|
| 63 |
+
`force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
_supports_gradient_checkpointing = True
|
| 67 |
+
|
| 68 |
+
@register_to_config
|
| 69 |
+
def __init__(
|
| 70 |
+
self,
|
| 71 |
+
in_channels: int = 3,
|
| 72 |
+
out_channels: int = 3,
|
| 73 |
+
down_block_types: Tuple[str] = ("DownEncoderBlock2D",),
|
| 74 |
+
up_block_types: Tuple[str] = ("UpDecoderBlock2D",),
|
| 75 |
+
block_out_channels: Tuple[int] = (64,),
|
| 76 |
+
layers_per_block: int = 1,
|
| 77 |
+
act_fn: str = "silu",
|
| 78 |
+
latent_channels: int = 4,
|
| 79 |
+
norm_num_groups: int = 32,
|
| 80 |
+
sample_size: int = 32,
|
| 81 |
+
scaling_factor: float = 0.18215,
|
| 82 |
+
force_upcast: float = True,
|
| 83 |
+
):
|
| 84 |
+
super().__init__()
|
| 85 |
+
|
| 86 |
+
# pass init params to Encoder
|
| 87 |
+
self.encoder = Encoder(
|
| 88 |
+
in_channels=in_channels,
|
| 89 |
+
out_channels=latent_channels,
|
| 90 |
+
down_block_types=down_block_types,
|
| 91 |
+
block_out_channels=block_out_channels,
|
| 92 |
+
layers_per_block=layers_per_block,
|
| 93 |
+
act_fn=act_fn,
|
| 94 |
+
norm_num_groups=norm_num_groups,
|
| 95 |
+
double_z=True,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
# pass init params to Decoder
|
| 99 |
+
self.decoder = Decoder(
|
| 100 |
+
in_channels=latent_channels,
|
| 101 |
+
out_channels=out_channels,
|
| 102 |
+
up_block_types=up_block_types,
|
| 103 |
+
block_out_channels=block_out_channels,
|
| 104 |
+
layers_per_block=layers_per_block,
|
| 105 |
+
norm_num_groups=norm_num_groups,
|
| 106 |
+
act_fn=act_fn,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
|
| 110 |
+
self.post_quant_conv = nn.Conv2d(latent_channels, latent_channels, 1)
|
| 111 |
+
|
| 112 |
+
self.use_slicing = False
|
| 113 |
+
self.use_tiling = False
|
| 114 |
+
|
| 115 |
+
# only relevant if vae tiling is enabled
|
| 116 |
+
self.tile_sample_min_size = self.config.sample_size
|
| 117 |
+
sample_size = (
|
| 118 |
+
self.config.sample_size[0]
|
| 119 |
+
if isinstance(self.config.sample_size, (list, tuple))
|
| 120 |
+
else self.config.sample_size
|
| 121 |
+
)
|
| 122 |
+
self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
|
| 123 |
+
self.tile_overlap_factor = 0.25
|
| 124 |
+
|
| 125 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 126 |
+
if isinstance(module, (Encoder, Decoder)):
|
| 127 |
+
module.gradient_checkpointing = value
|
| 128 |
+
|
| 129 |
+
def enable_tiling(self, use_tiling: bool = True):
|
| 130 |
+
r"""
|
| 131 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 132 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 133 |
+
processing larger images.
|
| 134 |
+
"""
|
| 135 |
+
self.use_tiling = use_tiling
|
| 136 |
+
|
| 137 |
+
def disable_tiling(self):
|
| 138 |
+
r"""
|
| 139 |
+
Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
|
| 140 |
+
decoding in one step.
|
| 141 |
+
"""
|
| 142 |
+
self.enable_tiling(False)
|
| 143 |
+
|
| 144 |
+
def enable_slicing(self):
|
| 145 |
+
r"""
|
| 146 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 147 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 148 |
+
"""
|
| 149 |
+
self.use_slicing = True
|
| 150 |
+
|
| 151 |
+
def disable_slicing(self):
|
| 152 |
+
r"""
|
| 153 |
+
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
|
| 154 |
+
decoding in one step.
|
| 155 |
+
"""
|
| 156 |
+
self.use_slicing = False
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
|
| 160 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
| 161 |
+
r"""
|
| 162 |
+
Returns:
|
| 163 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
| 164 |
+
indexed by its weight name.
|
| 165 |
+
"""
|
| 166 |
+
# set recursively
|
| 167 |
+
processors = {}
|
| 168 |
+
|
| 169 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
| 170 |
+
if hasattr(module, "get_processor"):
|
| 171 |
+
processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
|
| 172 |
+
|
| 173 |
+
for sub_name, child in module.named_children():
|
| 174 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
| 175 |
+
|
| 176 |
+
return processors
|
| 177 |
+
|
| 178 |
+
for name, module in self.named_children():
|
| 179 |
+
fn_recursive_add_processors(name, module, processors)
|
| 180 |
+
|
| 181 |
+
return processors
|
| 182 |
+
|
| 183 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
| 184 |
+
def set_attn_processor(
|
| 185 |
+
self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
|
| 186 |
+
):
|
| 187 |
+
r"""
|
| 188 |
+
Sets the attention processor to use to compute attention.
|
| 189 |
+
|
| 190 |
+
Parameters:
|
| 191 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
| 192 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
| 193 |
+
for **all** `Attention` layers.
|
| 194 |
+
|
| 195 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
| 196 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
| 197 |
+
|
| 198 |
+
"""
|
| 199 |
+
count = len(self.attn_processors.keys())
|
| 200 |
+
|
| 201 |
+
if isinstance(processor, dict) and len(processor) != count:
|
| 202 |
+
raise ValueError(
|
| 203 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
| 204 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
| 208 |
+
if hasattr(module, "set_processor"):
|
| 209 |
+
if not isinstance(processor, dict):
|
| 210 |
+
module.set_processor(processor, _remove_lora=_remove_lora)
|
| 211 |
+
else:
|
| 212 |
+
module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
|
| 213 |
+
|
| 214 |
+
for sub_name, child in module.named_children():
|
| 215 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
| 216 |
+
|
| 217 |
+
for name, module in self.named_children():
|
| 218 |
+
fn_recursive_attn_processor(name, module, processor)
|
| 219 |
+
|
| 220 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
|
| 221 |
+
def set_default_attn_processor(self):
|
| 222 |
+
"""
|
| 223 |
+
Disables custom attention processors and sets the default attention implementation.
|
| 224 |
+
"""
|
| 225 |
+
if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
| 226 |
+
processor = AttnAddedKVProcessor()
|
| 227 |
+
elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
| 228 |
+
processor = AttnProcessor()
|
| 229 |
+
else:
|
| 230 |
+
raise ValueError(
|
| 231 |
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
self.set_attn_processor(processor, _remove_lora=True)
|
| 235 |
+
|
| 236 |
+
@apply_forward_hook
|
| 237 |
+
def encode(
|
| 238 |
+
self, x: torch.FloatTensor, return_dict: bool = True
|
| 239 |
+
) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
|
| 240 |
+
"""
|
| 241 |
+
Encode a batch of images into latents.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
x (`torch.FloatTensor`): Input batch of images.
|
| 245 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 246 |
+
Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
The latent representations of the encoded images. If `return_dict` is True, a
|
| 250 |
+
[`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
|
| 251 |
+
"""
|
| 252 |
+
if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
|
| 253 |
+
return self.tiled_encode(x, return_dict=return_dict)
|
| 254 |
+
|
| 255 |
+
if self.use_slicing and x.shape[0] > 1:
|
| 256 |
+
encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)]
|
| 257 |
+
h = torch.cat(encoded_slices)
|
| 258 |
+
else:
|
| 259 |
+
h = self.encoder(x)
|
| 260 |
+
|
| 261 |
+
moments = self.quant_conv(h)
|
| 262 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 263 |
+
|
| 264 |
+
if not return_dict:
|
| 265 |
+
return (posterior,)
|
| 266 |
+
|
| 267 |
+
return AutoencoderKLOutput(latent_dist=posterior)
|
| 268 |
+
|
| 269 |
+
def _decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
|
| 270 |
+
if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
|
| 271 |
+
return self.tiled_decode(z, return_dict=return_dict)
|
| 272 |
+
|
| 273 |
+
z = self.post_quant_conv(z)
|
| 274 |
+
dec = self.decoder(z)
|
| 275 |
+
|
| 276 |
+
if not return_dict:
|
| 277 |
+
return (dec,)
|
| 278 |
+
|
| 279 |
+
return DecoderOutput(sample=dec)
|
| 280 |
+
|
| 281 |
+
@apply_forward_hook
|
| 282 |
+
def decode(
|
| 283 |
+
self, z: torch.FloatTensor, return_dict: bool = True, generator=None
|
| 284 |
+
) -> Union[DecoderOutput, torch.FloatTensor]:
|
| 285 |
+
"""
|
| 286 |
+
Decode a batch of images.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
z (`torch.FloatTensor`): Input batch of latent vectors.
|
| 290 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 291 |
+
Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
|
| 292 |
+
|
| 293 |
+
Returns:
|
| 294 |
+
[`~models.vae.DecoderOutput`] or `tuple`:
|
| 295 |
+
If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
|
| 296 |
+
returned.
|
| 297 |
+
|
| 298 |
+
"""
|
| 299 |
+
if self.use_slicing and z.shape[0] > 1:
|
| 300 |
+
decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
|
| 301 |
+
decoded = torch.cat(decoded_slices)
|
| 302 |
+
else:
|
| 303 |
+
decoded = self._decode(z).sample
|
| 304 |
+
|
| 305 |
+
if not return_dict:
|
| 306 |
+
return (decoded,)
|
| 307 |
+
|
| 308 |
+
return DecoderOutput(sample=decoded)
|
| 309 |
+
|
| 310 |
+
def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
| 311 |
+
blend_extent = min(a.shape[2], b.shape[2], blend_extent)
|
| 312 |
+
for y in range(blend_extent):
|
| 313 |
+
b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
|
| 314 |
+
return b
|
| 315 |
+
|
| 316 |
+
def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
| 317 |
+
blend_extent = min(a.shape[3], b.shape[3], blend_extent)
|
| 318 |
+
for x in range(blend_extent):
|
| 319 |
+
b[:, :, :, x] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
|
| 320 |
+
return b
|
| 321 |
+
|
| 322 |
+
def tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True) -> AutoencoderKLOutput:
|
| 323 |
+
r"""Encode a batch of images using a tiled encoder.
|
| 324 |
+
|
| 325 |
+
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
|
| 326 |
+
steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
|
| 327 |
+
different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
|
| 328 |
+
tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
|
| 329 |
+
output, but they should be much less noticeable.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
x (`torch.FloatTensor`): Input batch of images.
|
| 333 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 334 |
+
Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
|
| 335 |
+
|
| 336 |
+
Returns:
|
| 337 |
+
[`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`:
|
| 338 |
+
If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain
|
| 339 |
+
`tuple` is returned.
|
| 340 |
+
"""
|
| 341 |
+
overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
|
| 342 |
+
blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
|
| 343 |
+
row_limit = self.tile_latent_min_size - blend_extent
|
| 344 |
+
|
| 345 |
+
# Split the image into 512x512 tiles and encode them separately.
|
| 346 |
+
rows = []
|
| 347 |
+
for i in range(0, x.shape[2], overlap_size):
|
| 348 |
+
row = []
|
| 349 |
+
for j in range(0, x.shape[3], overlap_size):
|
| 350 |
+
tile = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
|
| 351 |
+
tile = self.encoder(tile)
|
| 352 |
+
tile = self.quant_conv(tile)
|
| 353 |
+
row.append(tile)
|
| 354 |
+
rows.append(row)
|
| 355 |
+
result_rows = []
|
| 356 |
+
for i, row in enumerate(rows):
|
| 357 |
+
result_row = []
|
| 358 |
+
for j, tile in enumerate(row):
|
| 359 |
+
# blend the above tile and the left tile
|
| 360 |
+
# to the current tile and add the current tile to the result row
|
| 361 |
+
if i > 0:
|
| 362 |
+
tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
|
| 363 |
+
if j > 0:
|
| 364 |
+
tile = self.blend_h(row[j - 1], tile, blend_extent)
|
| 365 |
+
result_row.append(tile[:, :, :row_limit, :row_limit])
|
| 366 |
+
result_rows.append(torch.cat(result_row, dim=3))
|
| 367 |
+
|
| 368 |
+
moments = torch.cat(result_rows, dim=2)
|
| 369 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 370 |
+
|
| 371 |
+
if not return_dict:
|
| 372 |
+
return (posterior,)
|
| 373 |
+
|
| 374 |
+
return AutoencoderKLOutput(latent_dist=posterior)
|
| 375 |
+
|
| 376 |
+
def tiled_decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
|
| 377 |
+
r"""
|
| 378 |
+
Decode a batch of images using a tiled decoder.
|
| 379 |
+
|
| 380 |
+
Args:
|
| 381 |
+
z (`torch.FloatTensor`): Input batch of latent vectors.
|
| 382 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 383 |
+
Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
|
| 384 |
+
|
| 385 |
+
Returns:
|
| 386 |
+
[`~models.vae.DecoderOutput`] or `tuple`:
|
| 387 |
+
If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
|
| 388 |
+
returned.
|
| 389 |
+
"""
|
| 390 |
+
overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
|
| 391 |
+
blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
|
| 392 |
+
row_limit = self.tile_sample_min_size - blend_extent
|
| 393 |
+
|
| 394 |
+
# Split z into overlapping 64x64 tiles and decode them separately.
|
| 395 |
+
# The tiles have an overlap to avoid seams between tiles.
|
| 396 |
+
rows = []
|
| 397 |
+
for i in range(0, z.shape[2], overlap_size):
|
| 398 |
+
row = []
|
| 399 |
+
for j in range(0, z.shape[3], overlap_size):
|
| 400 |
+
tile = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
|
| 401 |
+
tile = self.post_quant_conv(tile)
|
| 402 |
+
decoded = self.decoder(tile)
|
| 403 |
+
row.append(decoded)
|
| 404 |
+
rows.append(row)
|
| 405 |
+
result_rows = []
|
| 406 |
+
for i, row in enumerate(rows):
|
| 407 |
+
result_row = []
|
| 408 |
+
for j, tile in enumerate(row):
|
| 409 |
+
# blend the above tile and the left tile
|
| 410 |
+
# to the current tile and add the current tile to the result row
|
| 411 |
+
if i > 0:
|
| 412 |
+
tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
|
| 413 |
+
if j > 0:
|
| 414 |
+
tile = self.blend_h(row[j - 1], tile, blend_extent)
|
| 415 |
+
result_row.append(tile[:, :, :row_limit, :row_limit])
|
| 416 |
+
result_rows.append(torch.cat(result_row, dim=3))
|
| 417 |
+
|
| 418 |
+
dec = torch.cat(result_rows, dim=2)
|
| 419 |
+
if not return_dict:
|
| 420 |
+
return (dec,)
|
| 421 |
+
|
| 422 |
+
return DecoderOutput(sample=dec)
|
| 423 |
+
|
| 424 |
+
def forward(
|
| 425 |
+
self,
|
| 426 |
+
sample: torch.FloatTensor,
|
| 427 |
+
sample_posterior: bool = False,
|
| 428 |
+
return_dict: bool = True,
|
| 429 |
+
generator: Optional[torch.Generator] = None,
|
| 430 |
+
) -> Union[DecoderOutput, torch.FloatTensor]:
|
| 431 |
+
r"""
|
| 432 |
+
Args:
|
| 433 |
+
sample (`torch.FloatTensor`): Input sample.
|
| 434 |
+
sample_posterior (`bool`, *optional*, defaults to `False`):
|
| 435 |
+
Whether to sample from the posterior.
|
| 436 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 437 |
+
Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
|
| 438 |
+
"""
|
| 439 |
+
x = sample
|
| 440 |
+
posterior = self.encode(x).latent_dist
|
| 441 |
+
if sample_posterior:
|
| 442 |
+
z = posterior.sample(generator=generator)
|
| 443 |
+
else:
|
| 444 |
+
z = posterior.mode()
|
| 445 |
+
dec = self.decode(z).sample
|
| 446 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import Dict, Optional, Tuple, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
|
| 19 |
+
from ..configuration_utils import ConfigMixin, register_to_config
|
| 20 |
+
from ..loaders import FromOriginalVAEMixin
|
| 21 |
+
from ..utils import is_torch_version
|
| 22 |
+
from ..utils.accelerate_utils import apply_forward_hook
|
| 23 |
+
from .attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor
|
| 24 |
+
from .modeling_outputs import AutoencoderKLOutput
|
| 25 |
+
from .modeling_utils import ModelMixin
|
| 26 |
+
from .unet_3d_blocks import MidBlockTemporalDecoder, UpBlockTemporalDecoder
|
| 27 |
+
from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TemporalDecoder(nn.Module):
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
in_channels: int = 4,
|
| 34 |
+
out_channels: int = 3,
|
| 35 |
+
block_out_channels: Tuple[int] = (128, 256, 512, 512),
|
| 36 |
+
layers_per_block: int = 2,
|
| 37 |
+
):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.layers_per_block = layers_per_block
|
| 40 |
+
|
| 41 |
+
self.conv_in = nn.Conv2d(in_channels, block_out_channels[-1], kernel_size=3, stride=1, padding=1)
|
| 42 |
+
self.mid_block = MidBlockTemporalDecoder(
|
| 43 |
+
num_layers=self.layers_per_block,
|
| 44 |
+
in_channels=block_out_channels[-1],
|
| 45 |
+
out_channels=block_out_channels[-1],
|
| 46 |
+
attention_head_dim=block_out_channels[-1],
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# up
|
| 50 |
+
self.up_blocks = nn.ModuleList([])
|
| 51 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
| 52 |
+
output_channel = reversed_block_out_channels[0]
|
| 53 |
+
for i in range(len(block_out_channels)):
|
| 54 |
+
prev_output_channel = output_channel
|
| 55 |
+
output_channel = reversed_block_out_channels[i]
|
| 56 |
+
|
| 57 |
+
is_final_block = i == len(block_out_channels) - 1
|
| 58 |
+
up_block = UpBlockTemporalDecoder(
|
| 59 |
+
num_layers=self.layers_per_block + 1,
|
| 60 |
+
in_channels=prev_output_channel,
|
| 61 |
+
out_channels=output_channel,
|
| 62 |
+
add_upsample=not is_final_block,
|
| 63 |
+
)
|
| 64 |
+
self.up_blocks.append(up_block)
|
| 65 |
+
prev_output_channel = output_channel
|
| 66 |
+
|
| 67 |
+
self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-6)
|
| 68 |
+
|
| 69 |
+
self.conv_act = nn.SiLU()
|
| 70 |
+
self.conv_out = torch.nn.Conv2d(
|
| 71 |
+
in_channels=block_out_channels[0],
|
| 72 |
+
out_channels=out_channels,
|
| 73 |
+
kernel_size=3,
|
| 74 |
+
padding=1,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
conv_out_kernel_size = (3, 1, 1)
|
| 78 |
+
padding = [int(k // 2) for k in conv_out_kernel_size]
|
| 79 |
+
self.time_conv_out = torch.nn.Conv3d(
|
| 80 |
+
in_channels=out_channels,
|
| 81 |
+
out_channels=out_channels,
|
| 82 |
+
kernel_size=conv_out_kernel_size,
|
| 83 |
+
padding=padding,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
self.gradient_checkpointing = False
|
| 87 |
+
|
| 88 |
+
def forward(
|
| 89 |
+
self,
|
| 90 |
+
sample: torch.FloatTensor,
|
| 91 |
+
image_only_indicator: torch.FloatTensor,
|
| 92 |
+
num_frames: int = 1,
|
| 93 |
+
) -> torch.FloatTensor:
|
| 94 |
+
r"""The forward method of the `Decoder` class."""
|
| 95 |
+
|
| 96 |
+
sample = self.conv_in(sample)
|
| 97 |
+
|
| 98 |
+
upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
|
| 99 |
+
if self.training and self.gradient_checkpointing:
|
| 100 |
+
|
| 101 |
+
def create_custom_forward(module):
|
| 102 |
+
def custom_forward(*inputs):
|
| 103 |
+
return module(*inputs)
|
| 104 |
+
|
| 105 |
+
return custom_forward
|
| 106 |
+
|
| 107 |
+
if is_torch_version(">=", "1.11.0"):
|
| 108 |
+
# middle
|
| 109 |
+
sample = torch.utils.checkpoint.checkpoint(
|
| 110 |
+
create_custom_forward(self.mid_block),
|
| 111 |
+
sample,
|
| 112 |
+
image_only_indicator,
|
| 113 |
+
use_reentrant=False,
|
| 114 |
+
)
|
| 115 |
+
sample = sample.to(upscale_dtype)
|
| 116 |
+
|
| 117 |
+
# up
|
| 118 |
+
for up_block in self.up_blocks:
|
| 119 |
+
sample = torch.utils.checkpoint.checkpoint(
|
| 120 |
+
create_custom_forward(up_block),
|
| 121 |
+
sample,
|
| 122 |
+
image_only_indicator,
|
| 123 |
+
use_reentrant=False,
|
| 124 |
+
)
|
| 125 |
+
else:
|
| 126 |
+
# middle
|
| 127 |
+
sample = torch.utils.checkpoint.checkpoint(
|
| 128 |
+
create_custom_forward(self.mid_block),
|
| 129 |
+
sample,
|
| 130 |
+
image_only_indicator,
|
| 131 |
+
)
|
| 132 |
+
sample = sample.to(upscale_dtype)
|
| 133 |
+
|
| 134 |
+
# up
|
| 135 |
+
for up_block in self.up_blocks:
|
| 136 |
+
sample = torch.utils.checkpoint.checkpoint(
|
| 137 |
+
create_custom_forward(up_block),
|
| 138 |
+
sample,
|
| 139 |
+
image_only_indicator,
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
# middle
|
| 143 |
+
sample = self.mid_block(sample, image_only_indicator=image_only_indicator)
|
| 144 |
+
sample = sample.to(upscale_dtype)
|
| 145 |
+
|
| 146 |
+
# up
|
| 147 |
+
for up_block in self.up_blocks:
|
| 148 |
+
sample = up_block(sample, image_only_indicator=image_only_indicator)
|
| 149 |
+
|
| 150 |
+
# post-process
|
| 151 |
+
sample = self.conv_norm_out(sample)
|
| 152 |
+
sample = self.conv_act(sample)
|
| 153 |
+
sample = self.conv_out(sample)
|
| 154 |
+
|
| 155 |
+
batch_frames, channels, height, width = sample.shape
|
| 156 |
+
batch_size = batch_frames // num_frames
|
| 157 |
+
sample = sample[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
|
| 158 |
+
sample = self.time_conv_out(sample)
|
| 159 |
+
|
| 160 |
+
sample = sample.permute(0, 2, 1, 3, 4).reshape(batch_frames, channels, height, width)
|
| 161 |
+
|
| 162 |
+
return sample
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class AutoencoderKLTemporalDecoder(ModelMixin, ConfigMixin, FromOriginalVAEMixin):
|
| 166 |
+
r"""
|
| 167 |
+
A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
|
| 168 |
+
|
| 169 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
|
| 170 |
+
for all models (such as downloading or saving).
|
| 171 |
+
|
| 172 |
+
Parameters:
|
| 173 |
+
in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
|
| 174 |
+
out_channels (int, *optional*, defaults to 3): Number of channels in the output.
|
| 175 |
+
down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
|
| 176 |
+
Tuple of downsample block types.
|
| 177 |
+
block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
|
| 178 |
+
Tuple of block output channels.
|
| 179 |
+
layers_per_block: (`int`, *optional*, defaults to 1): Number of layers per block.
|
| 180 |
+
latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
|
| 181 |
+
sample_size (`int`, *optional*, defaults to `32`): Sample input size.
|
| 182 |
+
scaling_factor (`float`, *optional*, defaults to 0.18215):
|
| 183 |
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
| 184 |
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
| 185 |
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
| 186 |
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
|
| 187 |
+
/ scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
|
| 188 |
+
Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
|
| 189 |
+
force_upcast (`bool`, *optional*, default to `True`):
|
| 190 |
+
If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
|
| 191 |
+
can be fine-tuned / trained to a lower range without loosing too much precision in which case
|
| 192 |
+
`force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
_supports_gradient_checkpointing = True
|
| 196 |
+
|
| 197 |
+
@register_to_config
|
| 198 |
+
def __init__(
|
| 199 |
+
self,
|
| 200 |
+
in_channels: int = 3,
|
| 201 |
+
out_channels: int = 3,
|
| 202 |
+
down_block_types: Tuple[str] = ("DownEncoderBlock2D",),
|
| 203 |
+
block_out_channels: Tuple[int] = (64,),
|
| 204 |
+
layers_per_block: int = 1,
|
| 205 |
+
latent_channels: int = 4,
|
| 206 |
+
sample_size: int = 32,
|
| 207 |
+
scaling_factor: float = 0.18215,
|
| 208 |
+
force_upcast: float = True,
|
| 209 |
+
):
|
| 210 |
+
super().__init__()
|
| 211 |
+
|
| 212 |
+
# pass init params to Encoder
|
| 213 |
+
self.encoder = Encoder(
|
| 214 |
+
in_channels=in_channels,
|
| 215 |
+
out_channels=latent_channels,
|
| 216 |
+
down_block_types=down_block_types,
|
| 217 |
+
block_out_channels=block_out_channels,
|
| 218 |
+
layers_per_block=layers_per_block,
|
| 219 |
+
double_z=True,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# pass init params to Decoder
|
| 223 |
+
self.decoder = TemporalDecoder(
|
| 224 |
+
in_channels=latent_channels,
|
| 225 |
+
out_channels=out_channels,
|
| 226 |
+
block_out_channels=block_out_channels,
|
| 227 |
+
layers_per_block=layers_per_block,
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
|
| 231 |
+
|
| 232 |
+
sample_size = (
|
| 233 |
+
self.config.sample_size[0]
|
| 234 |
+
if isinstance(self.config.sample_size, (list, tuple))
|
| 235 |
+
else self.config.sample_size
|
| 236 |
+
)
|
| 237 |
+
self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
|
| 238 |
+
self.tile_overlap_factor = 0.25
|
| 239 |
+
|
| 240 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 241 |
+
if isinstance(module, (Encoder, TemporalDecoder)):
|
| 242 |
+
module.gradient_checkpointing = value
|
| 243 |
+
|
| 244 |
+
@property
|
| 245 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
|
| 246 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
| 247 |
+
r"""
|
| 248 |
+
Returns:
|
| 249 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
| 250 |
+
indexed by its weight name.
|
| 251 |
+
"""
|
| 252 |
+
# set recursively
|
| 253 |
+
processors = {}
|
| 254 |
+
|
| 255 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
| 256 |
+
if hasattr(module, "get_processor"):
|
| 257 |
+
processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
|
| 258 |
+
|
| 259 |
+
for sub_name, child in module.named_children():
|
| 260 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
| 261 |
+
|
| 262 |
+
return processors
|
| 263 |
+
|
| 264 |
+
for name, module in self.named_children():
|
| 265 |
+
fn_recursive_add_processors(name, module, processors)
|
| 266 |
+
|
| 267 |
+
return processors
|
| 268 |
+
|
| 269 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
| 270 |
+
def set_attn_processor(
|
| 271 |
+
self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
|
| 272 |
+
):
|
| 273 |
+
r"""
|
| 274 |
+
Sets the attention processor to use to compute attention.
|
| 275 |
+
|
| 276 |
+
Parameters:
|
| 277 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
| 278 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
| 279 |
+
for **all** `Attention` layers.
|
| 280 |
+
|
| 281 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
| 282 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
| 283 |
+
|
| 284 |
+
"""
|
| 285 |
+
count = len(self.attn_processors.keys())
|
| 286 |
+
|
| 287 |
+
if isinstance(processor, dict) and len(processor) != count:
|
| 288 |
+
raise ValueError(
|
| 289 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
| 290 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
| 294 |
+
if hasattr(module, "set_processor"):
|
| 295 |
+
if not isinstance(processor, dict):
|
| 296 |
+
module.set_processor(processor, _remove_lora=_remove_lora)
|
| 297 |
+
else:
|
| 298 |
+
module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
|
| 299 |
+
|
| 300 |
+
for sub_name, child in module.named_children():
|
| 301 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
| 302 |
+
|
| 303 |
+
for name, module in self.named_children():
|
| 304 |
+
fn_recursive_attn_processor(name, module, processor)
|
| 305 |
+
|
| 306 |
+
def set_default_attn_processor(self):
|
| 307 |
+
"""
|
| 308 |
+
Disables custom attention processors and sets the default attention implementation.
|
| 309 |
+
"""
|
| 310 |
+
if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
| 311 |
+
processor = AttnProcessor()
|
| 312 |
+
else:
|
| 313 |
+
raise ValueError(
|
| 314 |
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
self.set_attn_processor(processor, _remove_lora=True)
|
| 318 |
+
|
| 319 |
+
@apply_forward_hook
|
| 320 |
+
def encode(
|
| 321 |
+
self, x: torch.FloatTensor, return_dict: bool = True
|
| 322 |
+
) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
|
| 323 |
+
"""
|
| 324 |
+
Encode a batch of images into latents.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
x (`torch.FloatTensor`): Input batch of images.
|
| 328 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 329 |
+
Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
|
| 330 |
+
|
| 331 |
+
Returns:
|
| 332 |
+
The latent representations of the encoded images. If `return_dict` is True, a
|
| 333 |
+
[`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
|
| 334 |
+
"""
|
| 335 |
+
h = self.encoder(x)
|
| 336 |
+
moments = self.quant_conv(h)
|
| 337 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 338 |
+
|
| 339 |
+
if not return_dict:
|
| 340 |
+
return (posterior,)
|
| 341 |
+
|
| 342 |
+
return AutoencoderKLOutput(latent_dist=posterior)
|
| 343 |
+
|
| 344 |
+
@apply_forward_hook
|
| 345 |
+
def decode(
|
| 346 |
+
self,
|
| 347 |
+
z: torch.FloatTensor,
|
| 348 |
+
num_frames: int,
|
| 349 |
+
return_dict: bool = True,
|
| 350 |
+
) -> Union[DecoderOutput, torch.FloatTensor]:
|
| 351 |
+
"""
|
| 352 |
+
Decode a batch of images.
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
z (`torch.FloatTensor`): Input batch of latent vectors.
|
| 356 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 357 |
+
Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
|
| 358 |
+
|
| 359 |
+
Returns:
|
| 360 |
+
[`~models.vae.DecoderOutput`] or `tuple`:
|
| 361 |
+
If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
|
| 362 |
+
returned.
|
| 363 |
+
|
| 364 |
+
"""
|
| 365 |
+
batch_size = z.shape[0] // num_frames
|
| 366 |
+
image_only_indicator = torch.zeros(batch_size, num_frames, dtype=z.dtype, device=z.device)
|
| 367 |
+
decoded = self.decoder(z, num_frames=num_frames, image_only_indicator=image_only_indicator)
|
| 368 |
+
|
| 369 |
+
if not return_dict:
|
| 370 |
+
return (decoded,)
|
| 371 |
+
|
| 372 |
+
return DecoderOutput(sample=decoded)
|
| 373 |
+
|
| 374 |
+
def forward(
|
| 375 |
+
self,
|
| 376 |
+
sample: torch.FloatTensor,
|
| 377 |
+
sample_posterior: bool = False,
|
| 378 |
+
return_dict: bool = True,
|
| 379 |
+
generator: Optional[torch.Generator] = None,
|
| 380 |
+
num_frames: int = 1,
|
| 381 |
+
) -> Union[DecoderOutput, torch.FloatTensor]:
|
| 382 |
+
r"""
|
| 383 |
+
Args:
|
| 384 |
+
sample (`torch.FloatTensor`): Input sample.
|
| 385 |
+
sample_posterior (`bool`, *optional*, defaults to `False`):
|
| 386 |
+
Whether to sample from the posterior.
|
| 387 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 388 |
+
Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
|
| 389 |
+
"""
|
| 390 |
+
x = sample
|
| 391 |
+
posterior = self.encode(x).latent_dist
|
| 392 |
+
if sample_posterior:
|
| 393 |
+
z = posterior.sample(generator=generator)
|
| 394 |
+
else:
|
| 395 |
+
z = posterior.mode()
|
| 396 |
+
|
| 397 |
+
dec = self.decode(z, num_frames=num_frames).sample
|
| 398 |
+
|
| 399 |
+
if not return_dict:
|
| 400 |
+
return (dec,)
|
| 401 |
+
|
| 402 |
+
return DecoderOutput(sample=dec)
|
diffusers/models/autoencoder_tiny.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Ollin Boer Bohan and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from ..configuration_utils import ConfigMixin, register_to_config
|
| 22 |
+
from ..utils import BaseOutput
|
| 23 |
+
from ..utils.accelerate_utils import apply_forward_hook
|
| 24 |
+
from .modeling_utils import ModelMixin
|
| 25 |
+
from .vae import DecoderOutput, DecoderTiny, EncoderTiny
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class AutoencoderTinyOutput(BaseOutput):
|
| 30 |
+
"""
|
| 31 |
+
Output of AutoencoderTiny encoding method.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
latents (`torch.Tensor`): Encoded outputs of the `Encoder`.
|
| 35 |
+
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
latents: torch.Tensor
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class AutoencoderTiny(ModelMixin, ConfigMixin):
|
| 42 |
+
r"""
|
| 43 |
+
A tiny distilled VAE model for encoding images into latents and decoding latent representations into images.
|
| 44 |
+
|
| 45 |
+
[`AutoencoderTiny`] is a wrapper around the original implementation of `TAESD`.
|
| 46 |
+
|
| 47 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for its generic methods implemented for
|
| 48 |
+
all models (such as downloading or saving).
|
| 49 |
+
|
| 50 |
+
Parameters:
|
| 51 |
+
in_channels (`int`, *optional*, defaults to 3): Number of channels in the input image.
|
| 52 |
+
out_channels (`int`, *optional*, defaults to 3): Number of channels in the output.
|
| 53 |
+
encoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`):
|
| 54 |
+
Tuple of integers representing the number of output channels for each encoder block. The length of the
|
| 55 |
+
tuple should be equal to the number of encoder blocks.
|
| 56 |
+
decoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`):
|
| 57 |
+
Tuple of integers representing the number of output channels for each decoder block. The length of the
|
| 58 |
+
tuple should be equal to the number of decoder blocks.
|
| 59 |
+
act_fn (`str`, *optional*, defaults to `"relu"`):
|
| 60 |
+
Activation function to be used throughout the model.
|
| 61 |
+
latent_channels (`int`, *optional*, defaults to 4):
|
| 62 |
+
Number of channels in the latent representation. The latent space acts as a compressed representation of
|
| 63 |
+
the input image.
|
| 64 |
+
upsampling_scaling_factor (`int`, *optional*, defaults to 2):
|
| 65 |
+
Scaling factor for upsampling in the decoder. It determines the size of the output image during the
|
| 66 |
+
upsampling process.
|
| 67 |
+
num_encoder_blocks (`Tuple[int]`, *optional*, defaults to `(1, 3, 3, 3)`):
|
| 68 |
+
Tuple of integers representing the number of encoder blocks at each stage of the encoding process. The
|
| 69 |
+
length of the tuple should be equal to the number of stages in the encoder. Each stage has a different
|
| 70 |
+
number of encoder blocks.
|
| 71 |
+
num_decoder_blocks (`Tuple[int]`, *optional*, defaults to `(3, 3, 3, 1)`):
|
| 72 |
+
Tuple of integers representing the number of decoder blocks at each stage of the decoding process. The
|
| 73 |
+
length of the tuple should be equal to the number of stages in the decoder. Each stage has a different
|
| 74 |
+
number of decoder blocks.
|
| 75 |
+
latent_magnitude (`float`, *optional*, defaults to 3.0):
|
| 76 |
+
Magnitude of the latent representation. This parameter scales the latent representation values to control
|
| 77 |
+
the extent of information preservation.
|
| 78 |
+
latent_shift (float, *optional*, defaults to 0.5):
|
| 79 |
+
Shift applied to the latent representation. This parameter controls the center of the latent space.
|
| 80 |
+
scaling_factor (`float`, *optional*, defaults to 1.0):
|
| 81 |
+
The component-wise standard deviation of the trained latent space computed using the first batch of the
|
| 82 |
+
training set. This is used to scale the latent space to have unit variance when training the diffusion
|
| 83 |
+
model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
|
| 84 |
+
diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
|
| 85 |
+
/ scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
|
| 86 |
+
Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper. For this Autoencoder,
|
| 87 |
+
however, no such scaling factor was used, hence the value of 1.0 as the default.
|
| 88 |
+
force_upcast (`bool`, *optional*, default to `False`):
|
| 89 |
+
If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
|
| 90 |
+
can be fine-tuned / trained to a lower range without losing too much precision, in which case
|
| 91 |
+
`force_upcast` can be set to `False` (see this fp16-friendly
|
| 92 |
+
[AutoEncoder](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)).
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
_supports_gradient_checkpointing = True
|
| 96 |
+
|
| 97 |
+
@register_to_config
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
in_channels: int = 3,
|
| 101 |
+
out_channels: int = 3,
|
| 102 |
+
encoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64),
|
| 103 |
+
decoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64),
|
| 104 |
+
act_fn: str = "relu",
|
| 105 |
+
latent_channels: int = 4,
|
| 106 |
+
upsampling_scaling_factor: int = 2,
|
| 107 |
+
num_encoder_blocks: Tuple[int, ...] = (1, 3, 3, 3),
|
| 108 |
+
num_decoder_blocks: Tuple[int, ...] = (3, 3, 3, 1),
|
| 109 |
+
latent_magnitude: int = 3,
|
| 110 |
+
latent_shift: float = 0.5,
|
| 111 |
+
force_upcast: bool = False,
|
| 112 |
+
scaling_factor: float = 1.0,
|
| 113 |
+
):
|
| 114 |
+
super().__init__()
|
| 115 |
+
|
| 116 |
+
if len(encoder_block_out_channels) != len(num_encoder_blocks):
|
| 117 |
+
raise ValueError("`encoder_block_out_channels` should have the same length as `num_encoder_blocks`.")
|
| 118 |
+
if len(decoder_block_out_channels) != len(num_decoder_blocks):
|
| 119 |
+
raise ValueError("`decoder_block_out_channels` should have the same length as `num_decoder_blocks`.")
|
| 120 |
+
|
| 121 |
+
self.encoder = EncoderTiny(
|
| 122 |
+
in_channels=in_channels,
|
| 123 |
+
out_channels=latent_channels,
|
| 124 |
+
num_blocks=num_encoder_blocks,
|
| 125 |
+
block_out_channels=encoder_block_out_channels,
|
| 126 |
+
act_fn=act_fn,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
self.decoder = DecoderTiny(
|
| 130 |
+
in_channels=latent_channels,
|
| 131 |
+
out_channels=out_channels,
|
| 132 |
+
num_blocks=num_decoder_blocks,
|
| 133 |
+
block_out_channels=decoder_block_out_channels,
|
| 134 |
+
upsampling_scaling_factor=upsampling_scaling_factor,
|
| 135 |
+
act_fn=act_fn,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
self.latent_magnitude = latent_magnitude
|
| 139 |
+
self.latent_shift = latent_shift
|
| 140 |
+
self.scaling_factor = scaling_factor
|
| 141 |
+
|
| 142 |
+
self.use_slicing = False
|
| 143 |
+
self.use_tiling = False
|
| 144 |
+
|
| 145 |
+
# only relevant if vae tiling is enabled
|
| 146 |
+
self.spatial_scale_factor = 2**out_channels
|
| 147 |
+
self.tile_overlap_factor = 0.125
|
| 148 |
+
self.tile_sample_min_size = 512
|
| 149 |
+
self.tile_latent_min_size = self.tile_sample_min_size // self.spatial_scale_factor
|
| 150 |
+
|
| 151 |
+
self.register_to_config(block_out_channels=decoder_block_out_channels)
|
| 152 |
+
self.register_to_config(force_upcast=False)
|
| 153 |
+
|
| 154 |
+
def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
|
| 155 |
+
if isinstance(module, (EncoderTiny, DecoderTiny)):
|
| 156 |
+
module.gradient_checkpointing = value
|
| 157 |
+
|
| 158 |
+
def scale_latents(self, x: torch.FloatTensor) -> torch.FloatTensor:
|
| 159 |
+
"""raw latents -> [0, 1]"""
|
| 160 |
+
return x.div(2 * self.latent_magnitude).add(self.latent_shift).clamp(0, 1)
|
| 161 |
+
|
| 162 |
+
def unscale_latents(self, x: torch.FloatTensor) -> torch.FloatTensor:
|
| 163 |
+
"""[0, 1] -> raw latents"""
|
| 164 |
+
return x.sub(self.latent_shift).mul(2 * self.latent_magnitude)
|
| 165 |
+
|
| 166 |
+
def enable_slicing(self) -> None:
|
| 167 |
+
r"""
|
| 168 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 169 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 170 |
+
"""
|
| 171 |
+
self.use_slicing = True
|
| 172 |
+
|
| 173 |
+
def disable_slicing(self) -> None:
|
| 174 |
+
r"""
|
| 175 |
+
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
|
| 176 |
+
decoding in one step.
|
| 177 |
+
"""
|
| 178 |
+
self.use_slicing = False
|
| 179 |
+
|
| 180 |
+
def enable_tiling(self, use_tiling: bool = True) -> None:
|
| 181 |
+
r"""
|
| 182 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 183 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 184 |
+
processing larger images.
|
| 185 |
+
"""
|
| 186 |
+
self.use_tiling = use_tiling
|
| 187 |
+
|
| 188 |
+
def disable_tiling(self) -> None:
|
| 189 |
+
r"""
|
| 190 |
+
Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
|
| 191 |
+
decoding in one step.
|
| 192 |
+
"""
|
| 193 |
+
self.enable_tiling(False)
|
| 194 |
+
|
| 195 |
+
def _tiled_encode(self, x: torch.FloatTensor) -> torch.FloatTensor:
|
| 196 |
+
r"""Encode a batch of images using a tiled encoder.
|
| 197 |
+
|
| 198 |
+
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
|
| 199 |
+
steps. This is useful to keep memory use constant regardless of image size. To avoid tiling artifacts, the
|
| 200 |
+
tiles overlap and are blended together to form a smooth output.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
x (`torch.FloatTensor`): Input batch of images.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
`torch.FloatTensor`: Encoded batch of images.
|
| 207 |
+
"""
|
| 208 |
+
# scale of encoder output relative to input
|
| 209 |
+
sf = self.spatial_scale_factor
|
| 210 |
+
tile_size = self.tile_sample_min_size
|
| 211 |
+
|
| 212 |
+
# number of pixels to blend and to traverse between tile
|
| 213 |
+
blend_size = int(tile_size * self.tile_overlap_factor)
|
| 214 |
+
traverse_size = tile_size - blend_size
|
| 215 |
+
|
| 216 |
+
# tiles index (up/left)
|
| 217 |
+
ti = range(0, x.shape[-2], traverse_size)
|
| 218 |
+
tj = range(0, x.shape[-1], traverse_size)
|
| 219 |
+
|
| 220 |
+
# mask for blending
|
| 221 |
+
blend_masks = torch.stack(
|
| 222 |
+
torch.meshgrid([torch.arange(tile_size / sf) / (blend_size / sf - 1)] * 2, indexing="ij")
|
| 223 |
+
)
|
| 224 |
+
blend_masks = blend_masks.clamp(0, 1).to(x.device)
|
| 225 |
+
|
| 226 |
+
# output array
|
| 227 |
+
out = torch.zeros(x.shape[0], 4, x.shape[-2] // sf, x.shape[-1] // sf, device=x.device)
|
| 228 |
+
for i in ti:
|
| 229 |
+
for j in tj:
|
| 230 |
+
tile_in = x[..., i : i + tile_size, j : j + tile_size]
|
| 231 |
+
# tile result
|
| 232 |
+
tile_out = out[..., i // sf : (i + tile_size) // sf, j // sf : (j + tile_size) // sf]
|
| 233 |
+
tile = self.encoder(tile_in)
|
| 234 |
+
h, w = tile.shape[-2], tile.shape[-1]
|
| 235 |
+
# blend tile result into output
|
| 236 |
+
blend_mask_i = torch.ones_like(blend_masks[0]) if i == 0 else blend_masks[0]
|
| 237 |
+
blend_mask_j = torch.ones_like(blend_masks[1]) if j == 0 else blend_masks[1]
|
| 238 |
+
blend_mask = blend_mask_i * blend_mask_j
|
| 239 |
+
tile, blend_mask = tile[..., :h, :w], blend_mask[..., :h, :w]
|
| 240 |
+
tile_out.copy_(blend_mask * tile + (1 - blend_mask) * tile_out)
|
| 241 |
+
return out
|
| 242 |
+
|
| 243 |
+
def _tiled_decode(self, x: torch.FloatTensor) -> torch.FloatTensor:
|
| 244 |
+
r"""Encode a batch of images using a tiled encoder.
|
| 245 |
+
|
| 246 |
+
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
|
| 247 |
+
steps. This is useful to keep memory use constant regardless of image size. To avoid tiling artifacts, the
|
| 248 |
+
tiles overlap and are blended together to form a smooth output.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
x (`torch.FloatTensor`): Input batch of images.
|
| 252 |
+
|
| 253 |
+
Returns:
|
| 254 |
+
`torch.FloatTensor`: Encoded batch of images.
|
| 255 |
+
"""
|
| 256 |
+
# scale of decoder output relative to input
|
| 257 |
+
sf = self.spatial_scale_factor
|
| 258 |
+
tile_size = self.tile_latent_min_size
|
| 259 |
+
|
| 260 |
+
# number of pixels to blend and to traverse between tiles
|
| 261 |
+
blend_size = int(tile_size * self.tile_overlap_factor)
|
| 262 |
+
traverse_size = tile_size - blend_size
|
| 263 |
+
|
| 264 |
+
# tiles index (up/left)
|
| 265 |
+
ti = range(0, x.shape[-2], traverse_size)
|
| 266 |
+
tj = range(0, x.shape[-1], traverse_size)
|
| 267 |
+
|
| 268 |
+
# mask for blending
|
| 269 |
+
blend_masks = torch.stack(
|
| 270 |
+
torch.meshgrid([torch.arange(tile_size * sf) / (blend_size * sf - 1)] * 2, indexing="ij")
|
| 271 |
+
)
|
| 272 |
+
blend_masks = blend_masks.clamp(0, 1).to(x.device)
|
| 273 |
+
|
| 274 |
+
# output array
|
| 275 |
+
out = torch.zeros(x.shape[0], 3, x.shape[-2] * sf, x.shape[-1] * sf, device=x.device)
|
| 276 |
+
for i in ti:
|
| 277 |
+
for j in tj:
|
| 278 |
+
tile_in = x[..., i : i + tile_size, j : j + tile_size]
|
| 279 |
+
# tile result
|
| 280 |
+
tile_out = out[..., i * sf : (i + tile_size) * sf, j * sf : (j + tile_size) * sf]
|
| 281 |
+
tile = self.decoder(tile_in)
|
| 282 |
+
h, w = tile.shape[-2], tile.shape[-1]
|
| 283 |
+
# blend tile result into output
|
| 284 |
+
blend_mask_i = torch.ones_like(blend_masks[0]) if i == 0 else blend_masks[0]
|
| 285 |
+
blend_mask_j = torch.ones_like(blend_masks[1]) if j == 0 else blend_masks[1]
|
| 286 |
+
blend_mask = (blend_mask_i * blend_mask_j)[..., :h, :w]
|
| 287 |
+
tile_out.copy_(blend_mask * tile + (1 - blend_mask) * tile_out)
|
| 288 |
+
return out
|
| 289 |
+
|
| 290 |
+
@apply_forward_hook
|
| 291 |
+
def encode(
|
| 292 |
+
self, x: torch.FloatTensor, return_dict: bool = True
|
| 293 |
+
) -> Union[AutoencoderTinyOutput, Tuple[torch.FloatTensor]]:
|
| 294 |
+
if self.use_slicing and x.shape[0] > 1:
|
| 295 |
+
output = [self._tiled_encode(x_slice) if self.use_tiling else self.encoder(x) for x_slice in x.split(1)]
|
| 296 |
+
output = torch.cat(output)
|
| 297 |
+
else:
|
| 298 |
+
output = self._tiled_encode(x) if self.use_tiling else self.encoder(x)
|
| 299 |
+
|
| 300 |
+
if not return_dict:
|
| 301 |
+
return (output,)
|
| 302 |
+
|
| 303 |
+
return AutoencoderTinyOutput(latents=output)
|
| 304 |
+
|
| 305 |
+
@apply_forward_hook
|
| 306 |
+
def decode(
|
| 307 |
+
self, x: torch.FloatTensor, generator: Optional[torch.Generator] = None, return_dict: bool = True
|
| 308 |
+
) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
|
| 309 |
+
if self.use_slicing and x.shape[0] > 1:
|
| 310 |
+
output = [self._tiled_decode(x_slice) if self.use_tiling else self.decoder(x) for x_slice in x.split(1)]
|
| 311 |
+
output = torch.cat(output)
|
| 312 |
+
else:
|
| 313 |
+
output = self._tiled_decode(x) if self.use_tiling else self.decoder(x)
|
| 314 |
+
|
| 315 |
+
if not return_dict:
|
| 316 |
+
return (output,)
|
| 317 |
+
|
| 318 |
+
return DecoderOutput(sample=output)
|
| 319 |
+
|
| 320 |
+
def forward(
|
| 321 |
+
self,
|
| 322 |
+
sample: torch.FloatTensor,
|
| 323 |
+
return_dict: bool = True,
|
| 324 |
+
) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
|
| 325 |
+
r"""
|
| 326 |
+
Args:
|
| 327 |
+
sample (`torch.FloatTensor`): Input sample.
|
| 328 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 329 |
+
Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
|
| 330 |
+
"""
|
| 331 |
+
enc = self.encode(sample).latents
|
| 332 |
+
|
| 333 |
+
# scale latents to be in [0, 1], then quantize latents to a byte tensor,
|
| 334 |
+
# as if we were storing the latents in an RGBA uint8 image.
|
| 335 |
+
scaled_enc = self.scale_latents(enc).mul_(255).round_().byte()
|
| 336 |
+
|
| 337 |
+
# unquantize latents back into [0, 1], then unscale latents back to their original range,
|
| 338 |
+
# as if we were loading the latents from an RGBA uint8 image.
|
| 339 |
+
unscaled_enc = self.unscale_latents(scaled_enc / 255.0)
|
| 340 |
+
|
| 341 |
+
dec = self.decode(unscaled_enc)
|
| 342 |
+
|
| 343 |
+
if not return_dict:
|
| 344 |
+
return (dec,)
|
| 345 |
+
return DecoderOutput(sample=dec)
|
diffusers/models/consistency_decoder_vae.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Dict, Optional, Tuple, Union
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from torch import nn
|
| 20 |
+
|
| 21 |
+
from ..configuration_utils import ConfigMixin, register_to_config
|
| 22 |
+
from ..schedulers import ConsistencyDecoderScheduler
|
| 23 |
+
from ..utils import BaseOutput
|
| 24 |
+
from ..utils.accelerate_utils import apply_forward_hook
|
| 25 |
+
from ..utils.torch_utils import randn_tensor
|
| 26 |
+
from .attention_processor import (
|
| 27 |
+
ADDED_KV_ATTENTION_PROCESSORS,
|
| 28 |
+
CROSS_ATTENTION_PROCESSORS,
|
| 29 |
+
AttentionProcessor,
|
| 30 |
+
AttnAddedKVProcessor,
|
| 31 |
+
AttnProcessor,
|
| 32 |
+
)
|
| 33 |
+
from .modeling_utils import ModelMixin
|
| 34 |
+
from .unet_2d import UNet2DModel
|
| 35 |
+
from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class ConsistencyDecoderVAEOutput(BaseOutput):
|
| 40 |
+
"""
|
| 41 |
+
Output of encoding method.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
latent_dist (`DiagonalGaussianDistribution`):
|
| 45 |
+
Encoded outputs of `Encoder` represented as the mean and logvar of `DiagonalGaussianDistribution`.
|
| 46 |
+
`DiagonalGaussianDistribution` allows for sampling latents from the distribution.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
latent_dist: "DiagonalGaussianDistribution"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
|
| 53 |
+
r"""
|
| 54 |
+
The consistency decoder used with DALL-E 3.
|
| 55 |
+
|
| 56 |
+
Examples:
|
| 57 |
+
```py
|
| 58 |
+
>>> import torch
|
| 59 |
+
>>> from diffusers import StableDiffusionPipeline, ConsistencyDecoderVAE
|
| 60 |
+
|
| 61 |
+
>>> vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16)
|
| 62 |
+
>>> pipe = StableDiffusionPipeline.from_pretrained(
|
| 63 |
+
... "runwayml/stable-diffusion-v1-5", vae=vae, torch_dtype=torch.float16
|
| 64 |
+
... ).to("cuda")
|
| 65 |
+
|
| 66 |
+
>>> pipe("horse", generator=torch.manual_seed(0)).images
|
| 67 |
+
```
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
@register_to_config
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
scaling_factor: float = 0.18215,
|
| 74 |
+
latent_channels: int = 4,
|
| 75 |
+
encoder_act_fn: str = "silu",
|
| 76 |
+
encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
|
| 77 |
+
encoder_double_z: bool = True,
|
| 78 |
+
encoder_down_block_types: Tuple[str, ...] = (
|
| 79 |
+
"DownEncoderBlock2D",
|
| 80 |
+
"DownEncoderBlock2D",
|
| 81 |
+
"DownEncoderBlock2D",
|
| 82 |
+
"DownEncoderBlock2D",
|
| 83 |
+
),
|
| 84 |
+
encoder_in_channels: int = 3,
|
| 85 |
+
encoder_layers_per_block: int = 2,
|
| 86 |
+
encoder_norm_num_groups: int = 32,
|
| 87 |
+
encoder_out_channels: int = 4,
|
| 88 |
+
decoder_add_attention: bool = False,
|
| 89 |
+
decoder_block_out_channels: Tuple[int, ...] = (320, 640, 1024, 1024),
|
| 90 |
+
decoder_down_block_types: Tuple[str, ...] = (
|
| 91 |
+
"ResnetDownsampleBlock2D",
|
| 92 |
+
"ResnetDownsampleBlock2D",
|
| 93 |
+
"ResnetDownsampleBlock2D",
|
| 94 |
+
"ResnetDownsampleBlock2D",
|
| 95 |
+
),
|
| 96 |
+
decoder_downsample_padding: int = 1,
|
| 97 |
+
decoder_in_channels: int = 7,
|
| 98 |
+
decoder_layers_per_block: int = 3,
|
| 99 |
+
decoder_norm_eps: float = 1e-05,
|
| 100 |
+
decoder_norm_num_groups: int = 32,
|
| 101 |
+
decoder_num_train_timesteps: int = 1024,
|
| 102 |
+
decoder_out_channels: int = 6,
|
| 103 |
+
decoder_resnet_time_scale_shift: str = "scale_shift",
|
| 104 |
+
decoder_time_embedding_type: str = "learned",
|
| 105 |
+
decoder_up_block_types: Tuple[str, ...] = (
|
| 106 |
+
"ResnetUpsampleBlock2D",
|
| 107 |
+
"ResnetUpsampleBlock2D",
|
| 108 |
+
"ResnetUpsampleBlock2D",
|
| 109 |
+
"ResnetUpsampleBlock2D",
|
| 110 |
+
),
|
| 111 |
+
):
|
| 112 |
+
super().__init__()
|
| 113 |
+
self.encoder = Encoder(
|
| 114 |
+
act_fn=encoder_act_fn,
|
| 115 |
+
block_out_channels=encoder_block_out_channels,
|
| 116 |
+
double_z=encoder_double_z,
|
| 117 |
+
down_block_types=encoder_down_block_types,
|
| 118 |
+
in_channels=encoder_in_channels,
|
| 119 |
+
layers_per_block=encoder_layers_per_block,
|
| 120 |
+
norm_num_groups=encoder_norm_num_groups,
|
| 121 |
+
out_channels=encoder_out_channels,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
self.decoder_unet = UNet2DModel(
|
| 125 |
+
add_attention=decoder_add_attention,
|
| 126 |
+
block_out_channels=decoder_block_out_channels,
|
| 127 |
+
down_block_types=decoder_down_block_types,
|
| 128 |
+
downsample_padding=decoder_downsample_padding,
|
| 129 |
+
in_channels=decoder_in_channels,
|
| 130 |
+
layers_per_block=decoder_layers_per_block,
|
| 131 |
+
norm_eps=decoder_norm_eps,
|
| 132 |
+
norm_num_groups=decoder_norm_num_groups,
|
| 133 |
+
num_train_timesteps=decoder_num_train_timesteps,
|
| 134 |
+
out_channels=decoder_out_channels,
|
| 135 |
+
resnet_time_scale_shift=decoder_resnet_time_scale_shift,
|
| 136 |
+
time_embedding_type=decoder_time_embedding_type,
|
| 137 |
+
up_block_types=decoder_up_block_types,
|
| 138 |
+
)
|
| 139 |
+
self.decoder_scheduler = ConsistencyDecoderScheduler()
|
| 140 |
+
self.register_to_config(block_out_channels=encoder_block_out_channels)
|
| 141 |
+
self.register_to_config(force_upcast=False)
|
| 142 |
+
self.register_buffer(
|
| 143 |
+
"means",
|
| 144 |
+
torch.tensor([0.38862467, 0.02253063, 0.07381133, -0.0171294])[None, :, None, None],
|
| 145 |
+
persistent=False,
|
| 146 |
+
)
|
| 147 |
+
self.register_buffer(
|
| 148 |
+
"stds", torch.tensor([0.9654121, 1.0440036, 0.76147926, 0.77022034])[None, :, None, None], persistent=False
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
|
| 152 |
+
|
| 153 |
+
self.use_slicing = False
|
| 154 |
+
self.use_tiling = False
|
| 155 |
+
|
| 156 |
+
# Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_tiling
|
| 157 |
+
def enable_tiling(self, use_tiling: bool = True):
|
| 158 |
+
r"""
|
| 159 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 160 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 161 |
+
processing larger images.
|
| 162 |
+
"""
|
| 163 |
+
self.use_tiling = use_tiling
|
| 164 |
+
|
| 165 |
+
# Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_tiling
|
| 166 |
+
def disable_tiling(self):
|
| 167 |
+
r"""
|
| 168 |
+
Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
|
| 169 |
+
decoding in one step.
|
| 170 |
+
"""
|
| 171 |
+
self.enable_tiling(False)
|
| 172 |
+
|
| 173 |
+
# Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_slicing
|
| 174 |
+
def enable_slicing(self):
|
| 175 |
+
r"""
|
| 176 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 177 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 178 |
+
"""
|
| 179 |
+
self.use_slicing = True
|
| 180 |
+
|
| 181 |
+
# Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_slicing
|
| 182 |
+
def disable_slicing(self):
|
| 183 |
+
r"""
|
| 184 |
+
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
|
| 185 |
+
decoding in one step.
|
| 186 |
+
"""
|
| 187 |
+
self.use_slicing = False
|
| 188 |
+
|
| 189 |
+
@property
|
| 190 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
|
| 191 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
| 192 |
+
r"""
|
| 193 |
+
Returns:
|
| 194 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
| 195 |
+
indexed by its weight name.
|
| 196 |
+
"""
|
| 197 |
+
# set recursively
|
| 198 |
+
processors = {}
|
| 199 |
+
|
| 200 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
| 201 |
+
if hasattr(module, "get_processor"):
|
| 202 |
+
processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
|
| 203 |
+
|
| 204 |
+
for sub_name, child in module.named_children():
|
| 205 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
| 206 |
+
|
| 207 |
+
return processors
|
| 208 |
+
|
| 209 |
+
for name, module in self.named_children():
|
| 210 |
+
fn_recursive_add_processors(name, module, processors)
|
| 211 |
+
|
| 212 |
+
return processors
|
| 213 |
+
|
| 214 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
| 215 |
+
def set_attn_processor(
|
| 216 |
+
self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
|
| 217 |
+
):
|
| 218 |
+
r"""
|
| 219 |
+
Sets the attention processor to use to compute attention.
|
| 220 |
+
|
| 221 |
+
Parameters:
|
| 222 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
| 223 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
| 224 |
+
for **all** `Attention` layers.
|
| 225 |
+
|
| 226 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
| 227 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
| 228 |
+
|
| 229 |
+
"""
|
| 230 |
+
count = len(self.attn_processors.keys())
|
| 231 |
+
|
| 232 |
+
if isinstance(processor, dict) and len(processor) != count:
|
| 233 |
+
raise ValueError(
|
| 234 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
| 235 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
| 239 |
+
if hasattr(module, "set_processor"):
|
| 240 |
+
if not isinstance(processor, dict):
|
| 241 |
+
module.set_processor(processor, _remove_lora=_remove_lora)
|
| 242 |
+
else:
|
| 243 |
+
module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
|
| 244 |
+
|
| 245 |
+
for sub_name, child in module.named_children():
|
| 246 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
| 247 |
+
|
| 248 |
+
for name, module in self.named_children():
|
| 249 |
+
fn_recursive_attn_processor(name, module, processor)
|
| 250 |
+
|
| 251 |
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
|
| 252 |
+
def set_default_attn_processor(self):
|
| 253 |
+
"""
|
| 254 |
+
Disables custom attention processors and sets the default attention implementation.
|
| 255 |
+
"""
|
| 256 |
+
if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
| 257 |
+
processor = AttnAddedKVProcessor()
|
| 258 |
+
elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
| 259 |
+
processor = AttnProcessor()
|
| 260 |
+
else:
|
| 261 |
+
raise ValueError(
|
| 262 |
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
self.set_attn_processor(processor, _remove_lora=True)
|
| 266 |
+
|
| 267 |
+
@apply_forward_hook
|
| 268 |
+
def encode(
|
| 269 |
+
self, x: torch.FloatTensor, return_dict: bool = True
|
| 270 |
+
) -> Union[ConsistencyDecoderVAEOutput, Tuple[DiagonalGaussianDistribution]]:
|
| 271 |
+
"""
|
| 272 |
+
Encode a batch of images into latents.
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
x (`torch.FloatTensor`): Input batch of images.
|
| 276 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 277 |
+
Whether to return a [`~models.consistecy_decoder_vae.ConsistencyDecoderOoutput`] instead of a plain
|
| 278 |
+
tuple.
|
| 279 |
+
|
| 280 |
+
Returns:
|
| 281 |
+
The latent representations of the encoded images. If `return_dict` is True, a
|
| 282 |
+
[`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] is returned, otherwise a plain `tuple`
|
| 283 |
+
is returned.
|
| 284 |
+
"""
|
| 285 |
+
if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
|
| 286 |
+
return self.tiled_encode(x, return_dict=return_dict)
|
| 287 |
+
|
| 288 |
+
if self.use_slicing and x.shape[0] > 1:
|
| 289 |
+
encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)]
|
| 290 |
+
h = torch.cat(encoded_slices)
|
| 291 |
+
else:
|
| 292 |
+
h = self.encoder(x)
|
| 293 |
+
|
| 294 |
+
moments = self.quant_conv(h)
|
| 295 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 296 |
+
|
| 297 |
+
if not return_dict:
|
| 298 |
+
return (posterior,)
|
| 299 |
+
|
| 300 |
+
return ConsistencyDecoderVAEOutput(latent_dist=posterior)
|
| 301 |
+
|
| 302 |
+
@apply_forward_hook
|
| 303 |
+
def decode(
|
| 304 |
+
self,
|
| 305 |
+
z: torch.FloatTensor,
|
| 306 |
+
generator: Optional[torch.Generator] = None,
|
| 307 |
+
return_dict: bool = True,
|
| 308 |
+
num_inference_steps: int = 2,
|
| 309 |
+
) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
|
| 310 |
+
z = (z * self.config.scaling_factor - self.means) / self.stds
|
| 311 |
+
|
| 312 |
+
scale_factor = 2 ** (len(self.config.block_out_channels) - 1)
|
| 313 |
+
z = F.interpolate(z, mode="nearest", scale_factor=scale_factor)
|
| 314 |
+
|
| 315 |
+
batch_size, _, height, width = z.shape
|
| 316 |
+
|
| 317 |
+
self.decoder_scheduler.set_timesteps(num_inference_steps, device=self.device)
|
| 318 |
+
|
| 319 |
+
x_t = self.decoder_scheduler.init_noise_sigma * randn_tensor(
|
| 320 |
+
(batch_size, 3, height, width), generator=generator, dtype=z.dtype, device=z.device
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
for t in self.decoder_scheduler.timesteps:
|
| 324 |
+
model_input = torch.concat([self.decoder_scheduler.scale_model_input(x_t, t), z], dim=1)
|
| 325 |
+
model_output = self.decoder_unet(model_input, t).sample[:, :3, :, :]
|
| 326 |
+
prev_sample = self.decoder_scheduler.step(model_output, t, x_t, generator).prev_sample
|
| 327 |
+
x_t = prev_sample
|
| 328 |
+
|
| 329 |
+
x_0 = x_t
|
| 330 |
+
|
| 331 |
+
if not return_dict:
|
| 332 |
+
return (x_0,)
|
| 333 |
+
|
| 334 |
+
return DecoderOutput(sample=x_0)
|
| 335 |
+
|
| 336 |
+
# Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_v
|
| 337 |
+
def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
| 338 |
+
blend_extent = min(a.shape[2], b.shape[2], blend_extent)
|
| 339 |
+
for y in range(blend_extent):
|
| 340 |
+
b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
|
| 341 |
+
return b
|
| 342 |
+
|
| 343 |
+
# Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_h
|
| 344 |
+
def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
| 345 |
+
blend_extent = min(a.shape[3], b.shape[3], blend_extent)
|
| 346 |
+
for x in range(blend_extent):
|
| 347 |
+
b[:, :, :, x] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
|
| 348 |
+
return b
|
| 349 |
+
|
| 350 |
+
def tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True) -> ConsistencyDecoderVAEOutput:
|
| 351 |
+
r"""Encode a batch of images using a tiled encoder.
|
| 352 |
+
|
| 353 |
+
When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
|
| 354 |
+
steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
|
| 355 |
+
different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
|
| 356 |
+
tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
|
| 357 |
+
output, but they should be much less noticeable.
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
x (`torch.FloatTensor`): Input batch of images.
|
| 361 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 362 |
+
Whether or not to return a [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] instead of a
|
| 363 |
+
plain tuple.
|
| 364 |
+
|
| 365 |
+
Returns:
|
| 366 |
+
[`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] or `tuple`:
|
| 367 |
+
If return_dict is True, a [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] is returned,
|
| 368 |
+
otherwise a plain `tuple` is returned.
|
| 369 |
+
"""
|
| 370 |
+
overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
|
| 371 |
+
blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
|
| 372 |
+
row_limit = self.tile_latent_min_size - blend_extent
|
| 373 |
+
|
| 374 |
+
# Split the image into 512x512 tiles and encode them separately.
|
| 375 |
+
rows = []
|
| 376 |
+
for i in range(0, x.shape[2], overlap_size):
|
| 377 |
+
row = []
|
| 378 |
+
for j in range(0, x.shape[3], overlap_size):
|
| 379 |
+
tile = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
|
| 380 |
+
tile = self.encoder(tile)
|
| 381 |
+
tile = self.quant_conv(tile)
|
| 382 |
+
row.append(tile)
|
| 383 |
+
rows.append(row)
|
| 384 |
+
result_rows = []
|
| 385 |
+
for i, row in enumerate(rows):
|
| 386 |
+
result_row = []
|
| 387 |
+
for j, tile in enumerate(row):
|
| 388 |
+
# blend the above tile and the left tile
|
| 389 |
+
# to the current tile and add the current tile to the result row
|
| 390 |
+
if i > 0:
|
| 391 |
+
tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
|
| 392 |
+
if j > 0:
|
| 393 |
+
tile = self.blend_h(row[j - 1], tile, blend_extent)
|
| 394 |
+
result_row.append(tile[:, :, :row_limit, :row_limit])
|
| 395 |
+
result_rows.append(torch.cat(result_row, dim=3))
|
| 396 |
+
|
| 397 |
+
moments = torch.cat(result_rows, dim=2)
|
| 398 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 399 |
+
|
| 400 |
+
if not return_dict:
|
| 401 |
+
return (posterior,)
|
| 402 |
+
|
| 403 |
+
return ConsistencyDecoderVAEOutput(latent_dist=posterior)
|
| 404 |
+
|
| 405 |
+
def forward(
|
| 406 |
+
self,
|
| 407 |
+
sample: torch.FloatTensor,
|
| 408 |
+
sample_posterior: bool = False,
|
| 409 |
+
return_dict: bool = True,
|
| 410 |
+
generator: Optional[torch.Generator] = None,
|
| 411 |
+
) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
|
| 412 |
+
r"""
|
| 413 |
+
Args:
|
| 414 |
+
sample (`torch.FloatTensor`): Input sample.
|
| 415 |
+
sample_posterior (`bool`, *optional*, defaults to `False`):
|
| 416 |
+
Whether to sample from the posterior.
|
| 417 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 418 |
+
Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
|
| 419 |
+
generator (`torch.Generator`, *optional*, defaults to `None`):
|
| 420 |
+
Generator to use for sampling.
|
| 421 |
+
|
| 422 |
+
Returns:
|
| 423 |
+
[`DecoderOutput`] or `tuple`:
|
| 424 |
+
If return_dict is True, a [`DecoderOutput`] is returned, otherwise a plain `tuple` is returned.
|
| 425 |
+
"""
|
| 426 |
+
x = sample
|
| 427 |
+
posterior = self.encode(x).latent_dist
|
| 428 |
+
if sample_posterior:
|
| 429 |
+
z = posterior.sample(generator=generator)
|
| 430 |
+
else:
|
| 431 |
+
z = posterior.mode()
|
| 432 |
+
dec = self.decode(z, generator=generator).sample
|
| 433 |
+
|
| 434 |
+
if not return_dict:
|
| 435 |
+
return (dec,)
|
| 436 |
+
|
| 437 |
+
return DecoderOutput(sample=dec)
|