Spaces:
Runtime error
Runtime error
guobc2026 commited on
Commit ·
21db46b
0
Parent(s):
Stable-Makeup: HF Spaces deployment
Browse files- .gitattributes +51 -0
- .gitignore +6 -0
- HANDOFF.md +95 -0
- README.md +23 -0
- app.py +185 -0
- detail_encoder/__init__.py +0 -0
- detail_encoder/_clip.py +1349 -0
- detail_encoder/attention_processor.py +687 -0
- detail_encoder/encoder_plus.py +113 -0
- detail_encoder/resampler.py +112 -0
- download_weights.py +30 -0
- face_utils.py +99 -0
- pipeline_sd15.py +1867 -0
- requirements.txt +24 -0
- spiga_draw.py +199 -0
.gitattributes
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
|
| 4 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 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 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
|
| 18 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.db* filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.ark* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.gguf* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.ggml filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.llamafile* filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*.pt2 filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
|
| 49 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
|
| 51 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
/models/
|
| 4 |
+
/weights/
|
| 5 |
+
*.pyc
|
| 6 |
+
*.part
|
HANDOFF.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🤝 AI 交接文档 · Stable-Makeup 妆容迁移部署
|
| 2 |
+
|
| 3 |
+
> 写给下一位 AI:请从 AutoDL 终端开始,跑通推理流程。
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## 项目目标
|
| 8 |
+
|
| 9 |
+
部署 Stable-Makeup(妆容迁移 AI):用户上传素颜照 + 妆容参考图 → AI 输出迁移后的照片。
|
| 10 |
+
|
| 11 |
+
## 当前状态
|
| 12 |
+
|
| 13 |
+
用户在 **AutoDL** 租了一台 GPU 实例:
|
| 14 |
+
- **显卡**: RTX 2080Ti 11GB
|
| 15 |
+
- **环境**: PyTorch 2.x + CUDA 12.1 + Python 3.12 + Ubuntu 22.04
|
| 16 |
+
- **状态**: 实例已创建,JupyterLab 已打开,还没开始操作
|
| 17 |
+
|
| 18 |
+
代码仓库:`https://www.modelscope.cn/studios/guobc2026/stable-makeup.git`
|
| 19 |
+
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
## 下一步(在 AutoDL JupyterLab Terminal 里执行)
|
| 23 |
+
|
| 24 |
+
### 第 1 步:拉代码 + 装依赖
|
| 25 |
+
```bash
|
| 26 |
+
git clone https://www.modelscope.cn/studios/guobc2026/stable-makeup.git
|
| 27 |
+
cd stable-makeup && pip install -r requirements.txt
|
| 28 |
+
```
|
| 29 |
+
预计 3-5 分钟。依赖已锁版本,AutoDL 干净环境不会冲突。
|
| 30 |
+
|
| 31 |
+
### 第 2 步:启动
|
| 32 |
+
```bash
|
| 33 |
+
python app.py
|
| 34 |
+
```
|
| 35 |
+
模型加载(下载 + 加载到 GPU)预计 5-10 分钟。成功标志:打印 `✅ 模型加载完成 (float16 GPU + DDIM)`。
|
| 36 |
+
|
| 37 |
+
### 第 3 步:测试
|
| 38 |
+
Gradio 会打印公网链接(`https://xxx.gradio.live`),打开后上传素颜照和妆容图,点「开始试妆」测试。
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## 技术架构(关键信息)
|
| 43 |
+
|
| 44 |
+
### 推理链路
|
| 45 |
+
```
|
| 46 |
+
素颜照 → batch_face.RetinaFace(人脸检测) → SPIGA(98点关键点) → 骨架图 → ControlNet
|
| 47 |
+
参考图 → CLIP ViT-L/14 → SSR Attention → cross-attention注入
|
| 48 |
+
→ SD1.5 UNet(DDIM 30步) → 输出
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### 文件说明
|
| 52 |
+
| 文件 | 作用 |
|
| 53 |
+
|------|------|
|
| 54 |
+
| `app.py` | 主入口,Gradio UI + 推理函数 |
|
| 55 |
+
| `spiga_draw.py` | 人脸关键点检测 + 骨架图生成 |
|
| 56 |
+
| `pipeline_sd15.py` | 自定义 StableDiffusionControlNetPipeline(支持双路 ControlNet + SSR attention) |
|
| 57 |
+
| `detail_encoder/` | 妆容编码器(CLIP + SSR cross-attention) |
|
| 58 |
+
| `requirements.txt` | 完整依赖,版本已锁定 |
|
| 59 |
+
|
| 60 |
+
### 依赖版本链(不可单拆)
|
| 61 |
+
```
|
| 62 |
+
diffusers==0.29.2 + transformers==4.42.4 + peft==0.10.0
|
| 63 |
+
```
|
| 64 |
+
这三个版本互相依赖,改任何一个会导致 import 报错。`pipeline_sd15.py` 专为 diffusers 0.29.2 编写。
|
| 65 |
+
|
| 66 |
+
### 模型下载源
|
| 67 |
+
- **SD1.5 / CLIP / SPIGA**: 从 ModelScope 下载(`_ms_download` 函数)
|
| 68 |
+
- **Stable-Makeup 预训练权重**: 从 HuggingFace Hub 下载(`Xiaojiu-z/Stable-Makeup`)
|
| 69 |
+
- **人脸检测**: batch_face 包(pip 安装,不依赖 GitHub)
|
| 70 |
+
|
| 71 |
+
### 精度
|
| 72 |
+
- GPU: float16
|
| 73 |
+
- CPU: float32
|
| 74 |
+
- `app.py` 第 18 行自动判断:`DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32`
|
| 75 |
+
|
| 76 |
+
---
|
| 77 |
+
|
| 78 |
+
## 已知坑(已踩过)
|
| 79 |
+
|
| 80 |
+
| 坑 | 症状 | 原因 | 解决 |
|
| 81 |
+
|----|------|------|------|
|
| 82 |
+
| peft/transformers 版本冲突 | `ImportError: cannot import name 'EncoderDecoderCache'` | peft 新版本要求 transformers ≥ 4.45 | 锁死 peft==0.10.0 |
|
| 83 |
+
| GitHub 不可达 | facelib 安装超时 | ModelScope/AutoDL 可能无法访问 GitHub | 用 batch_face 替代 |
|
| 84 |
+
| .gitignore 误伤 vendor | `ModuleNotFoundError: _vendor.facelib` | `models/` 递归匹配 | 已删除 vendor 方案 |
|
| 85 |
+
| float16 在 CPU 报错 | 推理崩溃 | CPU 不支持 float16 运算 | 自适应精度 |
|
| 86 |
+
| 调度器不匹配 | 推理结果不对 | 默认 DPMSolver 不是论文原版 | 改用 DDIMScheduler |
|
| 87 |
+
|
| 88 |
+
---
|
| 89 |
+
|
| 90 |
+
## 成功标准
|
| 91 |
+
|
| 92 |
+
1. `app.py` 启动无报错
|
| 93 |
+
2. 模型加载打印 `✅ 模型加载完成`
|
| 94 |
+
3. 上传两张照片后返回一张 512×512 的妆容迁移结果
|
| 95 |
+
4. 推理时间:GPU 上约 10-20 秒/张
|
README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Stable-Makeup 妆容迁移
|
| 3 |
+
emoji: 💄
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: pink
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.1
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# 💄 Stable-Makeup · 妆容迁移
|
| 13 |
+
|
| 14 |
+
上传素颜照 + 参考妆容图,AI 将妆容迁移到你的照片上。
|
| 15 |
+
|
| 16 |
+
基于 [Stable-Makeup](https://arxiv.org/abs/2403.07764) (arXiv 2403.07764) · SD1.5 + 双路 ControlNet + D-P 妆容编码器
|
| 17 |
+
|
| 18 |
+
## 部署架构
|
| 19 |
+
|
| 20 |
+
- **推理框架**: Gradio 4.44.1 + Diffusers 0.29.2
|
| 21 |
+
- **模型加载**: 全部从 HuggingFace Hub 加载(不依赖外部网络)
|
| 22 |
+
- **精度**: GPU float16 / CPU float32 自适应
|
| 23 |
+
- **参考实现**: [sky24h/Stable-Makeup-unofficial](https://huggingface.co/spaces/sky24h/Stable-Makeup-unofficial)
|
app.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable-Makeup: 妆容迁移 · ModelScope 创空间 xGPU
|
| 2 |
+
|
| 3 |
+
基于 sky24h/Stable-Makeup-unofficial 成功部署方案。
|
| 4 |
+
模型从 ModelScope 加载,预训练权重从 HuggingFace Hub 拉取。
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import torch
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
+
os.chdir(PROJECT_ROOT)
|
| 15 |
+
|
| 16 |
+
# ═══ 设备 · 精度自适应 ═══
|
| 17 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
+
DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
|
| 19 |
+
print(f"[Stable-Makeup] 设备: {DEVICE}, 精度: {DTYPE}")
|
| 20 |
+
if DEVICE == "cuda":
|
| 21 |
+
print(f"[Stable-Makeup] GPU: {torch.cuda.get_device_name(0)}, 显存: {torch.cuda.get_device_properties(0).total_memory/1024**3:.0f}GB")
|
| 22 |
+
|
| 23 |
+
# ═══ 固定随机种子(与 sky24h 一致) ═══
|
| 24 |
+
torch.manual_seed(1024)
|
| 25 |
+
if torch.cuda.is_available():
|
| 26 |
+
torch.cuda.manual_seed(1024)
|
| 27 |
+
torch.cuda.manual_seed_all(1024)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# ═══════════════════════════════════════════════════════════
|
| 31 |
+
# 模型初始化(模块级加载)
|
| 32 |
+
# ═══════════════════════════════════════════════════════════
|
| 33 |
+
|
| 34 |
+
def _ms_download(repo_id, cache_dir="./models"):
|
| 35 |
+
"""从 ModelScope 下载模型"""
|
| 36 |
+
from modelscope import snapshot_download
|
| 37 |
+
return snapshot_download(repo_id, cache_dir=cache_dir)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def init_pipeline():
|
| 41 |
+
"""初始化推理管线——float16 GPU + DDIM"""
|
| 42 |
+
from diffusers import UNet2DConditionModel as OriginalUNet2DConditionModel
|
| 43 |
+
from diffusers import DDIMScheduler, ControlNetModel
|
| 44 |
+
from pipeline_sd15 import StableDiffusionControlNetPipeline
|
| 45 |
+
from detail_encoder.encoder_plus import detail_encoder
|
| 46 |
+
|
| 47 |
+
# ── SD1.5 基础模型 ──
|
| 48 |
+
sd15_dir = _ms_download("AI-ModelScope/stable-diffusion-v1-5")
|
| 49 |
+
print(f"[Stable-Makeup] SD1.5: {sd15_dir}")
|
| 50 |
+
|
| 51 |
+
Unet = OriginalUNet2DConditionModel.from_pretrained(
|
| 52 |
+
sd15_dir, subfolder="unet", torch_dtype=DTYPE, local_files_only=True
|
| 53 |
+
).to(DEVICE)
|
| 54 |
+
|
| 55 |
+
# ── 双路 ControlNet ──
|
| 56 |
+
id_encoder = ControlNetModel.from_unet(Unet)
|
| 57 |
+
pose_encoder = ControlNetModel.from_unet(Unet)
|
| 58 |
+
|
| 59 |
+
# ── 妆容编码器(CLIP + SSR attention) ──
|
| 60 |
+
clip_dir = _ms_download("AI-ModelScope/clip-vit-large-patch14")
|
| 61 |
+
print(f"[Stable-Makeup] CLIP: {clip_dir}")
|
| 62 |
+
makeup_encoder = detail_encoder(Unet, clip_dir, DEVICE, dtype=DTYPE)
|
| 63 |
+
|
| 64 |
+
# ── 加载 Stable-Makeup 预训练权重(本地优先 → Google Drive 兜底) ──
|
| 65 |
+
print("[Stable-Makeup] 加载预训练权重...")
|
| 66 |
+
import gc
|
| 67 |
+
|
| 68 |
+
REQUIRED = ["pytorch_model.bin", "pytorch_model_1.bin", "pytorch_model_2.bin"]
|
| 69 |
+
WEIGHTS_DIR = os.path.join(PROJECT_ROOT, "weights")
|
| 70 |
+
GDRIVE_FOLDER = "1397t27GrUyLPnj17qVpKWGwg93EcaFfg"
|
| 71 |
+
|
| 72 |
+
# 检查缺失文件 → 自动从 Google Drive 下载(HF Spaces 海外服务器可直连)
|
| 73 |
+
os.makedirs(WEIGHTS_DIR, exist_ok=True)
|
| 74 |
+
missing = [f for f in REQUIRED if not os.path.exists(os.path.join(WEIGHTS_DIR, f))]
|
| 75 |
+
if missing:
|
| 76 |
+
print(f"[Stable-Makeup] 缺失: {missing},从 Google Drive 下载...")
|
| 77 |
+
try:
|
| 78 |
+
import gdown
|
| 79 |
+
gdown.download_folder(id=GDRIVE_FOLDER, output=WEIGHTS_DIR, quiet=False)
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"[Stable-Makeup] ⚠️ 自动下载失败: {e}")
|
| 82 |
+
print(f" 请手动下载: https://drive.google.com/drive/folders/{GDRIVE_FOLDER}")
|
| 83 |
+
print(f" 放到: {WEIGHTS_DIR}/")
|
| 84 |
+
raise
|
| 85 |
+
|
| 86 |
+
def _load_weight(filename):
|
| 87 |
+
local_path = os.path.join(WEIGHTS_DIR, filename)
|
| 88 |
+
print(f" ✅ 加载: {local_path} ({os.path.getsize(local_path)/1024**3:.1f}GB)")
|
| 89 |
+
return torch.load(local_path, map_location="cpu")
|
| 90 |
+
|
| 91 |
+
id_encoder.load_state_dict(_load_weight("pytorch_model_1.bin"), strict=False)
|
| 92 |
+
gc.collect()
|
| 93 |
+
pose_encoder.load_state_dict(_load_weight("pytorch_model_2.bin"), strict=False)
|
| 94 |
+
gc.collect()
|
| 95 |
+
makeup_encoder.load_state_dict(_load_weight("pytorch_model.bin"), strict=False)
|
| 96 |
+
gc.collect()
|
| 97 |
+
|
| 98 |
+
id_encoder.to(device=DEVICE, dtype=DTYPE)
|
| 99 |
+
pose_encoder.to(device=DEVICE, dtype=DTYPE)
|
| 100 |
+
makeup_encoder.to(device=DEVICE, dtype=DTYPE)
|
| 101 |
+
|
| 102 |
+
# ── 推理管线 ──
|
| 103 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 104 |
+
sd15_dir,
|
| 105 |
+
safety_checker=None,
|
| 106 |
+
unet=Unet,
|
| 107 |
+
controlnet=[id_encoder, pose_encoder],
|
| 108 |
+
torch_dtype=DTYPE,
|
| 109 |
+
local_files_only=True,
|
| 110 |
+
).to(DEVICE)
|
| 111 |
+
|
| 112 |
+
# DDIMScheduler(论文原版,与 sky24h 一致)
|
| 113 |
+
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
|
| 114 |
+
print("[Stable-Makeup] ✅ 模型加载完成 (float16 GPU + DDIM)")
|
| 115 |
+
return pipe, makeup_encoder
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ── 启动时加载模型 ──
|
| 119 |
+
pipeline, makeup_encoder = init_pipeline()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ═══════════���═══════════════════════════════════════════════
|
| 123 |
+
# 推理函数
|
| 124 |
+
# ═══════════════════════════════════════════════════════════
|
| 125 |
+
|
| 126 |
+
def get_draw(pil_img, size):
|
| 127 |
+
"""生成人脸结构控制图(PIL → cv2 BGR → SPIGA → 骨架图)"""
|
| 128 |
+
import cv2
|
| 129 |
+
from spiga_draw import spiga_process, spiga_segmentation
|
| 130 |
+
cv2_img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
|
| 131 |
+
spigas = spiga_process(cv2_img)
|
| 132 |
+
if spigas is False:
|
| 133 |
+
width, height = pil_img.size
|
| 134 |
+
return Image.new("RGB", (width, height), color=(0, 0, 0))
|
| 135 |
+
return spiga_segmentation(spigas, size=size)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def makeup_transfer(id_image, makeup_image, guidance_scale=1.6):
|
| 139 |
+
"""妆容迁移——与 sky24h 推理逻辑完全一致"""
|
| 140 |
+
size = 512
|
| 141 |
+
id_image_resized = id_image.resize((size, size))
|
| 142 |
+
makeup_image_resized = makeup_image.resize((size, size))
|
| 143 |
+
|
| 144 |
+
pose_image = get_draw(id_image_resized, size=size)
|
| 145 |
+
result = makeup_encoder.generate(
|
| 146 |
+
id_image=[id_image_resized, pose_image],
|
| 147 |
+
makeup_image=makeup_image_resized,
|
| 148 |
+
guidance_scale=guidance_scale,
|
| 149 |
+
pipe=pipeline,
|
| 150 |
+
)
|
| 151 |
+
return result
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# ═══════════════════════════════════════════════════════════
|
| 155 |
+
# Gradio UI
|
| 156 |
+
# ═══════════════════════════════════════════════════════════
|
| 157 |
+
|
| 158 |
+
with gr.Blocks(title="Stable-Makeup 妆容迁移") as demo:
|
| 159 |
+
gr.Markdown("""
|
| 160 |
+
# 💄 Stable-Makeup · 妆容迁移
|
| 161 |
+
上传素颜照 + 参考妆容图,AI 将妆容迁移到你的照片上。
|
| 162 |
+
基于 [Stable-Makeup](https://arxiv.org/abs/2403.07764) (arXiv 2403.07764)
|
| 163 |
+
""")
|
| 164 |
+
with gr.Row():
|
| 165 |
+
with gr.Column():
|
| 166 |
+
id_img = gr.Image(label="素颜照", type="pil", height=400)
|
| 167 |
+
with gr.Column():
|
| 168 |
+
makeup_img = gr.Image(label="参考妆容", type="pil", height=400)
|
| 169 |
+
|
| 170 |
+
guidance = gr.Slider(
|
| 171 |
+
minimum=1.01, maximum=3.0, value=1.6, step=0.05,
|
| 172 |
+
label="妆容浓度 (guidance_scale)",
|
| 173 |
+
info="淡妆建议 1.05-1.15,浓妆建议 2.0"
|
| 174 |
+
)
|
| 175 |
+
btn = gr.Button("开始试妆", variant="primary")
|
| 176 |
+
output = gr.Image(label="试妆结果", type="pil")
|
| 177 |
+
|
| 178 |
+
btn.click(
|
| 179 |
+
fn=makeup_transfer,
|
| 180 |
+
inputs=[id_img, makeup_img, guidance],
|
| 181 |
+
outputs=output,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
demo.queue(max_size=10).launch()
|
detail_encoder/__init__.py
ADDED
|
File without changes
|
detail_encoder/_clip.py
ADDED
|
@@ -0,0 +1,1349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The OpenAI Team Authors and 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 |
+
""" PyTorch CLIP model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.utils.checkpoint
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from transformers.activations import ACT2FN
|
| 26 |
+
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
|
| 27 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 28 |
+
from transformers.utils import (
|
| 29 |
+
ModelOutput,
|
| 30 |
+
add_start_docstrings,
|
| 31 |
+
add_start_docstrings_to_model_forward,
|
| 32 |
+
logging,
|
| 33 |
+
replace_return_docstrings,
|
| 34 |
+
)
|
| 35 |
+
from transformers.models.clip.configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
logger = logging.get_logger(__name__)
|
| 39 |
+
|
| 40 |
+
_CHECKPOINT_FOR_DOC = "openai/clip-vit-base-patch32"
|
| 41 |
+
|
| 42 |
+
CLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 43 |
+
"openai/clip-vit-base-patch32",
|
| 44 |
+
# See all CLIP models at https://huggingface.co/models?filter=clip
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
| 49 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 50 |
+
"""
|
| 51 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 52 |
+
"""
|
| 53 |
+
bsz, src_len = mask.size()
|
| 54 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 55 |
+
|
| 56 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 57 |
+
|
| 58 |
+
inverted_mask = 1.0 - expanded_mask
|
| 59 |
+
|
| 60 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# contrastive loss function, adapted from
|
| 64 |
+
# https://sachinruk.github.io/blog/2021-03-07-clip.html
|
| 65 |
+
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
|
| 66 |
+
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def clip_loss(similarity: torch.Tensor) -> torch.Tensor:
|
| 70 |
+
caption_loss = contrastive_loss(similarity)
|
| 71 |
+
image_loss = contrastive_loss(similarity.t())
|
| 72 |
+
return (caption_loss + image_loss) / 2.0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass
|
| 76 |
+
class CLIPVisionModelOutput(ModelOutput):
|
| 77 |
+
"""
|
| 78 |
+
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 82 |
+
The image embeddings obtained by applying the projection layer to the pooler_output.
|
| 83 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 84 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 85 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 86 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 87 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 88 |
+
|
| 89 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 90 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 91 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 92 |
+
sequence_length)`.
|
| 93 |
+
|
| 94 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 95 |
+
heads.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
image_embeds: Optional[torch.FloatTensor] = None
|
| 99 |
+
last_hidden_state: torch.FloatTensor = None
|
| 100 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 101 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@dataclass
|
| 105 |
+
class CLIPTextModelOutput(ModelOutput):
|
| 106 |
+
"""
|
| 107 |
+
Base class for text model's outputs that also contains a pooling of the last hidden states.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
|
| 111 |
+
The text embeddings obtained by applying the projection layer to the pooler_output.
|
| 112 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 113 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 114 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 115 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 116 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 117 |
+
|
| 118 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 119 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 120 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 121 |
+
sequence_length)`.
|
| 122 |
+
|
| 123 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 124 |
+
heads.
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
text_embeds: Optional[torch.FloatTensor] = None
|
| 128 |
+
last_hidden_state: torch.FloatTensor = None
|
| 129 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 130 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@dataclass
|
| 134 |
+
class CLIPOutput(ModelOutput):
|
| 135 |
+
"""
|
| 136 |
+
Args:
|
| 137 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
|
| 138 |
+
Contrastive loss for image-text similarity.
|
| 139 |
+
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
|
| 140 |
+
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
|
| 141 |
+
similarity scores.
|
| 142 |
+
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
|
| 143 |
+
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
|
| 144 |
+
similarity scores.
|
| 145 |
+
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 146 |
+
The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPTextModel`].
|
| 147 |
+
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
|
| 148 |
+
The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`].
|
| 149 |
+
text_model_output(`BaseModelOutputWithPooling`):
|
| 150 |
+
The output of the [`CLIPTextModel`].
|
| 151 |
+
vision_model_output(`BaseModelOutputWithPooling`):
|
| 152 |
+
The output of the [`CLIPVisionModel`].
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
loss: Optional[torch.FloatTensor] = None
|
| 156 |
+
logits_per_image: torch.FloatTensor = None
|
| 157 |
+
logits_per_text: torch.FloatTensor = None
|
| 158 |
+
text_embeds: torch.FloatTensor = None
|
| 159 |
+
image_embeds: torch.FloatTensor = None
|
| 160 |
+
text_model_output: BaseModelOutputWithPooling = None
|
| 161 |
+
vision_model_output: BaseModelOutputWithPooling = None
|
| 162 |
+
|
| 163 |
+
def to_tuple(self) -> Tuple[Any]:
|
| 164 |
+
return tuple(
|
| 165 |
+
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
|
| 166 |
+
for k in self.keys()
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class CLIPVisionEmbeddings(nn.Module):
|
| 171 |
+
def __init__(self, config: CLIPVisionConfig):
|
| 172 |
+
super().__init__()
|
| 173 |
+
self.config = config
|
| 174 |
+
self.embed_dim = config.hidden_size
|
| 175 |
+
self.image_size = config.image_size
|
| 176 |
+
self.patch_size = config.patch_size
|
| 177 |
+
|
| 178 |
+
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
|
| 179 |
+
|
| 180 |
+
self.patch_embedding = nn.Conv2d(
|
| 181 |
+
in_channels=config.num_channels,
|
| 182 |
+
out_channels=self.embed_dim,
|
| 183 |
+
kernel_size=self.patch_size,
|
| 184 |
+
stride=self.patch_size,
|
| 185 |
+
bias=False,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
self.num_patches = (self.image_size // self.patch_size) ** 2
|
| 189 |
+
self.num_positions = self.num_patches + 1
|
| 190 |
+
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
|
| 191 |
+
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
|
| 192 |
+
|
| 193 |
+
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
|
| 194 |
+
batch_size = pixel_values.shape[0]
|
| 195 |
+
target_dtype = self.patch_embedding.weight.dtype
|
| 196 |
+
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
|
| 197 |
+
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
|
| 198 |
+
|
| 199 |
+
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
|
| 200 |
+
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
|
| 201 |
+
embeddings = embeddings + self.position_embedding(self.position_ids)
|
| 202 |
+
return embeddings
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class CLIPTextEmbeddings(nn.Module):
|
| 206 |
+
def __init__(self, config: CLIPTextConfig):
|
| 207 |
+
super().__init__()
|
| 208 |
+
embed_dim = config.hidden_size
|
| 209 |
+
|
| 210 |
+
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
|
| 211 |
+
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
|
| 212 |
+
|
| 213 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
| 214 |
+
self.register_buffer(
|
| 215 |
+
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
def forward(
|
| 219 |
+
self,
|
| 220 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 221 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 222 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 223 |
+
) -> torch.Tensor:
|
| 224 |
+
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
|
| 225 |
+
|
| 226 |
+
if position_ids is None:
|
| 227 |
+
position_ids = self.position_ids[:, :seq_length]
|
| 228 |
+
|
| 229 |
+
if inputs_embeds is None:
|
| 230 |
+
inputs_embeds = self.token_embedding(input_ids)
|
| 231 |
+
|
| 232 |
+
position_embeddings = self.position_embedding(position_ids)
|
| 233 |
+
embeddings = inputs_embeds + position_embeddings
|
| 234 |
+
|
| 235 |
+
return embeddings
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class CLIPAttention(nn.Module):
|
| 239 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 240 |
+
|
| 241 |
+
def __init__(self, config):
|
| 242 |
+
super().__init__()
|
| 243 |
+
self.config = config
|
| 244 |
+
self.embed_dim = config.hidden_size
|
| 245 |
+
self.num_heads = config.num_attention_heads
|
| 246 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 247 |
+
if self.head_dim * self.num_heads != self.embed_dim:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
|
| 250 |
+
f" {self.num_heads})."
|
| 251 |
+
)
|
| 252 |
+
self.scale = self.head_dim**-0.5
|
| 253 |
+
self.dropout = config.attention_dropout
|
| 254 |
+
|
| 255 |
+
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 256 |
+
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 257 |
+
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 258 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
|
| 259 |
+
|
| 260 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 261 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 262 |
+
|
| 263 |
+
def forward(
|
| 264 |
+
self,
|
| 265 |
+
hidden_states: torch.Tensor,
|
| 266 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 267 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 268 |
+
output_attentions: Optional[bool] = False,
|
| 269 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 270 |
+
"""Input shape: Batch x Time x Channel"""
|
| 271 |
+
|
| 272 |
+
bsz, tgt_len, embed_dim = hidden_states.size()
|
| 273 |
+
|
| 274 |
+
# get query proj
|
| 275 |
+
query_states = self.q_proj(hidden_states) * self.scale
|
| 276 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 277 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 278 |
+
|
| 279 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 280 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 281 |
+
key_states = key_states.view(*proj_shape)
|
| 282 |
+
value_states = value_states.view(*proj_shape)
|
| 283 |
+
|
| 284 |
+
src_len = key_states.size(1)
|
| 285 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 286 |
+
|
| 287 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 288 |
+
raise ValueError(
|
| 289 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
|
| 290 |
+
f" {attn_weights.size()}"
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
# apply the causal_attention_mask first
|
| 294 |
+
if causal_attention_mask is not None:
|
| 295 |
+
if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 296 |
+
raise ValueError(
|
| 297 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
|
| 298 |
+
f" {causal_attention_mask.size()}"
|
| 299 |
+
)
|
| 300 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
|
| 301 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 302 |
+
|
| 303 |
+
if attention_mask is not None:
|
| 304 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 305 |
+
raise ValueError(
|
| 306 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 307 |
+
)
|
| 308 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 309 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 310 |
+
|
| 311 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 312 |
+
|
| 313 |
+
if output_attentions:
|
| 314 |
+
# this operation is a bit akward, but it's required to
|
| 315 |
+
# make sure that attn_weights keeps its gradient.
|
| 316 |
+
# In order to do so, attn_weights have to reshaped
|
| 317 |
+
# twice and have to be reused in the following
|
| 318 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 319 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 320 |
+
else:
|
| 321 |
+
attn_weights_reshaped = None
|
| 322 |
+
|
| 323 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 324 |
+
|
| 325 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 326 |
+
|
| 327 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 328 |
+
raise ValueError(
|
| 329 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
|
| 330 |
+
f" {attn_output.size()}"
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 334 |
+
attn_output = attn_output.transpose(1, 2)
|
| 335 |
+
attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
|
| 336 |
+
|
| 337 |
+
attn_output = self.out_proj(attn_output)
|
| 338 |
+
|
| 339 |
+
return attn_output, attn_weights_reshaped
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class CLIPMLP(nn.Module):
|
| 343 |
+
def __init__(self, config):
|
| 344 |
+
super().__init__()
|
| 345 |
+
self.config = config
|
| 346 |
+
self.activation_fn = ACT2FN[config.hidden_act]
|
| 347 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 348 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 349 |
+
|
| 350 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 351 |
+
hidden_states = self.fc1(hidden_states)
|
| 352 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 353 |
+
hidden_states = self.fc2(hidden_states)
|
| 354 |
+
return hidden_states
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class CLIPEncoderLayer(nn.Module):
|
| 358 |
+
def __init__(self, config: CLIPConfig):
|
| 359 |
+
super().__init__()
|
| 360 |
+
self.embed_dim = config.hidden_size
|
| 361 |
+
self.self_attn = CLIPAttention(config)
|
| 362 |
+
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 363 |
+
self.mlp = CLIPMLP(config)
|
| 364 |
+
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
|
| 365 |
+
|
| 366 |
+
def forward(
|
| 367 |
+
self,
|
| 368 |
+
hidden_states: torch.Tensor,
|
| 369 |
+
attention_mask: torch.Tensor,
|
| 370 |
+
causal_attention_mask: torch.Tensor,
|
| 371 |
+
output_attentions: Optional[bool] = False,
|
| 372 |
+
) -> Tuple[torch.FloatTensor]:
|
| 373 |
+
"""
|
| 374 |
+
Args:
|
| 375 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 376 |
+
attention_mask (`torch.FloatTensor`): attention mask of size
|
| 377 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 378 |
+
`(config.encoder_attention_heads,)`.
|
| 379 |
+
output_attentions (`bool`, *optional*):
|
| 380 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 381 |
+
returned tensors for more detail.
|
| 382 |
+
"""
|
| 383 |
+
residual = hidden_states
|
| 384 |
+
|
| 385 |
+
hidden_states = self.layer_norm1(hidden_states)
|
| 386 |
+
hidden_states, attn_weights = self.self_attn(
|
| 387 |
+
hidden_states=hidden_states,
|
| 388 |
+
attention_mask=attention_mask,
|
| 389 |
+
causal_attention_mask=causal_attention_mask,
|
| 390 |
+
output_attentions=output_attentions,
|
| 391 |
+
)
|
| 392 |
+
hidden_states = residual + hidden_states
|
| 393 |
+
|
| 394 |
+
residual = hidden_states
|
| 395 |
+
hidden_states = self.layer_norm2(hidden_states)
|
| 396 |
+
hidden_states = self.mlp(hidden_states)
|
| 397 |
+
hidden_states = residual + hidden_states
|
| 398 |
+
|
| 399 |
+
outputs = (hidden_states,)
|
| 400 |
+
|
| 401 |
+
if output_attentions:
|
| 402 |
+
outputs += (attn_weights,)
|
| 403 |
+
|
| 404 |
+
return outputs
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class CLIPPreTrainedModel(PreTrainedModel):
|
| 408 |
+
"""
|
| 409 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 410 |
+
models.
|
| 411 |
+
"""
|
| 412 |
+
|
| 413 |
+
config_class = CLIPConfig
|
| 414 |
+
base_model_prefix = "clip"
|
| 415 |
+
supports_gradient_checkpointing = True
|
| 416 |
+
|
| 417 |
+
def _init_weights(self, module):
|
| 418 |
+
"""Initialize the weights"""
|
| 419 |
+
factor = self.config.initializer_factor
|
| 420 |
+
if isinstance(module, CLIPTextEmbeddings):
|
| 421 |
+
module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
| 422 |
+
module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
|
| 423 |
+
elif isinstance(module, CLIPVisionEmbeddings):
|
| 424 |
+
factor = self.config.initializer_factor
|
| 425 |
+
nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
|
| 426 |
+
nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
|
| 427 |
+
nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
|
| 428 |
+
elif isinstance(module, CLIPAttention):
|
| 429 |
+
factor = self.config.initializer_factor
|
| 430 |
+
in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 431 |
+
out_proj_std = (module.embed_dim**-0.5) * factor
|
| 432 |
+
nn.init.normal_(module.q_proj.weight, std=in_proj_std)
|
| 433 |
+
nn.init.normal_(module.k_proj.weight, std=in_proj_std)
|
| 434 |
+
nn.init.normal_(module.v_proj.weight, std=in_proj_std)
|
| 435 |
+
nn.init.normal_(module.out_proj.weight, std=out_proj_std)
|
| 436 |
+
elif isinstance(module, CLIPMLP):
|
| 437 |
+
factor = self.config.initializer_factor
|
| 438 |
+
in_proj_std = (
|
| 439 |
+
(module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
|
| 440 |
+
)
|
| 441 |
+
fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
|
| 442 |
+
nn.init.normal_(module.fc1.weight, std=fc_std)
|
| 443 |
+
nn.init.normal_(module.fc2.weight, std=in_proj_std)
|
| 444 |
+
elif isinstance(module, CLIPModel):
|
| 445 |
+
nn.init.normal_(
|
| 446 |
+
module.text_projection.weight,
|
| 447 |
+
std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
|
| 448 |
+
)
|
| 449 |
+
nn.init.normal_(
|
| 450 |
+
module.visual_projection.weight,
|
| 451 |
+
std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
|
| 452 |
+
)
|
| 453 |
+
elif isinstance(module, CLIPVisionModelWithProjection):
|
| 454 |
+
nn.init.normal_(
|
| 455 |
+
module.visual_projection.weight,
|
| 456 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
| 457 |
+
)
|
| 458 |
+
elif isinstance(module, CLIPTextModelWithProjection):
|
| 459 |
+
nn.init.normal_(
|
| 460 |
+
module.text_projection.weight,
|
| 461 |
+
std=self.config.hidden_size**-0.5 * self.config.initializer_factor,
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
if isinstance(module, nn.LayerNorm):
|
| 465 |
+
module.bias.data.zero_()
|
| 466 |
+
module.weight.data.fill_(1.0)
|
| 467 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 468 |
+
module.bias.data.zero_()
|
| 469 |
+
|
| 470 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 471 |
+
if isinstance(module, CLIPEncoder):
|
| 472 |
+
module.gradient_checkpointing = value
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
CLIP_START_DOCSTRING = r"""
|
| 476 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 477 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 478 |
+
etc.)
|
| 479 |
+
|
| 480 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 481 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 482 |
+
and behavior.
|
| 483 |
+
|
| 484 |
+
Parameters:
|
| 485 |
+
config ([`CLIPConfig`]): Model configuration class with all the parameters of the model.
|
| 486 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 487 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 488 |
+
"""
|
| 489 |
+
|
| 490 |
+
CLIP_TEXT_INPUTS_DOCSTRING = r"""
|
| 491 |
+
Args:
|
| 492 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 493 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 494 |
+
it.
|
| 495 |
+
|
| 496 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 497 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 498 |
+
|
| 499 |
+
[What are input IDs?](../glossary#input-ids)
|
| 500 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 501 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 502 |
+
|
| 503 |
+
- 1 for tokens that are **not masked**,
|
| 504 |
+
- 0 for tokens that are **masked**.
|
| 505 |
+
|
| 506 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 507 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 508 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 509 |
+
config.max_position_embeddings - 1]`.
|
| 510 |
+
|
| 511 |
+
[What are position IDs?](../glossary#position-ids)
|
| 512 |
+
output_attentions (`bool`, *optional*):
|
| 513 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 514 |
+
tensors for more detail.
|
| 515 |
+
output_hidden_states (`bool`, *optional*):
|
| 516 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 517 |
+
more detail.
|
| 518 |
+
return_dict (`bool`, *optional*):
|
| 519 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 520 |
+
"""
|
| 521 |
+
|
| 522 |
+
CLIP_VISION_INPUTS_DOCSTRING = r"""
|
| 523 |
+
Args:
|
| 524 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 525 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 526 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 527 |
+
output_attentions (`bool`, *optional*):
|
| 528 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 529 |
+
tensors for more detail.
|
| 530 |
+
output_hidden_states (`bool`, *optional*):
|
| 531 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 532 |
+
more detail.
|
| 533 |
+
return_dict (`bool`, *optional*):
|
| 534 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
CLIP_INPUTS_DOCSTRING = r"""
|
| 538 |
+
Args:
|
| 539 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 540 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 541 |
+
it.
|
| 542 |
+
|
| 543 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 544 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 545 |
+
|
| 546 |
+
[What are input IDs?](../glossary#input-ids)
|
| 547 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 548 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 549 |
+
|
| 550 |
+
- 1 for tokens that are **not masked**,
|
| 551 |
+
- 0 for tokens that are **masked**.
|
| 552 |
+
|
| 553 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 554 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 555 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 556 |
+
config.max_position_embeddings - 1]`.
|
| 557 |
+
|
| 558 |
+
[What are position IDs?](../glossary#position-ids)
|
| 559 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 560 |
+
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
|
| 561 |
+
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
|
| 562 |
+
return_loss (`bool`, *optional*):
|
| 563 |
+
Whether or not to return the contrastive loss.
|
| 564 |
+
output_attentions (`bool`, *optional*):
|
| 565 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 566 |
+
tensors for more detail.
|
| 567 |
+
output_hidden_states (`bool`, *optional*):
|
| 568 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 569 |
+
more detail.
|
| 570 |
+
return_dict (`bool`, *optional*):
|
| 571 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 572 |
+
"""
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
class CLIPEncoder(nn.Module):
|
| 576 |
+
"""
|
| 577 |
+
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
|
| 578 |
+
[`CLIPEncoderLayer`].
|
| 579 |
+
|
| 580 |
+
Args:
|
| 581 |
+
config: CLIPConfig
|
| 582 |
+
"""
|
| 583 |
+
|
| 584 |
+
def __init__(self, config: CLIPConfig):
|
| 585 |
+
super().__init__()
|
| 586 |
+
self.config = config
|
| 587 |
+
self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 588 |
+
self.gradient_checkpointing = False
|
| 589 |
+
|
| 590 |
+
def forward(
|
| 591 |
+
self,
|
| 592 |
+
inputs_embeds,
|
| 593 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 594 |
+
causal_attention_mask: Optional[torch.Tensor] = None,
|
| 595 |
+
output_attentions: Optional[bool] = None,
|
| 596 |
+
output_hidden_states: Optional[bool] = None,
|
| 597 |
+
return_dict: Optional[bool] = None,
|
| 598 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 599 |
+
r"""
|
| 600 |
+
Args:
|
| 601 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 602 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
|
| 603 |
+
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
|
| 604 |
+
than the model's internal embedding lookup matrix.
|
| 605 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 606 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 607 |
+
|
| 608 |
+
- 1 for tokens that are **not masked**,
|
| 609 |
+
- 0 for tokens that are **masked**.
|
| 610 |
+
|
| 611 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 612 |
+
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 613 |
+
Causal mask for the text model. Mask values selected in `[0, 1]`:
|
| 614 |
+
|
| 615 |
+
- 1 for tokens that are **not masked**,
|
| 616 |
+
- 0 for tokens that are **masked**.
|
| 617 |
+
|
| 618 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 619 |
+
output_attentions (`bool`, *optional*):
|
| 620 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 621 |
+
returned tensors for more detail.
|
| 622 |
+
output_hidden_states (`bool`, *optional*):
|
| 623 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
|
| 624 |
+
for more detail.
|
| 625 |
+
return_dict (`bool`, *optional*):
|
| 626 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 627 |
+
"""
|
| 628 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 629 |
+
output_hidden_states = (
|
| 630 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 631 |
+
)
|
| 632 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 633 |
+
|
| 634 |
+
encoder_states = () if output_hidden_states else None
|
| 635 |
+
all_attentions = () if output_attentions else None
|
| 636 |
+
|
| 637 |
+
hidden_states = inputs_embeds
|
| 638 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 639 |
+
if output_hidden_states:
|
| 640 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 641 |
+
if self.gradient_checkpointing and self.training:
|
| 642 |
+
|
| 643 |
+
def create_custom_forward(module):
|
| 644 |
+
def custom_forward(*inputs):
|
| 645 |
+
return module(*inputs, output_attentions)
|
| 646 |
+
|
| 647 |
+
return custom_forward
|
| 648 |
+
|
| 649 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 650 |
+
create_custom_forward(encoder_layer),
|
| 651 |
+
hidden_states,
|
| 652 |
+
attention_mask,
|
| 653 |
+
causal_attention_mask,
|
| 654 |
+
)
|
| 655 |
+
else:
|
| 656 |
+
layer_outputs = encoder_layer(
|
| 657 |
+
hidden_states,
|
| 658 |
+
attention_mask,
|
| 659 |
+
causal_attention_mask,
|
| 660 |
+
output_attentions=output_attentions,
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
hidden_states = layer_outputs[0]
|
| 664 |
+
|
| 665 |
+
if output_attentions:
|
| 666 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 667 |
+
|
| 668 |
+
if output_hidden_states:
|
| 669 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 670 |
+
|
| 671 |
+
if not return_dict:
|
| 672 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 673 |
+
return BaseModelOutput(
|
| 674 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
| 679 |
+
def _make_causal_mask(
|
| 680 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
| 681 |
+
):
|
| 682 |
+
"""
|
| 683 |
+
Make causal mask used for bi-directional self-attention.
|
| 684 |
+
"""
|
| 685 |
+
bsz, tgt_len = input_ids_shape
|
| 686 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
| 687 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
| 688 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
| 689 |
+
mask = mask.to(dtype)
|
| 690 |
+
|
| 691 |
+
if past_key_values_length > 0:
|
| 692 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
| 693 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class CLIPTextTransformer(nn.Module):
|
| 697 |
+
def __init__(self, config: CLIPTextConfig):
|
| 698 |
+
super().__init__()
|
| 699 |
+
self.config = config
|
| 700 |
+
embed_dim = config.hidden_size
|
| 701 |
+
self.embeddings = CLIPTextEmbeddings(config)
|
| 702 |
+
self.encoder = CLIPEncoder(config)
|
| 703 |
+
self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 704 |
+
|
| 705 |
+
# For `pooled_output` computation
|
| 706 |
+
self.eos_token_id = config.eos_token_id
|
| 707 |
+
|
| 708 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
| 709 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
|
| 710 |
+
def forward(
|
| 711 |
+
self,
|
| 712 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 713 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 714 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 715 |
+
output_attentions: Optional[bool] = None,
|
| 716 |
+
output_hidden_states: Optional[bool] = None,
|
| 717 |
+
return_dict: Optional[bool] = None,
|
| 718 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 719 |
+
r"""
|
| 720 |
+
Returns:
|
| 721 |
+
|
| 722 |
+
"""
|
| 723 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 724 |
+
output_hidden_states = (
|
| 725 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 726 |
+
)
|
| 727 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 728 |
+
|
| 729 |
+
if input_ids is None:
|
| 730 |
+
raise ValueError("You have to specify input_ids")
|
| 731 |
+
|
| 732 |
+
input_shape = input_ids.size()
|
| 733 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 734 |
+
|
| 735 |
+
hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
|
| 736 |
+
|
| 737 |
+
# CLIP's text model uses causal mask, prepare it here.
|
| 738 |
+
# https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
|
| 739 |
+
causal_attention_mask = _make_causal_mask(input_shape, hidden_states.dtype, device=hidden_states.device)
|
| 740 |
+
# expand attention_mask
|
| 741 |
+
if attention_mask is not None:
|
| 742 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 743 |
+
attention_mask = _expand_mask(attention_mask, hidden_states.dtype)
|
| 744 |
+
|
| 745 |
+
encoder_outputs = self.encoder(
|
| 746 |
+
inputs_embeds=hidden_states,
|
| 747 |
+
attention_mask=attention_mask,
|
| 748 |
+
causal_attention_mask=causal_attention_mask,
|
| 749 |
+
output_attentions=output_attentions,
|
| 750 |
+
output_hidden_states=output_hidden_states,
|
| 751 |
+
return_dict=return_dict,
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
last_hidden_state = encoder_outputs[0]
|
| 755 |
+
last_hidden_state = self.final_layer_norm(last_hidden_state)
|
| 756 |
+
|
| 757 |
+
if self.eos_token_id == 2:
|
| 758 |
+
# The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
|
| 759 |
+
# A CLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added
|
| 760 |
+
# ------------------------------------------------------------
|
| 761 |
+
# text_embeds.shape = [batch_size, sequence_length, transformer.width]
|
| 762 |
+
# take features from the eot embedding (eot_token is the highest number in each sequence)
|
| 763 |
+
# casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
|
| 764 |
+
pooled_output = last_hidden_state[
|
| 765 |
+
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
|
| 766 |
+
input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
|
| 767 |
+
]
|
| 768 |
+
else:
|
| 769 |
+
# The config gets updated `eos_token_id` from PR #24773 (so the use of exta new tokens is possible)
|
| 770 |
+
pooled_output = last_hidden_state[
|
| 771 |
+
torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
|
| 772 |
+
# We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`)
|
| 773 |
+
(input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id)
|
| 774 |
+
.int()
|
| 775 |
+
.argmax(dim=-1),
|
| 776 |
+
]
|
| 777 |
+
|
| 778 |
+
if not return_dict:
|
| 779 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 780 |
+
|
| 781 |
+
return BaseModelOutputWithPooling(
|
| 782 |
+
last_hidden_state=last_hidden_state,
|
| 783 |
+
pooler_output=pooled_output,
|
| 784 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 785 |
+
attentions=encoder_outputs.attentions,
|
| 786 |
+
)
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
@add_start_docstrings(
|
| 790 |
+
"""The text model from CLIP without any head or projection on top.""",
|
| 791 |
+
CLIP_START_DOCSTRING,
|
| 792 |
+
)
|
| 793 |
+
class CLIPTextModel(CLIPPreTrainedModel):
|
| 794 |
+
config_class = CLIPTextConfig
|
| 795 |
+
|
| 796 |
+
_no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
|
| 797 |
+
|
| 798 |
+
def __init__(self, config: CLIPTextConfig):
|
| 799 |
+
super().__init__(config)
|
| 800 |
+
self.text_model = CLIPTextTransformer(config)
|
| 801 |
+
# Initialize weights and apply final processing
|
| 802 |
+
self.post_init()
|
| 803 |
+
|
| 804 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 805 |
+
return self.text_model.embeddings.token_embedding
|
| 806 |
+
|
| 807 |
+
def set_input_embeddings(self, value):
|
| 808 |
+
self.text_model.embeddings.token_embedding = value
|
| 809 |
+
|
| 810 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
| 811 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPTextConfig)
|
| 812 |
+
def forward(
|
| 813 |
+
self,
|
| 814 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 815 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 816 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 817 |
+
output_attentions: Optional[bool] = None,
|
| 818 |
+
output_hidden_states: Optional[bool] = None,
|
| 819 |
+
return_dict: Optional[bool] = None,
|
| 820 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 821 |
+
r"""
|
| 822 |
+
Returns:
|
| 823 |
+
|
| 824 |
+
Examples:
|
| 825 |
+
|
| 826 |
+
```python
|
| 827 |
+
>>> from transformers import AutoTokenizer, CLIPTextModel
|
| 828 |
+
|
| 829 |
+
>>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 830 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
| 831 |
+
|
| 832 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 833 |
+
|
| 834 |
+
>>> outputs = model(**inputs)
|
| 835 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 836 |
+
>>> pooled_output = outputs.pooler_output # pooled (EOS token) states
|
| 837 |
+
```"""
|
| 838 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 839 |
+
|
| 840 |
+
return self.text_model(
|
| 841 |
+
input_ids=input_ids,
|
| 842 |
+
attention_mask=attention_mask,
|
| 843 |
+
position_ids=position_ids,
|
| 844 |
+
output_attentions=output_attentions,
|
| 845 |
+
output_hidden_states=output_hidden_states,
|
| 846 |
+
return_dict=return_dict,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
class CLIPVisionTransformer(nn.Module):
|
| 851 |
+
def __init__(self, config: CLIPVisionConfig):
|
| 852 |
+
super().__init__()
|
| 853 |
+
self.config = config
|
| 854 |
+
embed_dim = config.hidden_size
|
| 855 |
+
|
| 856 |
+
self.embeddings = CLIPVisionEmbeddings(config)
|
| 857 |
+
self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
|
| 858 |
+
self.encoder = CLIPEncoder(config)
|
| 859 |
+
self.post_layernorm = None
|
| 860 |
+
|
| 861 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
| 862 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
|
| 863 |
+
def forward(
|
| 864 |
+
self,
|
| 865 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 866 |
+
output_attentions: Optional[bool] = None,
|
| 867 |
+
output_hidden_states: Optional[bool] = None,
|
| 868 |
+
return_dict: Optional[bool] = None,
|
| 869 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 870 |
+
r"""
|
| 871 |
+
Returns:
|
| 872 |
+
|
| 873 |
+
"""
|
| 874 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 875 |
+
output_hidden_states = (
|
| 876 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 877 |
+
)
|
| 878 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 879 |
+
|
| 880 |
+
if pixel_values is None:
|
| 881 |
+
raise ValueError("You have to specify pixel_values")
|
| 882 |
+
|
| 883 |
+
hidden_states = self.embeddings(pixel_values)
|
| 884 |
+
hidden_states = self.pre_layrnorm(hidden_states)
|
| 885 |
+
|
| 886 |
+
encoder_outputs = self.encoder(
|
| 887 |
+
inputs_embeds=hidden_states,
|
| 888 |
+
output_attentions=output_attentions,
|
| 889 |
+
output_hidden_states=output_hidden_states,
|
| 890 |
+
return_dict=return_dict,
|
| 891 |
+
)
|
| 892 |
+
|
| 893 |
+
last_hidden_state = encoder_outputs[0]
|
| 894 |
+
# pooled_output = last_hidden_state[:, 0, :]
|
| 895 |
+
# pooled_output = self.post_layernorm(pooled_output)
|
| 896 |
+
pooled_output = None
|
| 897 |
+
|
| 898 |
+
if not return_dict:
|
| 899 |
+
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
|
| 900 |
+
|
| 901 |
+
return BaseModelOutputWithPooling(
|
| 902 |
+
last_hidden_state=last_hidden_state,
|
| 903 |
+
pooler_output=pooled_output,
|
| 904 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 905 |
+
attentions=encoder_outputs.attentions,
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
@add_start_docstrings(
|
| 910 |
+
"""The vision model from CLIP without any head or projection on top.""",
|
| 911 |
+
CLIP_START_DOCSTRING,
|
| 912 |
+
)
|
| 913 |
+
class CLIPVisionModel(CLIPPreTrainedModel):
|
| 914 |
+
config_class = CLIPVisionConfig
|
| 915 |
+
main_input_name = "pixel_values"
|
| 916 |
+
|
| 917 |
+
def __init__(self, config: CLIPVisionConfig):
|
| 918 |
+
super().__init__(config)
|
| 919 |
+
self.vision_model = CLIPVisionTransformer(config)
|
| 920 |
+
# Initialize weights and apply final processing
|
| 921 |
+
self.post_init()
|
| 922 |
+
|
| 923 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 924 |
+
return self.vision_model.embeddings.patch_embedding
|
| 925 |
+
|
| 926 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
| 927 |
+
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPVisionConfig)
|
| 928 |
+
def forward(
|
| 929 |
+
self,
|
| 930 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 931 |
+
output_attentions: Optional[bool] = None,
|
| 932 |
+
output_hidden_states: Optional[bool] = None,
|
| 933 |
+
return_dict: Optional[bool] = None,
|
| 934 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 935 |
+
r"""
|
| 936 |
+
Returns:
|
| 937 |
+
|
| 938 |
+
Examples:
|
| 939 |
+
|
| 940 |
+
```python
|
| 941 |
+
>>> from PIL import Image
|
| 942 |
+
>>> import requests
|
| 943 |
+
>>> from transformers import AutoProcessor, CLIPVisionModel
|
| 944 |
+
|
| 945 |
+
>>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 946 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 947 |
+
|
| 948 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 949 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 950 |
+
|
| 951 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 952 |
+
|
| 953 |
+
>>> outputs = model(**inputs)
|
| 954 |
+
>>> last_hidden_state = outputs.last_hidden_state
|
| 955 |
+
>>> pooled_output = outputs.pooler_output # pooled CLS states
|
| 956 |
+
```"""
|
| 957 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 958 |
+
|
| 959 |
+
return self.vision_model(
|
| 960 |
+
pixel_values=pixel_values,
|
| 961 |
+
output_attentions=output_attentions,
|
| 962 |
+
output_hidden_states=output_hidden_states,
|
| 963 |
+
return_dict=return_dict,
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
@add_start_docstrings(CLIP_START_DOCSTRING)
|
| 968 |
+
class CLIPModel(CLIPPreTrainedModel):
|
| 969 |
+
config_class = CLIPConfig
|
| 970 |
+
|
| 971 |
+
def __init__(self, config: CLIPConfig):
|
| 972 |
+
super().__init__(config)
|
| 973 |
+
|
| 974 |
+
if not isinstance(config.text_config, CLIPTextConfig):
|
| 975 |
+
raise ValueError(
|
| 976 |
+
"config.text_config is expected to be of type CLIPTextConfig but is of type"
|
| 977 |
+
f" {type(config.text_config)}."
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
if not isinstance(config.vision_config, CLIPVisionConfig):
|
| 981 |
+
raise ValueError(
|
| 982 |
+
"config.vision_config is expected to be of type CLIPVisionConfig but is of type"
|
| 983 |
+
f" {type(config.vision_config)}."
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
text_config = config.text_config
|
| 987 |
+
vision_config = config.vision_config
|
| 988 |
+
|
| 989 |
+
self.projection_dim = config.projection_dim
|
| 990 |
+
self.text_embed_dim = text_config.hidden_size
|
| 991 |
+
self.vision_embed_dim = vision_config.hidden_size
|
| 992 |
+
|
| 993 |
+
self.text_model = CLIPTextTransformer(text_config)
|
| 994 |
+
self.vision_model = CLIPVisionTransformer(vision_config)
|
| 995 |
+
|
| 996 |
+
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
|
| 997 |
+
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
|
| 998 |
+
self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
|
| 999 |
+
|
| 1000 |
+
# Initialize weights and apply final processing
|
| 1001 |
+
self.post_init()
|
| 1002 |
+
|
| 1003 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
| 1004 |
+
def get_text_features(
|
| 1005 |
+
self,
|
| 1006 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1007 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1008 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1009 |
+
output_attentions: Optional[bool] = None,
|
| 1010 |
+
output_hidden_states: Optional[bool] = None,
|
| 1011 |
+
return_dict: Optional[bool] = None,
|
| 1012 |
+
) -> torch.FloatTensor:
|
| 1013 |
+
r"""
|
| 1014 |
+
Returns:
|
| 1015 |
+
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
|
| 1016 |
+
applying the projection layer to the pooled output of [`CLIPTextModel`].
|
| 1017 |
+
|
| 1018 |
+
Examples:
|
| 1019 |
+
|
| 1020 |
+
```python
|
| 1021 |
+
>>> from transformers import AutoTokenizer, CLIPModel
|
| 1022 |
+
|
| 1023 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 1024 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
| 1025 |
+
|
| 1026 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1027 |
+
>>> text_features = model.get_text_features(**inputs)
|
| 1028 |
+
```"""
|
| 1029 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1030 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1031 |
+
output_hidden_states = (
|
| 1032 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1033 |
+
)
|
| 1034 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1035 |
+
|
| 1036 |
+
text_outputs = self.text_model(
|
| 1037 |
+
input_ids=input_ids,
|
| 1038 |
+
attention_mask=attention_mask,
|
| 1039 |
+
position_ids=position_ids,
|
| 1040 |
+
output_attentions=output_attentions,
|
| 1041 |
+
output_hidden_states=output_hidden_states,
|
| 1042 |
+
return_dict=return_dict,
|
| 1043 |
+
)
|
| 1044 |
+
|
| 1045 |
+
pooled_output = text_outputs[1]
|
| 1046 |
+
text_features = self.text_projection(pooled_output)
|
| 1047 |
+
|
| 1048 |
+
return text_features
|
| 1049 |
+
|
| 1050 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
| 1051 |
+
def get_image_features(
|
| 1052 |
+
self,
|
| 1053 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1054 |
+
output_attentions: Optional[bool] = None,
|
| 1055 |
+
output_hidden_states: Optional[bool] = None,
|
| 1056 |
+
return_dict: Optional[bool] = None,
|
| 1057 |
+
) -> torch.FloatTensor:
|
| 1058 |
+
r"""
|
| 1059 |
+
Returns:
|
| 1060 |
+
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
|
| 1061 |
+
applying the projection layer to the pooled output of [`CLIPVisionModel`].
|
| 1062 |
+
|
| 1063 |
+
Examples:
|
| 1064 |
+
|
| 1065 |
+
```python
|
| 1066 |
+
>>> from PIL import Image
|
| 1067 |
+
>>> import requests
|
| 1068 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
| 1069 |
+
|
| 1070 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 1071 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 1072 |
+
|
| 1073 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1074 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1075 |
+
|
| 1076 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1077 |
+
|
| 1078 |
+
>>> image_features = model.get_image_features(**inputs)
|
| 1079 |
+
```"""
|
| 1080 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1081 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1082 |
+
output_hidden_states = (
|
| 1083 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1084 |
+
)
|
| 1085 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1086 |
+
|
| 1087 |
+
vision_outputs = self.vision_model(
|
| 1088 |
+
pixel_values=pixel_values,
|
| 1089 |
+
output_attentions=output_attentions,
|
| 1090 |
+
output_hidden_states=output_hidden_states,
|
| 1091 |
+
return_dict=return_dict,
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1095 |
+
image_features = self.visual_projection(pooled_output)
|
| 1096 |
+
|
| 1097 |
+
return image_features
|
| 1098 |
+
|
| 1099 |
+
@add_start_docstrings_to_model_forward(CLIP_INPUTS_DOCSTRING)
|
| 1100 |
+
@replace_return_docstrings(output_type=CLIPOutput, config_class=CLIPConfig)
|
| 1101 |
+
def forward(
|
| 1102 |
+
self,
|
| 1103 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1104 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1105 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1106 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1107 |
+
return_loss: Optional[bool] = None,
|
| 1108 |
+
output_attentions: Optional[bool] = None,
|
| 1109 |
+
output_hidden_states: Optional[bool] = None,
|
| 1110 |
+
return_dict: Optional[bool] = None,
|
| 1111 |
+
) -> Union[Tuple, CLIPOutput]:
|
| 1112 |
+
r"""
|
| 1113 |
+
Returns:
|
| 1114 |
+
|
| 1115 |
+
Examples:
|
| 1116 |
+
|
| 1117 |
+
```python
|
| 1118 |
+
>>> from PIL import Image
|
| 1119 |
+
>>> import requests
|
| 1120 |
+
>>> from transformers import AutoProcessor, CLIPModel
|
| 1121 |
+
|
| 1122 |
+
>>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 1123 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 1124 |
+
|
| 1125 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1126 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1127 |
+
|
| 1128 |
+
>>> inputs = processor(
|
| 1129 |
+
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
|
| 1130 |
+
... )
|
| 1131 |
+
|
| 1132 |
+
>>> outputs = model(**inputs)
|
| 1133 |
+
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
|
| 1134 |
+
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
|
| 1135 |
+
```"""
|
| 1136 |
+
# Use CLIP model's config for some fields (if specified) instead of those of vision & text components.
|
| 1137 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1138 |
+
output_hidden_states = (
|
| 1139 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1140 |
+
)
|
| 1141 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1142 |
+
|
| 1143 |
+
vision_outputs = self.vision_model(
|
| 1144 |
+
pixel_values=pixel_values,
|
| 1145 |
+
output_attentions=output_attentions,
|
| 1146 |
+
output_hidden_states=output_hidden_states,
|
| 1147 |
+
return_dict=return_dict,
|
| 1148 |
+
)
|
| 1149 |
+
|
| 1150 |
+
text_outputs = self.text_model(
|
| 1151 |
+
input_ids=input_ids,
|
| 1152 |
+
attention_mask=attention_mask,
|
| 1153 |
+
position_ids=position_ids,
|
| 1154 |
+
output_attentions=output_attentions,
|
| 1155 |
+
output_hidden_states=output_hidden_states,
|
| 1156 |
+
return_dict=return_dict,
|
| 1157 |
+
)
|
| 1158 |
+
|
| 1159 |
+
image_embeds = vision_outputs[1]
|
| 1160 |
+
image_embeds = self.visual_projection(image_embeds)
|
| 1161 |
+
|
| 1162 |
+
text_embeds = text_outputs[1]
|
| 1163 |
+
text_embeds = self.text_projection(text_embeds)
|
| 1164 |
+
|
| 1165 |
+
# normalized features
|
| 1166 |
+
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1167 |
+
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
|
| 1168 |
+
|
| 1169 |
+
# cosine similarity as logits
|
| 1170 |
+
logit_scale = self.logit_scale.exp()
|
| 1171 |
+
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
|
| 1172 |
+
logits_per_image = logits_per_text.t()
|
| 1173 |
+
|
| 1174 |
+
loss = None
|
| 1175 |
+
if return_loss:
|
| 1176 |
+
loss = clip_loss(logits_per_text)
|
| 1177 |
+
|
| 1178 |
+
if not return_dict:
|
| 1179 |
+
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
|
| 1180 |
+
return ((loss,) + output) if loss is not None else output
|
| 1181 |
+
|
| 1182 |
+
return CLIPOutput(
|
| 1183 |
+
loss=loss,
|
| 1184 |
+
logits_per_image=logits_per_image,
|
| 1185 |
+
logits_per_text=logits_per_text,
|
| 1186 |
+
text_embeds=text_embeds,
|
| 1187 |
+
image_embeds=image_embeds,
|
| 1188 |
+
text_model_output=text_outputs,
|
| 1189 |
+
vision_model_output=vision_outputs,
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
@add_start_docstrings(
|
| 1194 |
+
"""
|
| 1195 |
+
CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output).
|
| 1196 |
+
""",
|
| 1197 |
+
CLIP_START_DOCSTRING,
|
| 1198 |
+
)
|
| 1199 |
+
class CLIPTextModelWithProjection(CLIPPreTrainedModel):
|
| 1200 |
+
config_class = CLIPTextConfig
|
| 1201 |
+
|
| 1202 |
+
_no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
|
| 1203 |
+
|
| 1204 |
+
def __init__(self, config: CLIPTextConfig):
|
| 1205 |
+
super().__init__(config)
|
| 1206 |
+
|
| 1207 |
+
self.text_model = CLIPTextTransformer(config)
|
| 1208 |
+
|
| 1209 |
+
self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
| 1210 |
+
|
| 1211 |
+
# Initialize weights and apply final processing
|
| 1212 |
+
self.post_init()
|
| 1213 |
+
|
| 1214 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1215 |
+
return self.text_model.embeddings.token_embedding
|
| 1216 |
+
|
| 1217 |
+
def set_input_embeddings(self, value):
|
| 1218 |
+
self.text_model.embeddings.token_embedding = value
|
| 1219 |
+
|
| 1220 |
+
@add_start_docstrings_to_model_forward(CLIP_TEXT_INPUTS_DOCSTRING)
|
| 1221 |
+
@replace_return_docstrings(output_type=CLIPTextModelOutput, config_class=CLIPTextConfig)
|
| 1222 |
+
def forward(
|
| 1223 |
+
self,
|
| 1224 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 1225 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1226 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1227 |
+
output_attentions: Optional[bool] = None,
|
| 1228 |
+
output_hidden_states: Optional[bool] = None,
|
| 1229 |
+
return_dict: Optional[bool] = None,
|
| 1230 |
+
) -> Union[Tuple, CLIPTextModelOutput]:
|
| 1231 |
+
r"""
|
| 1232 |
+
Returns:
|
| 1233 |
+
|
| 1234 |
+
Examples:
|
| 1235 |
+
|
| 1236 |
+
```python
|
| 1237 |
+
>>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
|
| 1238 |
+
|
| 1239 |
+
>>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
| 1240 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
|
| 1241 |
+
|
| 1242 |
+
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
|
| 1243 |
+
|
| 1244 |
+
>>> outputs = model(**inputs)
|
| 1245 |
+
>>> text_embeds = outputs.text_embeds
|
| 1246 |
+
```"""
|
| 1247 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1248 |
+
|
| 1249 |
+
text_outputs = self.text_model(
|
| 1250 |
+
input_ids=input_ids,
|
| 1251 |
+
attention_mask=attention_mask,
|
| 1252 |
+
position_ids=position_ids,
|
| 1253 |
+
output_attentions=output_attentions,
|
| 1254 |
+
output_hidden_states=output_hidden_states,
|
| 1255 |
+
return_dict=return_dict,
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
pooled_output = text_outputs[1]
|
| 1259 |
+
|
| 1260 |
+
text_embeds = self.text_projection(pooled_output)
|
| 1261 |
+
|
| 1262 |
+
if not return_dict:
|
| 1263 |
+
outputs = (text_embeds, text_outputs[0]) + text_outputs[2:]
|
| 1264 |
+
return tuple(output for output in outputs if output is not None)
|
| 1265 |
+
|
| 1266 |
+
return CLIPTextModelOutput(
|
| 1267 |
+
text_embeds=text_embeds,
|
| 1268 |
+
last_hidden_state=text_outputs.last_hidden_state,
|
| 1269 |
+
hidden_states=text_outputs.hidden_states,
|
| 1270 |
+
attentions=text_outputs.attentions,
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
@add_start_docstrings(
|
| 1275 |
+
"""
|
| 1276 |
+
CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output).
|
| 1277 |
+
""",
|
| 1278 |
+
CLIP_START_DOCSTRING,
|
| 1279 |
+
)
|
| 1280 |
+
class CLIPVisionModelWithProjection(CLIPPreTrainedModel):
|
| 1281 |
+
config_class = CLIPVisionConfig
|
| 1282 |
+
main_input_name = "pixel_values"
|
| 1283 |
+
|
| 1284 |
+
def __init__(self, config: CLIPVisionConfig):
|
| 1285 |
+
super().__init__(config)
|
| 1286 |
+
|
| 1287 |
+
self.vision_model = CLIPVisionTransformer(config)
|
| 1288 |
+
|
| 1289 |
+
self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
|
| 1290 |
+
|
| 1291 |
+
# Initialize weights and apply final processing
|
| 1292 |
+
self.post_init()
|
| 1293 |
+
|
| 1294 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1295 |
+
return self.vision_model.embeddings.patch_embedding
|
| 1296 |
+
|
| 1297 |
+
@add_start_docstrings_to_model_forward(CLIP_VISION_INPUTS_DOCSTRING)
|
| 1298 |
+
@replace_return_docstrings(output_type=CLIPVisionModelOutput, config_class=CLIPVisionConfig)
|
| 1299 |
+
def forward(
|
| 1300 |
+
self,
|
| 1301 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 1302 |
+
output_attentions: Optional[bool] = None,
|
| 1303 |
+
output_hidden_states: Optional[bool] = None,
|
| 1304 |
+
return_dict: Optional[bool] = None,
|
| 1305 |
+
) -> Union[Tuple, CLIPVisionModelOutput]:
|
| 1306 |
+
r"""
|
| 1307 |
+
Returns:
|
| 1308 |
+
|
| 1309 |
+
Examples:
|
| 1310 |
+
|
| 1311 |
+
```python
|
| 1312 |
+
>>> from PIL import Image
|
| 1313 |
+
>>> import requests
|
| 1314 |
+
>>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
|
| 1315 |
+
|
| 1316 |
+
>>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
|
| 1317 |
+
>>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 1318 |
+
|
| 1319 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 1320 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1321 |
+
|
| 1322 |
+
>>> inputs = processor(images=image, return_tensors="pt")
|
| 1323 |
+
|
| 1324 |
+
>>> outputs = model(**inputs)
|
| 1325 |
+
>>> image_embeds = outputs.image_embeds
|
| 1326 |
+
```"""
|
| 1327 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1328 |
+
|
| 1329 |
+
vision_outputs = self.vision_model(
|
| 1330 |
+
pixel_values=pixel_values,
|
| 1331 |
+
output_attentions=output_attentions,
|
| 1332 |
+
output_hidden_states=output_hidden_states,
|
| 1333 |
+
return_dict=return_dict,
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
pooled_output = vision_outputs[1] # pooled_output
|
| 1337 |
+
|
| 1338 |
+
image_embeds = self.visual_projection(pooled_output)
|
| 1339 |
+
|
| 1340 |
+
if not return_dict:
|
| 1341 |
+
outputs = (image_embeds, vision_outputs[0]) + vision_outputs[2:]
|
| 1342 |
+
return tuple(output for output in outputs if output is not None)
|
| 1343 |
+
|
| 1344 |
+
return CLIPVisionModelOutput(
|
| 1345 |
+
image_embeds=image_embeds,
|
| 1346 |
+
last_hidden_state=vision_outputs.last_hidden_state,
|
| 1347 |
+
hidden_states=vision_outputs.hidden_states,
|
| 1348 |
+
attentions=vision_outputs.attentions,
|
| 1349 |
+
)
|
detail_encoder/attention_processor.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 6 |
+
from torchvision import transforms
|
| 7 |
+
if is_xformers_available():
|
| 8 |
+
import xformers
|
| 9 |
+
import xformers.ops
|
| 10 |
+
else:
|
| 11 |
+
xformers = None
|
| 12 |
+
|
| 13 |
+
class SSRAttnProcessor(nn.Module):
|
| 14 |
+
r"""
|
| 15 |
+
Attention processor for SSR-Adapater.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1):
|
| 19 |
+
super().__init__()
|
| 20 |
+
self.hidden_size = hidden_size
|
| 21 |
+
self.cross_attention_dim = cross_attention_dim
|
| 22 |
+
self.scale = scale
|
| 23 |
+
# self.to_q_SSR = nn.Linear(hidden_size, hidden_size, bias=False)
|
| 24 |
+
self.to_k_SSR = nn.Linear(cross_attention_dim, hidden_size, bias=False)
|
| 25 |
+
self.to_v_SSR = nn.Linear(cross_attention_dim, hidden_size, bias=False)
|
| 26 |
+
|
| 27 |
+
def __call__(
|
| 28 |
+
self,
|
| 29 |
+
attn,
|
| 30 |
+
hidden_states,
|
| 31 |
+
encoder_hidden_states=None,
|
| 32 |
+
attention_mask=None,
|
| 33 |
+
temb=None,
|
| 34 |
+
):
|
| 35 |
+
residual = hidden_states
|
| 36 |
+
|
| 37 |
+
if attn.spatial_norm is not None:
|
| 38 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 39 |
+
|
| 40 |
+
input_ndim = hidden_states.ndim
|
| 41 |
+
|
| 42 |
+
if input_ndim == 4:
|
| 43 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 44 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 45 |
+
|
| 46 |
+
batch_size, sequence_length, _ = (
|
| 47 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 48 |
+
)
|
| 49 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 50 |
+
|
| 51 |
+
if attn.group_norm is not None:
|
| 52 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 53 |
+
|
| 54 |
+
# query = self.to_q_SSR(hidden_states)
|
| 55 |
+
query = attn.to_q(hidden_states)
|
| 56 |
+
query = attn.head_to_batch_dim(query)
|
| 57 |
+
|
| 58 |
+
if encoder_hidden_states is None:
|
| 59 |
+
encoder_hidden_states = hidden_states
|
| 60 |
+
elif attn.norm_cross:
|
| 61 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 62 |
+
|
| 63 |
+
_hidden_states = encoder_hidden_states
|
| 64 |
+
_key = self.to_k_SSR(_hidden_states)
|
| 65 |
+
_value = self.to_v_SSR(_hidden_states)
|
| 66 |
+
_key = attn.head_to_batch_dim(_key)
|
| 67 |
+
_value = attn.head_to_batch_dim(_value)
|
| 68 |
+
_attention_probs = attn.get_attention_scores(query, _key, None)
|
| 69 |
+
_hidden_states = torch.bmm(_attention_probs, _value)
|
| 70 |
+
_hidden_states = attn.batch_to_head_dim(_hidden_states)
|
| 71 |
+
hidden_states = self.scale * _hidden_states
|
| 72 |
+
|
| 73 |
+
# linear proj
|
| 74 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 75 |
+
# dropout
|
| 76 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 77 |
+
|
| 78 |
+
if input_ndim == 4:
|
| 79 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 80 |
+
|
| 81 |
+
if attn.residual_connection:
|
| 82 |
+
hidden_states = hidden_states + residual
|
| 83 |
+
|
| 84 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 85 |
+
|
| 86 |
+
return hidden_states
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class SSRAttnProcessor2_0(torch.nn.Module):
|
| 90 |
+
r"""
|
| 91 |
+
Attention processor for SSR-Adapater for PyTorch 2.0.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0):
|
| 95 |
+
super().__init__()
|
| 96 |
+
|
| 97 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 98 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 99 |
+
self.hidden_size = hidden_size
|
| 100 |
+
self.cross_attention_dim = cross_attention_dim
|
| 101 |
+
self.scale = scale
|
| 102 |
+
# self.to_q_SSR = nn.Linear(hidden_size, hidden_size, bias=False)
|
| 103 |
+
self.to_k_SSR = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 104 |
+
self.to_v_SSR = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 105 |
+
|
| 106 |
+
def __call__(
|
| 107 |
+
self,
|
| 108 |
+
attn,
|
| 109 |
+
hidden_states,
|
| 110 |
+
encoder_hidden_states=None,
|
| 111 |
+
attention_mask=None,
|
| 112 |
+
temb=None,
|
| 113 |
+
):
|
| 114 |
+
residual = hidden_states
|
| 115 |
+
|
| 116 |
+
if attn.spatial_norm is not None:
|
| 117 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 118 |
+
|
| 119 |
+
input_ndim = hidden_states.ndim
|
| 120 |
+
|
| 121 |
+
if input_ndim == 4:
|
| 122 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 123 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 124 |
+
|
| 125 |
+
batch_size, sequence_length, _ = (
|
| 126 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if attention_mask is not None:
|
| 130 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 131 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
| 132 |
+
# (batch, heads, source_length, target_length)
|
| 133 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
| 134 |
+
|
| 135 |
+
if attn.group_norm is not None:
|
| 136 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 137 |
+
|
| 138 |
+
# query = self.to_q_SSR(hidden_states)
|
| 139 |
+
query = attn.to_q(hidden_states)
|
| 140 |
+
|
| 141 |
+
if encoder_hidden_states is None:
|
| 142 |
+
encoder_hidden_states = hidden_states
|
| 143 |
+
elif attn.norm_cross:
|
| 144 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 145 |
+
|
| 146 |
+
# split hidden states
|
| 147 |
+
_hidden_states = encoder_hidden_states
|
| 148 |
+
|
| 149 |
+
_key = self.to_k_SSR(_hidden_states)
|
| 150 |
+
_value = self.to_v_SSR(_hidden_states)
|
| 151 |
+
inner_dim = _key.shape[-1]
|
| 152 |
+
head_dim = inner_dim // attn.heads
|
| 153 |
+
|
| 154 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 155 |
+
|
| 156 |
+
_key = _key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 157 |
+
_value = _value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 158 |
+
|
| 159 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 160 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 161 |
+
_hidden_states = F.scaled_dot_product_attention(
|
| 162 |
+
query, _key, _value, attn_mask=None, dropout_p=0.0, is_causal=False
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
_hidden_states = _hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 166 |
+
_hidden_states = _hidden_states.to(query.dtype)
|
| 167 |
+
|
| 168 |
+
hidden_states = self.scale * _hidden_states
|
| 169 |
+
|
| 170 |
+
# linear proj
|
| 171 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 172 |
+
# dropout
|
| 173 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 174 |
+
|
| 175 |
+
if input_ndim == 4:
|
| 176 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 177 |
+
|
| 178 |
+
if attn.residual_connection:
|
| 179 |
+
hidden_states = hidden_states + residual
|
| 180 |
+
|
| 181 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 182 |
+
|
| 183 |
+
return hidden_states
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class AttnProcessor2_0(torch.nn.Module):
|
| 187 |
+
r"""
|
| 188 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
def __init__(
|
| 192 |
+
self,
|
| 193 |
+
hidden_size=None,
|
| 194 |
+
cross_attention_dim=None,
|
| 195 |
+
):
|
| 196 |
+
super().__init__()
|
| 197 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 198 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 199 |
+
|
| 200 |
+
def __call__(
|
| 201 |
+
self,
|
| 202 |
+
attn,
|
| 203 |
+
hidden_states,
|
| 204 |
+
encoder_hidden_states=None,
|
| 205 |
+
attention_mask=None,
|
| 206 |
+
temb=None,
|
| 207 |
+
):
|
| 208 |
+
residual = hidden_states
|
| 209 |
+
|
| 210 |
+
if attn.spatial_norm is not None:
|
| 211 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 212 |
+
|
| 213 |
+
input_ndim = hidden_states.ndim
|
| 214 |
+
|
| 215 |
+
if input_ndim == 4:
|
| 216 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 217 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 218 |
+
|
| 219 |
+
batch_size, sequence_length, _ = (
|
| 220 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if attention_mask is not None:
|
| 224 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 225 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
| 226 |
+
# (batch, heads, source_length, target_length)
|
| 227 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
| 228 |
+
|
| 229 |
+
if attn.group_norm is not None:
|
| 230 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 231 |
+
|
| 232 |
+
query = attn.to_q(hidden_states)
|
| 233 |
+
|
| 234 |
+
if encoder_hidden_states is None:
|
| 235 |
+
encoder_hidden_states = hidden_states
|
| 236 |
+
elif attn.norm_cross:
|
| 237 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 238 |
+
|
| 239 |
+
key = attn.to_k(encoder_hidden_states)
|
| 240 |
+
value = attn.to_v(encoder_hidden_states)
|
| 241 |
+
|
| 242 |
+
inner_dim = key.shape[-1]
|
| 243 |
+
head_dim = inner_dim // attn.heads
|
| 244 |
+
|
| 245 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 246 |
+
|
| 247 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 248 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 249 |
+
|
| 250 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 251 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 252 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 253 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 257 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 258 |
+
|
| 259 |
+
# linear proj
|
| 260 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 261 |
+
# dropout
|
| 262 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 263 |
+
|
| 264 |
+
if input_ndim == 4:
|
| 265 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 266 |
+
|
| 267 |
+
if attn.residual_connection:
|
| 268 |
+
hidden_states = hidden_states + residual
|
| 269 |
+
|
| 270 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 271 |
+
|
| 272 |
+
return hidden_states
|
| 273 |
+
|
| 274 |
+
class AttnProcessor(nn.Module):
|
| 275 |
+
r"""
|
| 276 |
+
Default processor for performing attention-related computations.
|
| 277 |
+
"""
|
| 278 |
+
def __init__(
|
| 279 |
+
self,
|
| 280 |
+
hidden_size=None,
|
| 281 |
+
cross_attention_dim=None,
|
| 282 |
+
):
|
| 283 |
+
super().__init__()
|
| 284 |
+
|
| 285 |
+
def __call__(
|
| 286 |
+
self,
|
| 287 |
+
attn,
|
| 288 |
+
hidden_states,
|
| 289 |
+
encoder_hidden_states=None,
|
| 290 |
+
attention_mask=None,
|
| 291 |
+
temb=None,
|
| 292 |
+
):
|
| 293 |
+
residual = hidden_states
|
| 294 |
+
|
| 295 |
+
if attn.spatial_norm is not None:
|
| 296 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 297 |
+
|
| 298 |
+
input_ndim = hidden_states.ndim
|
| 299 |
+
|
| 300 |
+
if input_ndim == 4:
|
| 301 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 302 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 303 |
+
|
| 304 |
+
batch_size, sequence_length, _ = (
|
| 305 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 306 |
+
)
|
| 307 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 308 |
+
|
| 309 |
+
if attn.group_norm is not None:
|
| 310 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 311 |
+
|
| 312 |
+
query = attn.to_q(hidden_states)
|
| 313 |
+
|
| 314 |
+
if encoder_hidden_states is None:
|
| 315 |
+
encoder_hidden_states = hidden_states
|
| 316 |
+
elif attn.norm_cross:
|
| 317 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 318 |
+
|
| 319 |
+
key = attn.to_k(encoder_hidden_states)
|
| 320 |
+
value = attn.to_v(encoder_hidden_states)
|
| 321 |
+
|
| 322 |
+
query = attn.head_to_batch_dim(query)
|
| 323 |
+
key = attn.head_to_batch_dim(key)
|
| 324 |
+
value = attn.head_to_batch_dim(value)
|
| 325 |
+
|
| 326 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 327 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 328 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 329 |
+
|
| 330 |
+
# linear proj
|
| 331 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 332 |
+
# dropout
|
| 333 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 334 |
+
|
| 335 |
+
if input_ndim == 4:
|
| 336 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 337 |
+
|
| 338 |
+
if attn.residual_connection:
|
| 339 |
+
hidden_states = hidden_states + residual
|
| 340 |
+
|
| 341 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 342 |
+
|
| 343 |
+
return hidden_states
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class ConvAttnProcessor:
|
| 347 |
+
def __call__(
|
| 348 |
+
self,
|
| 349 |
+
attn,
|
| 350 |
+
hidden_states,
|
| 351 |
+
encoder_hidden_states=None,
|
| 352 |
+
attention_mask=None,
|
| 353 |
+
):
|
| 354 |
+
## map to 2D
|
| 355 |
+
if len(hidden_states.shape) == 4:
|
| 356 |
+
shape = hidden_states.shape
|
| 357 |
+
hidden_states = torch.reshape(hidden_states, (shape[0], shape[1], shape[2] * shape[3]))
|
| 358 |
+
hidden_states = hidden_states.permute(0, 2, 1)
|
| 359 |
+
if encoder_hidden_states is not None:
|
| 360 |
+
if len(encoder_hidden_states.shape) == 4:
|
| 361 |
+
kv_shape = encoder_hidden_states.shape
|
| 362 |
+
encoder_hidden_states = torch.reshape(
|
| 363 |
+
encoder_hidden_states, (kv_shape[0], kv_shape[1], kv_shape[2] * kv_shape[3])
|
| 364 |
+
)
|
| 365 |
+
encoder_hidden_states = encoder_hidden_states.permute(0, 2, 1)
|
| 366 |
+
|
| 367 |
+
# the same to standard attn
|
| 368 |
+
batch_size, sequence_length, _ = (
|
| 369 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 370 |
+
)
|
| 371 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 372 |
+
query = attn.to_q(hidden_states)
|
| 373 |
+
|
| 374 |
+
if encoder_hidden_states is None:
|
| 375 |
+
encoder_hidden_states = hidden_states
|
| 376 |
+
elif attn.norm_cross:
|
| 377 |
+
encoder_hidden_states = attn.norm_cross(encoder_hidden_states)
|
| 378 |
+
|
| 379 |
+
key = attn.to_k(encoder_hidden_states)
|
| 380 |
+
value = attn.to_v(encoder_hidden_states)
|
| 381 |
+
|
| 382 |
+
query = attn.head_to_batch_dim(query)
|
| 383 |
+
key = attn.head_to_batch_dim(key)
|
| 384 |
+
value = attn.head_to_batch_dim(value)
|
| 385 |
+
|
| 386 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 387 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 388 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 389 |
+
|
| 390 |
+
# linear proj
|
| 391 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 392 |
+
# dropout
|
| 393 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 394 |
+
|
| 395 |
+
# map back to 4D
|
| 396 |
+
if len(hidden_states.shape) == 3:
|
| 397 |
+
hidden_states = hidden_states.permute(0, 2, 1)
|
| 398 |
+
hidden_states = torch.reshape(hidden_states, (shape[0], shape[1], shape[2], shape[3]))
|
| 399 |
+
|
| 400 |
+
return hidden_states
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class SSRAttnProcessor_text(nn.Module):
|
| 404 |
+
r"""
|
| 405 |
+
Attention processor for SSR-Adapater.
|
| 406 |
+
"""
|
| 407 |
+
|
| 408 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1):
|
| 409 |
+
super().__init__()
|
| 410 |
+
self.text_context_len = 77
|
| 411 |
+
self.hidden_size = hidden_size
|
| 412 |
+
self.cross_attention_dim = cross_attention_dim
|
| 413 |
+
self.scale = scale
|
| 414 |
+
self.to_k_SSR = nn.Linear(cross_attention_dim, hidden_size, bias=False)
|
| 415 |
+
self.to_v_SSR = nn.Linear(cross_attention_dim, hidden_size, bias=False)
|
| 416 |
+
|
| 417 |
+
def __call__(
|
| 418 |
+
self,
|
| 419 |
+
attn,
|
| 420 |
+
hidden_states,
|
| 421 |
+
encoder_hidden_states=None,
|
| 422 |
+
attention_mask=None,
|
| 423 |
+
temb=None,
|
| 424 |
+
):
|
| 425 |
+
residual = hidden_states
|
| 426 |
+
|
| 427 |
+
if attn.spatial_norm is not None:
|
| 428 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 429 |
+
|
| 430 |
+
input_ndim = hidden_states.ndim
|
| 431 |
+
|
| 432 |
+
if input_ndim == 4:
|
| 433 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 434 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 435 |
+
|
| 436 |
+
batch_size, sequence_length, _ = (
|
| 437 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 438 |
+
)
|
| 439 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 440 |
+
|
| 441 |
+
if attn.group_norm is not None:
|
| 442 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 443 |
+
|
| 444 |
+
query = attn.to_q(hidden_states)
|
| 445 |
+
query = attn.head_to_batch_dim(query)
|
| 446 |
+
|
| 447 |
+
if encoder_hidden_states is None:
|
| 448 |
+
encoder_hidden_states = hidden_states
|
| 449 |
+
elif attn.norm_cross:
|
| 450 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 451 |
+
|
| 452 |
+
# split hidden states
|
| 453 |
+
encoder_hidden_states, _hidden_states = encoder_hidden_states[:, :self.text_context_len,
|
| 454 |
+
:], encoder_hidden_states[:, self.text_context_len:, :]
|
| 455 |
+
encoder_hidden_states = encoder_hidden_states[:, :, :768]
|
| 456 |
+
# for text
|
| 457 |
+
key = attn.to_k(encoder_hidden_states)
|
| 458 |
+
value = attn.to_v(encoder_hidden_states)
|
| 459 |
+
|
| 460 |
+
key = attn.head_to_batch_dim(key)
|
| 461 |
+
value = attn.head_to_batch_dim(value)
|
| 462 |
+
|
| 463 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 464 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 465 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 466 |
+
|
| 467 |
+
# for image
|
| 468 |
+
_key = self.to_k_SSR(_hidden_states)
|
| 469 |
+
_value = self.to_v_SSR(_hidden_states)
|
| 470 |
+
_key = attn.head_to_batch_dim(_key)
|
| 471 |
+
_value = attn.head_to_batch_dim(_value)
|
| 472 |
+
_attention_probs = attn.get_attention_scores(query, _key, None)
|
| 473 |
+
_hidden_states = torch.bmm(_attention_probs, _value)
|
| 474 |
+
_hidden_states = attn.batch_to_head_dim(_hidden_states)
|
| 475 |
+
hidden_states = self.scale * _hidden_states + hidden_states
|
| 476 |
+
|
| 477 |
+
# linear proj
|
| 478 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 479 |
+
# dropout
|
| 480 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 481 |
+
|
| 482 |
+
if input_ndim == 4:
|
| 483 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 484 |
+
|
| 485 |
+
if attn.residual_connection:
|
| 486 |
+
hidden_states = hidden_states + residual
|
| 487 |
+
|
| 488 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 489 |
+
|
| 490 |
+
return hidden_states
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
class SSRAttnProcessor2_0_text(torch.nn.Module):
|
| 494 |
+
r"""
|
| 495 |
+
Attention processor for SSR-Adapater for PyTorch 2.0.
|
| 496 |
+
"""
|
| 497 |
+
|
| 498 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0):
|
| 499 |
+
super().__init__()
|
| 500 |
+
|
| 501 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
| 502 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
| 503 |
+
self.text_context_len = 77
|
| 504 |
+
self.hidden_size = hidden_size
|
| 505 |
+
self.cross_attention_dim = cross_attention_dim
|
| 506 |
+
self.scale = scale
|
| 507 |
+
self.to_k_SSR = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 508 |
+
self.to_v_SSR = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
| 509 |
+
|
| 510 |
+
def __call__(
|
| 511 |
+
self,
|
| 512 |
+
attn,
|
| 513 |
+
hidden_states,
|
| 514 |
+
encoder_hidden_states=None,
|
| 515 |
+
attention_mask=None,
|
| 516 |
+
temb=None,
|
| 517 |
+
):
|
| 518 |
+
residual = hidden_states
|
| 519 |
+
|
| 520 |
+
if attn.spatial_norm is not None:
|
| 521 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 522 |
+
|
| 523 |
+
input_ndim = hidden_states.ndim
|
| 524 |
+
|
| 525 |
+
if input_ndim == 4:
|
| 526 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 527 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 528 |
+
|
| 529 |
+
batch_size, sequence_length, _ = (
|
| 530 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
if attention_mask is not None:
|
| 534 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 535 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
| 536 |
+
# (batch, heads, source_length, target_length)
|
| 537 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
| 538 |
+
|
| 539 |
+
if attn.group_norm is not None:
|
| 540 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 541 |
+
|
| 542 |
+
query = attn.to_q(hidden_states)
|
| 543 |
+
|
| 544 |
+
if encoder_hidden_states is None:
|
| 545 |
+
encoder_hidden_states = hidden_states
|
| 546 |
+
elif attn.norm_cross:
|
| 547 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 548 |
+
|
| 549 |
+
# split hidden states
|
| 550 |
+
encoder_hidden_states, _hidden_states = encoder_hidden_states[:, :self.text_context_len,
|
| 551 |
+
:], encoder_hidden_states[:, self.text_context_len:, :]
|
| 552 |
+
|
| 553 |
+
encoder_hidden_states = encoder_hidden_states[:, :, :768]
|
| 554 |
+
# for text
|
| 555 |
+
key = attn.to_k(encoder_hidden_states)
|
| 556 |
+
value = attn.to_v(encoder_hidden_states)
|
| 557 |
+
inner_dim = key.shape[-1]
|
| 558 |
+
head_dim = inner_dim // attn.heads
|
| 559 |
+
|
| 560 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 561 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 562 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 563 |
+
|
| 564 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 565 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 566 |
+
hidden_states = F.scaled_dot_product_attention(
|
| 567 |
+
query, key, value, attn_mask=attention_mask, dropout_p = 0.0, is_causal = False
|
| 568 |
+
)
|
| 569 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 570 |
+
hidden_states = hidden_states.to(query.dtype)
|
| 571 |
+
|
| 572 |
+
# for image
|
| 573 |
+
_key = self.to_k_SSR(_hidden_states)
|
| 574 |
+
_value = self.to_v_SSR(_hidden_states)
|
| 575 |
+
inner_dim = _key.shape[-1]
|
| 576 |
+
head_dim = inner_dim // attn.heads
|
| 577 |
+
|
| 578 |
+
_key = _key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 579 |
+
_value = _value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
| 580 |
+
|
| 581 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
| 582 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
| 583 |
+
_hidden_states = F.scaled_dot_product_attention(
|
| 584 |
+
query, _key, _value, attn_mask=None, dropout_p=0.0, is_causal=False
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
_hidden_states = _hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
| 588 |
+
_hidden_states = _hidden_states.to(query.dtype)
|
| 589 |
+
|
| 590 |
+
hidden_states = self.scale * _hidden_states + hidden_states
|
| 591 |
+
|
| 592 |
+
# linear proj
|
| 593 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 594 |
+
# dropout
|
| 595 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 596 |
+
|
| 597 |
+
if input_ndim == 4:
|
| 598 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 599 |
+
|
| 600 |
+
if attn.residual_connection:
|
| 601 |
+
hidden_states = hidden_states + residual
|
| 602 |
+
|
| 603 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 604 |
+
|
| 605 |
+
return hidden_states
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class SSRAttnProcessor_visual(nn.Module):
|
| 609 |
+
r"""
|
| 610 |
+
Attention processor for attn visualization.
|
| 611 |
+
"""
|
| 612 |
+
|
| 613 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1, attnstore=None, place_in_unet=None):
|
| 614 |
+
super().__init__()
|
| 615 |
+
self.hidden_size = hidden_size
|
| 616 |
+
self.cross_attention_dim = cross_attention_dim
|
| 617 |
+
self.scale = scale
|
| 618 |
+
self.to_k_SSR = nn.Linear(cross_attention_dim, hidden_size, bias=False)
|
| 619 |
+
self.to_v_SSR = nn.Linear(cross_attention_dim, hidden_size, bias=False)
|
| 620 |
+
self.attnstore = attnstore
|
| 621 |
+
self.place_in_unet = place_in_unet
|
| 622 |
+
|
| 623 |
+
def __call__(
|
| 624 |
+
self,
|
| 625 |
+
attn,
|
| 626 |
+
hidden_states,
|
| 627 |
+
encoder_hidden_states=None,
|
| 628 |
+
attention_mask=None,
|
| 629 |
+
temb=None,
|
| 630 |
+
):
|
| 631 |
+
residual = hidden_states
|
| 632 |
+
|
| 633 |
+
if attn.spatial_norm is not None:
|
| 634 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
| 635 |
+
|
| 636 |
+
input_ndim = hidden_states.ndim
|
| 637 |
+
|
| 638 |
+
if input_ndim == 4:
|
| 639 |
+
batch_size, channel, height, width = hidden_states.shape
|
| 640 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
| 641 |
+
|
| 642 |
+
batch_size, sequence_length, _ = (
|
| 643 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 644 |
+
)
|
| 645 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 646 |
+
|
| 647 |
+
if attn.group_norm is not None:
|
| 648 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
| 649 |
+
|
| 650 |
+
# query = self.to_q_SSR(hidden_states)
|
| 651 |
+
query = attn.to_q(hidden_states)
|
| 652 |
+
query = attn.head_to_batch_dim(query)
|
| 653 |
+
|
| 654 |
+
if encoder_hidden_states is None:
|
| 655 |
+
encoder_hidden_states = hidden_states
|
| 656 |
+
elif attn.norm_cross:
|
| 657 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 658 |
+
|
| 659 |
+
_hidden_states = encoder_hidden_states
|
| 660 |
+
_key = self.to_k_SSR(_hidden_states)
|
| 661 |
+
_value = self.to_v_SSR(_hidden_states)
|
| 662 |
+
_key = attn.head_to_batch_dim(_key)
|
| 663 |
+
_value = attn.head_to_batch_dim(_value)
|
| 664 |
+
_attention_probs = attn.get_attention_scores(query, _key, None)
|
| 665 |
+
|
| 666 |
+
# store attention maps
|
| 667 |
+
is_cross = encoder_hidden_states is not None
|
| 668 |
+
self.attnstore(_attention_probs, is_cross, self.place_in_unet)
|
| 669 |
+
|
| 670 |
+
_hidden_states = torch.bmm(_attention_probs, _value)
|
| 671 |
+
_hidden_states = attn.batch_to_head_dim(_hidden_states)
|
| 672 |
+
hidden_states = self.scale * _hidden_states
|
| 673 |
+
|
| 674 |
+
# linear proj
|
| 675 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 676 |
+
# dropout
|
| 677 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 678 |
+
|
| 679 |
+
if input_ndim == 4:
|
| 680 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
| 681 |
+
|
| 682 |
+
if attn.residual_connection:
|
| 683 |
+
hidden_states = hidden_states + residual
|
| 684 |
+
|
| 685 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 686 |
+
|
| 687 |
+
return hidden_states
|
detail_encoder/encoder_plus.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
import torch
|
| 3 |
+
from torchvision import transforms
|
| 4 |
+
from transformers import CLIPImageProcessor
|
| 5 |
+
from transformers import CLIPVisionModel as OriginalCLIPVisionModel
|
| 6 |
+
from ._clip import CLIPVisionModel
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
def is_torch2_available():
|
| 13 |
+
return hasattr(F, "scaled_dot_product_attention")
|
| 14 |
+
if is_torch2_available():
|
| 15 |
+
from .attention_processor import SSRAttnProcessor2_0 as SSRAttnProcessor, AttnProcessor2_0 as AttnProcessor
|
| 16 |
+
else:
|
| 17 |
+
from .attention_processor import SSRAttnProcessor, AttnProcessor
|
| 18 |
+
from .resampler import Resampler
|
| 19 |
+
|
| 20 |
+
class detail_encoder(torch.nn.Module):
|
| 21 |
+
"""from SSR-encoder"""
|
| 22 |
+
def __init__(self, unet, image_encoder_path, device="cuda", dtype=torch.float32):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.device = device
|
| 25 |
+
self.dtype = dtype
|
| 26 |
+
|
| 27 |
+
# load image encoder
|
| 28 |
+
clip_encoder = OriginalCLIPVisionModel.from_pretrained(image_encoder_path)
|
| 29 |
+
self.image_encoder = CLIPVisionModel(clip_encoder.config)
|
| 30 |
+
state_dict = clip_encoder.state_dict()
|
| 31 |
+
self.image_encoder.load_state_dict(state_dict, strict=False)
|
| 32 |
+
self.image_encoder.to(self.device, self.dtype)
|
| 33 |
+
del clip_encoder
|
| 34 |
+
self.clip_image_processor = CLIPImageProcessor()
|
| 35 |
+
|
| 36 |
+
# load SSR layers
|
| 37 |
+
attn_procs = {}
|
| 38 |
+
for name in unet.attn_processors.keys():
|
| 39 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 40 |
+
if name.startswith("mid_block"):
|
| 41 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 42 |
+
elif name.startswith("up_blocks"):
|
| 43 |
+
block_id = int(name[len("up_blocks.")])
|
| 44 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 45 |
+
elif name.startswith("down_blocks"):
|
| 46 |
+
block_id = int(name[len("down_blocks.")])
|
| 47 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 48 |
+
if cross_attention_dim is None:
|
| 49 |
+
attn_procs[name] = AttnProcessor()
|
| 50 |
+
else:
|
| 51 |
+
attn_procs[name] = SSRAttnProcessor(hidden_size=hidden_size, cross_attention_dim=1024, scale=1).to(self.device, dtype=self.dtype)
|
| 52 |
+
unet.set_attn_processor(attn_procs)
|
| 53 |
+
adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
|
| 54 |
+
self.SSR_layers = adapter_modules
|
| 55 |
+
self.SSR_layers.to(self.device, dtype=self.dtype)
|
| 56 |
+
self.resampler = self.init_proj()
|
| 57 |
+
|
| 58 |
+
def init_proj(self):
|
| 59 |
+
resampler = Resampler().to(self.device, dtype=self.dtype)
|
| 60 |
+
return resampler
|
| 61 |
+
|
| 62 |
+
def forward(self, img):
|
| 63 |
+
image_embeds = self.image_encoder(img, output_hidden_states=True)['hidden_states'][2::2]
|
| 64 |
+
image_embeds = torch.cat(image_embeds, dim=1)
|
| 65 |
+
image_embeds = self.resampler(image_embeds)
|
| 66 |
+
return image_embeds
|
| 67 |
+
|
| 68 |
+
@torch.inference_mode()
|
| 69 |
+
def get_image_embeds(self, pil_image):
|
| 70 |
+
if isinstance(pil_image, Image.Image):
|
| 71 |
+
pil_image = [pil_image]
|
| 72 |
+
clip_image = []
|
| 73 |
+
for pil in pil_image:
|
| 74 |
+
tensor_image = self.clip_image_processor(images=pil, return_tensors="pt").pixel_values.to(self.device, dtype=self.dtype)
|
| 75 |
+
clip_image.append(tensor_image)
|
| 76 |
+
clip_image = torch.cat(clip_image, dim=0)
|
| 77 |
+
|
| 78 |
+
# cond
|
| 79 |
+
clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True)['hidden_states'][2::2] # 1 257*12 1024
|
| 80 |
+
clip_image_embeds = torch.cat(clip_image_embeds, dim=1)
|
| 81 |
+
uncond_clip_image_embeds = self.image_encoder(torch.zeros_like(clip_image), output_hidden_states=True)['hidden_states'][2::2]
|
| 82 |
+
uncond_clip_image_embeds = torch.cat(uncond_clip_image_embeds, dim=1)
|
| 83 |
+
clip_image_embeds = self.resampler(clip_image_embeds)
|
| 84 |
+
uncond_clip_image_embeds = self.resampler(uncond_clip_image_embeds)
|
| 85 |
+
return clip_image_embeds, uncond_clip_image_embeds
|
| 86 |
+
|
| 87 |
+
def generate(
|
| 88 |
+
self,
|
| 89 |
+
id_image,
|
| 90 |
+
makeup_image,
|
| 91 |
+
seed=None,
|
| 92 |
+
guidance_scale=2,
|
| 93 |
+
num_inference_steps=30,
|
| 94 |
+
pipe=None,
|
| 95 |
+
**kwargs,
|
| 96 |
+
):
|
| 97 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(makeup_image)
|
| 98 |
+
|
| 99 |
+
prompt_embeds = image_prompt_embeds
|
| 100 |
+
negative_prompt_embeds = uncond_image_prompt_embeds
|
| 101 |
+
|
| 102 |
+
generator = torch.Generator(self.device).manual_seed(seed) if seed is not None else None
|
| 103 |
+
image = pipe(
|
| 104 |
+
image=id_image,
|
| 105 |
+
prompt_embeds=prompt_embeds,
|
| 106 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 107 |
+
guidance_scale=guidance_scale,
|
| 108 |
+
num_inference_steps=num_inference_steps,
|
| 109 |
+
generator=generator,
|
| 110 |
+
**kwargs,
|
| 111 |
+
).images[0]
|
| 112 |
+
|
| 113 |
+
return image
|
detail_encoder/resampler.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import math
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch import nn, einsum
|
| 5 |
+
from inspect import isfunction
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def exists(val):
|
| 9 |
+
return val is not None
|
| 10 |
+
|
| 11 |
+
def uniq(arr):
|
| 12 |
+
return{el: True for el in arr}.keys()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def default(val, d):
|
| 16 |
+
if exists(val):
|
| 17 |
+
return val
|
| 18 |
+
return d() if isfunction(d) else d
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def max_neg_value(t):
|
| 22 |
+
return -torch.finfo(t.dtype).max
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def init_(tensor):
|
| 26 |
+
dim = tensor.shape[-1]
|
| 27 |
+
std = 1 / math.sqrt(dim)
|
| 28 |
+
tensor.uniform_(-std, std)
|
| 29 |
+
return tensor
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# feedforward
|
| 33 |
+
class GEGLU(nn.Module):
|
| 34 |
+
def __init__(self, dim_in, dim_out):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
| 37 |
+
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
| 40 |
+
return x * F.gelu(gate)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class FeedForward(nn.Module):
|
| 44 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=True, dropout=0.):
|
| 45 |
+
super().__init__()
|
| 46 |
+
inner_dim = int(dim * mult)
|
| 47 |
+
dim_out = default(dim_out, dim)
|
| 48 |
+
project_in = nn.Sequential(
|
| 49 |
+
nn.Linear(dim, inner_dim),
|
| 50 |
+
nn.GELU()
|
| 51 |
+
) if not glu else GEGLU(dim, inner_dim)
|
| 52 |
+
|
| 53 |
+
self.net = nn.Sequential(
|
| 54 |
+
project_in,
|
| 55 |
+
nn.Dropout(dropout),
|
| 56 |
+
nn.Linear(inner_dim, dim_out)
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def forward(self, x):
|
| 60 |
+
return self.net(x)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class SelfAttention(nn.Module):
|
| 64 |
+
def __init__(self, query_dim, heads=8, dim_head=64, dropout=0.):
|
| 65 |
+
super().__init__()
|
| 66 |
+
inner_dim = dim_head * heads
|
| 67 |
+
self.scale = dim_head ** -0.5
|
| 68 |
+
self.heads = heads
|
| 69 |
+
|
| 70 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
| 71 |
+
self.to_k = nn.Linear(query_dim, inner_dim, bias=False)
|
| 72 |
+
self.to_v = nn.Linear(query_dim, inner_dim, bias=False)
|
| 73 |
+
|
| 74 |
+
self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout) )
|
| 75 |
+
|
| 76 |
+
def forward(self, x):
|
| 77 |
+
q = self.to_q(x) # B*N*(H*C)
|
| 78 |
+
k = self.to_k(x) # B*N*(H*C)
|
| 79 |
+
v = self.to_v(x) # B*N*(H*C)
|
| 80 |
+
|
| 81 |
+
B, N, HC = q.shape
|
| 82 |
+
H = self.heads
|
| 83 |
+
C = HC // H
|
| 84 |
+
|
| 85 |
+
q = q.view(B,N,H,C).permute(0,2,1,3).reshape(B*H,N,C) # (B*H)*N*C
|
| 86 |
+
k = k.view(B,N,H,C).permute(0,2,1,3).reshape(B*H,N,C) # (B*H)*N*C
|
| 87 |
+
v = v.view(B,N,H,C).permute(0,2,1,3).reshape(B*H,N,C) # (B*H)*N*C
|
| 88 |
+
|
| 89 |
+
sim = torch.einsum('b i c, b j c -> b i j', q, k) * self.scale # (B*H)*N*N
|
| 90 |
+
attn = sim.softmax(dim=-1) # (B*H)*N*N
|
| 91 |
+
|
| 92 |
+
out = torch.einsum('b i j, b j c -> b i c', attn, v) # (B*H)*N*C
|
| 93 |
+
out = out.view(B,H,N,C).permute(0,2,1,3).reshape(B,N,(H*C)) # B*N*(H*C)
|
| 94 |
+
|
| 95 |
+
return self.to_out(out)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class Resampler(nn.Module):
|
| 100 |
+
def __init__(self, query_dim=1024, n_heads=8, d_head=64):
|
| 101 |
+
super().__init__()
|
| 102 |
+
|
| 103 |
+
self.attn = SelfAttention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
|
| 104 |
+
self.ff = FeedForward(query_dim, glu=True)
|
| 105 |
+
|
| 106 |
+
self.norm1 = nn.LayerNorm(query_dim)
|
| 107 |
+
self.norm2 = nn.LayerNorm(query_dim)
|
| 108 |
+
|
| 109 |
+
def forward(self, x):
|
| 110 |
+
x = x + self.attn(self.norm1(x))
|
| 111 |
+
x = x + self.ff(self.norm2(x))
|
| 112 |
+
return x
|
download_weights.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""下载 Stable-Makeup 预训练权重(从 Google Drive)
|
| 2 |
+
Windows 本地运行:python download_weights.py
|
| 3 |
+
依赖:pip install gdown
|
| 4 |
+
"""
|
| 5 |
+
import gdown
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
OUTPUT_DIR = "./weights"
|
| 9 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 10 |
+
|
| 11 |
+
# Google Drive folder: https://drive.google.com/drive/folders/1397t27GrUyLPnj17qVpKWGwg93EcaFfg
|
| 12 |
+
FOLDER_ID = "1397t27GrUyLPnj17qVpKWGwg93EcaFfg"
|
| 13 |
+
|
| 14 |
+
print("⬇️ 从 Google Drive 下载全部权重文件...")
|
| 15 |
+
downloaded = gdown.download_folder(
|
| 16 |
+
id=FOLDER_ID,
|
| 17 |
+
output=OUTPUT_DIR,
|
| 18 |
+
quiet=False,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
if downloaded:
|
| 22 |
+
for f in downloaded:
|
| 23 |
+
size_mb = os.path.getsize(f) / 1024**2
|
| 24 |
+
print(f" ✅ {f} ({size_mb:.0f}MB)")
|
| 25 |
+
print(f"\n🎉 全部完成!文件在: {OUTPUT_DIR}/")
|
| 26 |
+
else:
|
| 27 |
+
# 备选:手动下载
|
| 28 |
+
print("gdown 下载失败,请浏览器打开以下链接手动下载:")
|
| 29 |
+
print("https://drive.google.com/drive/folders/1397t27GrUyLPnj17qVpKWGwg93EcaFfg")
|
| 30 |
+
print(f"下载后把 3 个 .bin 文件放到 {OUTPUT_DIR}/ 目录下")
|
face_utils.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from batch_face import RetinaFace
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _get_square_face(coord, image, padding_scale = 1.5):
|
| 9 |
+
x1, y1, x2, y2 = coord
|
| 10 |
+
# expand the face region by {padding_scale} times
|
| 11 |
+
length = ((x2 - x1) + (y2 - y1)) // 2
|
| 12 |
+
x1 = x1 - length * (padding_scale - 1.0)
|
| 13 |
+
x2 = x2 + length * (padding_scale - 1.0)
|
| 14 |
+
y1 = y1 - length * (padding_scale - 1.0)
|
| 15 |
+
y2 = y2 + length * (padding_scale - 1.0)
|
| 16 |
+
|
| 17 |
+
# Move the center upside a little
|
| 18 |
+
y1 -= length * (padding_scale - 1.0) * 0.2
|
| 19 |
+
y2 -= length * (padding_scale - 1.0) * 0.2
|
| 20 |
+
|
| 21 |
+
# get square image
|
| 22 |
+
center = (x1 + x2) // 2, (y1 + y2) // 2
|
| 23 |
+
length = max(x2 - x1, y2 - y1) // 2
|
| 24 |
+
x1 = max(int(round(center[0] - length)), 0)
|
| 25 |
+
x2 = min(int(round(center[0] + length)), image.shape[1])
|
| 26 |
+
y1 = max(int(round(center[1] - length)), 0)
|
| 27 |
+
y2 = min(int(round(center[1] + length)), image.shape[0])
|
| 28 |
+
return image[y1:y2, x1:x2]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _get_face_coord(face_detector, frame_cv2):
|
| 32 |
+
faces = face_detector(frame_cv2, cv=True)
|
| 33 |
+
if len(faces) == 0:
|
| 34 |
+
raise ValueError("Face is not detected")
|
| 35 |
+
else:
|
| 36 |
+
coord = faces[0][0]
|
| 37 |
+
return coord
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _smooth_coord(last_coord, current_coord, smooth_factor=0.1):
|
| 42 |
+
change = np.array(current_coord) - np.array(last_coord)
|
| 43 |
+
# smooth the change to 0.1 times
|
| 44 |
+
change = change * smooth_factor
|
| 45 |
+
return (np.array(last_coord) + np.array(change)).astype(int).tolist()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_face_img(face_detector, input_frame_path):
|
| 49 |
+
print("Detecting face in the image...")
|
| 50 |
+
frame_cv2 = cv2.imread(input_frame_path)
|
| 51 |
+
coord = _get_face_coord(face_detector, frame_cv2)
|
| 52 |
+
face = _get_square_face(coord, frame_cv2)
|
| 53 |
+
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
|
| 54 |
+
return Image.fromarray(face), coord
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_faces_video(face_detector, input_video_path):
|
| 58 |
+
output_frames = []
|
| 59 |
+
output_coords = []
|
| 60 |
+
last_coord = None
|
| 61 |
+
|
| 62 |
+
print("Detecting faces in the video...")
|
| 63 |
+
cap = cv2.VideoCapture(input_video_path)
|
| 64 |
+
while cap.isOpened():
|
| 65 |
+
ret, frame = cap.read()
|
| 66 |
+
if not ret:
|
| 67 |
+
break
|
| 68 |
+
face_coord = _get_face_coord(face_detector, frame)
|
| 69 |
+
if last_coord is not None:
|
| 70 |
+
face_coord = _smooth_coord(last_coord, face_coord)
|
| 71 |
+
last_coord = face_coord
|
| 72 |
+
face = _get_square_face(face_coord, frame)
|
| 73 |
+
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
|
| 74 |
+
face_pil = Image.fromarray(face)
|
| 75 |
+
output_frames.append(face_pil)
|
| 76 |
+
output_coords.append(face_coord)
|
| 77 |
+
cap.release()
|
| 78 |
+
return output_frames, output_coords
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == '__main__':
|
| 82 |
+
import torch
|
| 83 |
+
face_detector = RetinaFace(gpu_id=0) if torch.cuda.is_available() else RetinaFace(gpu_id=-1)
|
| 84 |
+
# test for image
|
| 85 |
+
input_frame_path = './test_imgs/makeup/1.jpg'
|
| 86 |
+
face, _ = get_face_img(face_detector, input_frame_path)
|
| 87 |
+
face.save('face.png')
|
| 88 |
+
print("Image saved to face.png")
|
| 89 |
+
|
| 90 |
+
# test for video
|
| 91 |
+
import imageio
|
| 92 |
+
from tqdm import tqdm
|
| 93 |
+
frames, _ = get_faces_video(face_detector, './test_imgs/input_video.mp4')
|
| 94 |
+
print("Number of frames: ", len(frames))
|
| 95 |
+
writer = imageio.get_writer('face.mp4', fps=30, macro_block_size=1, quality=8, codec="libx264")
|
| 96 |
+
for frame in tqdm(frames):
|
| 97 |
+
writer.append_data(np.array(frame.resize((512, 512))))
|
| 98 |
+
writer.close()
|
| 99 |
+
print("Video saved to face.mp4")
|
pipeline_sd15.py
ADDED
|
@@ -0,0 +1,1867 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
|
| 16 |
+
import inspect
|
| 17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import PIL.Image
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
| 24 |
+
|
| 25 |
+
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
| 26 |
+
from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
| 27 |
+
from diffusers.models import AutoencoderKL, ControlNetModel, UNet2DConditionModel
|
| 28 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
| 29 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
| 30 |
+
from diffusers.utils import (
|
| 31 |
+
USE_PEFT_BACKEND,
|
| 32 |
+
deprecate,
|
| 33 |
+
logging,
|
| 34 |
+
replace_example_docstring,
|
| 35 |
+
scale_lora_layers,
|
| 36 |
+
unscale_lora_layers,
|
| 37 |
+
)
|
| 38 |
+
from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
|
| 39 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 40 |
+
from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
|
| 41 |
+
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 42 |
+
from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
EXAMPLE_DOC_STRING = """
|
| 48 |
+
Examples:
|
| 49 |
+
```py
|
| 50 |
+
>>> # !pip install opencv-python transformers accelerate
|
| 51 |
+
>>> from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
|
| 52 |
+
>>> from diffusers.utils import load_image
|
| 53 |
+
>>> import numpy as np
|
| 54 |
+
>>> import torch
|
| 55 |
+
|
| 56 |
+
>>> import cv2
|
| 57 |
+
>>> from PIL import Image
|
| 58 |
+
|
| 59 |
+
>>> # download an image
|
| 60 |
+
>>> image = load_image(
|
| 61 |
+
... "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
|
| 62 |
+
... )
|
| 63 |
+
>>> image = np.array(image)
|
| 64 |
+
|
| 65 |
+
>>> # get canny image
|
| 66 |
+
>>> image = cv2.Canny(image, 100, 200)
|
| 67 |
+
>>> image = image[:, :, None]
|
| 68 |
+
>>> image = np.concatenate([image, image, image], axis=2)
|
| 69 |
+
>>> canny_image = Image.fromarray(image)
|
| 70 |
+
|
| 71 |
+
>>> # load control net and stable diffusion v1-5
|
| 72 |
+
>>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
|
| 73 |
+
>>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 74 |
+
... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
|
| 75 |
+
... )
|
| 76 |
+
|
| 77 |
+
>>> # speed up diffusion process with faster scheduler and memory optimization
|
| 78 |
+
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
| 79 |
+
>>> # remove following line if xformers is not installed
|
| 80 |
+
>>> pipe.enable_xformers_memory_efficient_attention()
|
| 81 |
+
|
| 82 |
+
>>> pipe.enable_model_cpu_offload()
|
| 83 |
+
|
| 84 |
+
>>> # generate image
|
| 85 |
+
>>> generator = torch.manual_seed(0)
|
| 86 |
+
>>> image = pipe(
|
| 87 |
+
... "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
|
| 88 |
+
... ).images[0]
|
| 89 |
+
```
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class StableDiffusionControlNetPipeline(
|
| 94 |
+
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
|
| 95 |
+
):
|
| 96 |
+
r"""
|
| 97 |
+
Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.
|
| 98 |
+
|
| 99 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 100 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 101 |
+
|
| 102 |
+
The pipeline also inherits the following loading methods:
|
| 103 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
vae ([`AutoencoderKL`]):
|
| 107 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 108 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
| 109 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 110 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
| 111 |
+
A `CLIPTokenizer` to tokenize text.
|
| 112 |
+
unet ([`UNet2DConditionModel`]):
|
| 113 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 114 |
+
controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
|
| 115 |
+
Provides additional conditioning to the `unet` during the denoising process. If you set multiple
|
| 116 |
+
ControlNets as a list, the outputs from each ControlNet are added together to create one combined
|
| 117 |
+
additional conditioning.
|
| 118 |
+
scheduler ([`SchedulerMixin`]):
|
| 119 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 120 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 121 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 122 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 123 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
| 124 |
+
about a model's potential harms.
|
| 125 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 126 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 127 |
+
"""
|
| 128 |
+
model_cpu_offload_seq = "text_encoder->unet->vae"
|
| 129 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
| 130 |
+
_exclude_from_cpu_offload = ["safety_checker"]
|
| 131 |
+
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
vae: AutoencoderKL,
|
| 135 |
+
text_encoder: CLIPTextModel,
|
| 136 |
+
tokenizer: CLIPTokenizer,
|
| 137 |
+
unet: UNet2DConditionModel,
|
| 138 |
+
controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
|
| 139 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 140 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 141 |
+
feature_extractor: CLIPImageProcessor,
|
| 142 |
+
requires_safety_checker: bool = True,
|
| 143 |
+
):
|
| 144 |
+
super().__init__()
|
| 145 |
+
|
| 146 |
+
if safety_checker is None and requires_safety_checker:
|
| 147 |
+
logger.warning(
|
| 148 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
| 149 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
| 150 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
| 151 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
| 152 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
| 153 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
if safety_checker is not None and feature_extractor is None:
|
| 157 |
+
raise ValueError(
|
| 158 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
| 159 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if isinstance(controlnet, (list, tuple)):
|
| 163 |
+
controlnet = MultiControlNetModel(controlnet)
|
| 164 |
+
|
| 165 |
+
self.register_modules(
|
| 166 |
+
vae=vae,
|
| 167 |
+
text_encoder=text_encoder,
|
| 168 |
+
tokenizer=tokenizer,
|
| 169 |
+
unet=unet,
|
| 170 |
+
controlnet=controlnet,
|
| 171 |
+
scheduler=scheduler,
|
| 172 |
+
safety_checker=safety_checker,
|
| 173 |
+
feature_extractor=feature_extractor,
|
| 174 |
+
)
|
| 175 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 176 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
| 177 |
+
self.control_image_processor = VaeImageProcessor(
|
| 178 |
+
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
|
| 179 |
+
)
|
| 180 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 181 |
+
self.adapter=None
|
| 182 |
+
|
| 183 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
|
| 184 |
+
def enable_vae_slicing(self):
|
| 185 |
+
r"""
|
| 186 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 187 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 188 |
+
"""
|
| 189 |
+
self.vae.enable_slicing()
|
| 190 |
+
|
| 191 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
|
| 192 |
+
def disable_vae_slicing(self):
|
| 193 |
+
r"""
|
| 194 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
| 195 |
+
computing decoding in one step.
|
| 196 |
+
"""
|
| 197 |
+
self.vae.disable_slicing()
|
| 198 |
+
|
| 199 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
|
| 200 |
+
def enable_vae_tiling(self):
|
| 201 |
+
r"""
|
| 202 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 203 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 204 |
+
processing larger images.
|
| 205 |
+
"""
|
| 206 |
+
self.vae.enable_tiling()
|
| 207 |
+
|
| 208 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
|
| 209 |
+
def disable_vae_tiling(self):
|
| 210 |
+
r"""
|
| 211 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
| 212 |
+
computing decoding in one step.
|
| 213 |
+
"""
|
| 214 |
+
self.vae.disable_tiling()
|
| 215 |
+
|
| 216 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
|
| 217 |
+
def _encode_prompt(
|
| 218 |
+
self,
|
| 219 |
+
prompt,
|
| 220 |
+
device,
|
| 221 |
+
num_images_per_prompt,
|
| 222 |
+
do_classifier_free_guidance,
|
| 223 |
+
negative_prompt=None,
|
| 224 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 225 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 226 |
+
lora_scale: Optional[float] = None,
|
| 227 |
+
**kwargs,
|
| 228 |
+
):
|
| 229 |
+
deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
|
| 230 |
+
deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
|
| 231 |
+
|
| 232 |
+
prompt_embeds_tuple = self.encode_prompt(
|
| 233 |
+
prompt=prompt,
|
| 234 |
+
device=device,
|
| 235 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 236 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 237 |
+
negative_prompt=negative_prompt,
|
| 238 |
+
prompt_embeds=prompt_embeds,
|
| 239 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 240 |
+
lora_scale=lora_scale,
|
| 241 |
+
**kwargs,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# concatenate for backwards comp
|
| 245 |
+
prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
|
| 246 |
+
|
| 247 |
+
return prompt_embeds
|
| 248 |
+
|
| 249 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
|
| 250 |
+
def encode_prompt(
|
| 251 |
+
self,
|
| 252 |
+
prompt,
|
| 253 |
+
device,
|
| 254 |
+
num_images_per_prompt,
|
| 255 |
+
do_classifier_free_guidance,
|
| 256 |
+
negative_prompt=None,
|
| 257 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 258 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 259 |
+
lora_scale: Optional[float] = None,
|
| 260 |
+
clip_skip: Optional[int] = None,
|
| 261 |
+
):
|
| 262 |
+
r"""
|
| 263 |
+
Encodes the prompt into text encoder hidden states.
|
| 264 |
+
|
| 265 |
+
Args:
|
| 266 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 267 |
+
prompt to be encoded
|
| 268 |
+
device: (`torch.device`):
|
| 269 |
+
torch device
|
| 270 |
+
num_images_per_prompt (`int`):
|
| 271 |
+
number of images that should be generated per prompt
|
| 272 |
+
do_classifier_free_guidance (`bool`):
|
| 273 |
+
whether to use classifier free guidance or not
|
| 274 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 275 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 276 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 277 |
+
less than `1`).
|
| 278 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 279 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 280 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 281 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 282 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 283 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 284 |
+
argument.
|
| 285 |
+
lora_scale (`float`, *optional*):
|
| 286 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 287 |
+
clip_skip (`int`, *optional*):
|
| 288 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 289 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 290 |
+
"""
|
| 291 |
+
# set lora scale so that monkey patched LoRA
|
| 292 |
+
# function of text encoder can correctly access it
|
| 293 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 294 |
+
self._lora_scale = lora_scale
|
| 295 |
+
|
| 296 |
+
# dynamically adjust the LoRA scale
|
| 297 |
+
if not USE_PEFT_BACKEND:
|
| 298 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 299 |
+
else:
|
| 300 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 301 |
+
|
| 302 |
+
if prompt is not None and isinstance(prompt, str):
|
| 303 |
+
batch_size = 1
|
| 304 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 305 |
+
batch_size = len(prompt)
|
| 306 |
+
else:
|
| 307 |
+
batch_size = prompt_embeds.shape[0]
|
| 308 |
+
|
| 309 |
+
if prompt_embeds is None:
|
| 310 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 311 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 312 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 313 |
+
|
| 314 |
+
text_inputs = self.tokenizer(
|
| 315 |
+
prompt,
|
| 316 |
+
padding="max_length",
|
| 317 |
+
max_length=self.tokenizer.model_max_length,
|
| 318 |
+
truncation=True,
|
| 319 |
+
return_tensors="pt",
|
| 320 |
+
)
|
| 321 |
+
text_input_ids = text_inputs.input_ids
|
| 322 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 323 |
+
|
| 324 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 325 |
+
text_input_ids, untruncated_ids
|
| 326 |
+
):
|
| 327 |
+
removed_text = self.tokenizer.batch_decode(
|
| 328 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 329 |
+
)
|
| 330 |
+
logger.warning(
|
| 331 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 332 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 336 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 337 |
+
else:
|
| 338 |
+
attention_mask = None
|
| 339 |
+
|
| 340 |
+
if clip_skip is None:
|
| 341 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 342 |
+
prompt_embeds = prompt_embeds[0]
|
| 343 |
+
else:
|
| 344 |
+
prompt_embeds = self.text_encoder(
|
| 345 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 346 |
+
)
|
| 347 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 348 |
+
# all the hidden states from the encoder layers. Then index into
|
| 349 |
+
# the tuple to access the hidden states from the desired layer.
|
| 350 |
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
| 351 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 352 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 353 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 354 |
+
# layer.
|
| 355 |
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
| 356 |
+
|
| 357 |
+
if self.text_encoder is not None:
|
| 358 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 359 |
+
elif self.unet is not None:
|
| 360 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 361 |
+
else:
|
| 362 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 363 |
+
|
| 364 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 365 |
+
|
| 366 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 367 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 368 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 369 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 370 |
+
|
| 371 |
+
# get unconditional embeddings for classifier free guidance
|
| 372 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 373 |
+
uncond_tokens: List[str]
|
| 374 |
+
if negative_prompt is None:
|
| 375 |
+
uncond_tokens = [""] * batch_size
|
| 376 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 377 |
+
raise TypeError(
|
| 378 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 379 |
+
f" {type(prompt)}."
|
| 380 |
+
)
|
| 381 |
+
elif isinstance(negative_prompt, str):
|
| 382 |
+
uncond_tokens = [negative_prompt]
|
| 383 |
+
elif batch_size != len(negative_prompt):
|
| 384 |
+
raise ValueError(
|
| 385 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 386 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 387 |
+
" the batch size of `prompt`."
|
| 388 |
+
)
|
| 389 |
+
else:
|
| 390 |
+
uncond_tokens = negative_prompt
|
| 391 |
+
|
| 392 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 393 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 394 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 395 |
+
|
| 396 |
+
max_length = prompt_embeds.shape[1]
|
| 397 |
+
uncond_input = self.tokenizer(
|
| 398 |
+
uncond_tokens,
|
| 399 |
+
padding="max_length",
|
| 400 |
+
max_length=max_length,
|
| 401 |
+
truncation=True,
|
| 402 |
+
return_tensors="pt",
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 406 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 407 |
+
else:
|
| 408 |
+
attention_mask = None
|
| 409 |
+
|
| 410 |
+
negative_prompt_embeds = self.text_encoder(
|
| 411 |
+
uncond_input.input_ids.to(device),
|
| 412 |
+
attention_mask=attention_mask,
|
| 413 |
+
)
|
| 414 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 415 |
+
|
| 416 |
+
if do_classifier_free_guidance:
|
| 417 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 418 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 419 |
+
|
| 420 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 421 |
+
|
| 422 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 423 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 424 |
+
|
| 425 |
+
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 426 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 427 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 428 |
+
|
| 429 |
+
return prompt_embeds, negative_prompt_embeds
|
| 430 |
+
|
| 431 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
| 432 |
+
def run_safety_checker(self, image, device, dtype):
|
| 433 |
+
if self.safety_checker is None:
|
| 434 |
+
has_nsfw_concept = None
|
| 435 |
+
else:
|
| 436 |
+
if torch.is_tensor(image):
|
| 437 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
| 438 |
+
else:
|
| 439 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
| 440 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
| 441 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 442 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 443 |
+
)
|
| 444 |
+
return image, has_nsfw_concept
|
| 445 |
+
|
| 446 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
|
| 447 |
+
def decode_latents(self, latents):
|
| 448 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 449 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 450 |
+
|
| 451 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 452 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 453 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 454 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 455 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 456 |
+
return image
|
| 457 |
+
|
| 458 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 459 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 460 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 461 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 462 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 463 |
+
# and should be between [0, 1]
|
| 464 |
+
|
| 465 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 466 |
+
extra_step_kwargs = {}
|
| 467 |
+
if accepts_eta:
|
| 468 |
+
extra_step_kwargs["eta"] = eta
|
| 469 |
+
|
| 470 |
+
# check if the scheduler accepts generator
|
| 471 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 472 |
+
if accepts_generator:
|
| 473 |
+
extra_step_kwargs["generator"] = generator
|
| 474 |
+
return extra_step_kwargs
|
| 475 |
+
|
| 476 |
+
def check_inputs(
|
| 477 |
+
self,
|
| 478 |
+
prompt,
|
| 479 |
+
image,
|
| 480 |
+
callback_steps,
|
| 481 |
+
negative_prompt=None,
|
| 482 |
+
prompt_embeds=None,
|
| 483 |
+
negative_prompt_embeds=None,
|
| 484 |
+
controlnet_conditioning_scale=1.0,
|
| 485 |
+
control_guidance_start=0.0,
|
| 486 |
+
control_guidance_end=1.0,
|
| 487 |
+
):
|
| 488 |
+
if (callback_steps is None) or (
|
| 489 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 490 |
+
):
|
| 491 |
+
raise ValueError(
|
| 492 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 493 |
+
f" {type(callback_steps)}."
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
if prompt is not None and prompt_embeds is not None:
|
| 497 |
+
raise ValueError(
|
| 498 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 499 |
+
" only forward one of the two."
|
| 500 |
+
)
|
| 501 |
+
elif prompt is None and prompt_embeds is None:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 504 |
+
)
|
| 505 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 506 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 507 |
+
|
| 508 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 509 |
+
raise ValueError(
|
| 510 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 511 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 515 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 516 |
+
raise ValueError(
|
| 517 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 518 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 519 |
+
f" {negative_prompt_embeds.shape}."
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# `prompt` needs more sophisticated handling when there are multiple
|
| 523 |
+
# conditionings.
|
| 524 |
+
if isinstance(self.controlnet, MultiControlNetModel):
|
| 525 |
+
if isinstance(prompt, list):
|
| 526 |
+
logger.warning(
|
| 527 |
+
f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
|
| 528 |
+
" prompts. The conditionings will be fixed across the prompts."
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
# Check `image`
|
| 532 |
+
is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
|
| 533 |
+
self.controlnet, torch._dynamo.eval_frame.OptimizedModule
|
| 534 |
+
)
|
| 535 |
+
if (
|
| 536 |
+
isinstance(self.controlnet, ControlNetModel)
|
| 537 |
+
or is_compiled
|
| 538 |
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
| 539 |
+
):
|
| 540 |
+
self.check_image(image, prompt, prompt_embeds)
|
| 541 |
+
elif (
|
| 542 |
+
isinstance(self.controlnet, MultiControlNetModel)
|
| 543 |
+
or is_compiled
|
| 544 |
+
and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
|
| 545 |
+
):
|
| 546 |
+
if not isinstance(image, list):
|
| 547 |
+
raise TypeError("For multiple controlnets: `image` must be type `list`")
|
| 548 |
+
|
| 549 |
+
# When `image` is a nested list:
|
| 550 |
+
# (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
|
| 551 |
+
elif any(isinstance(i, list) for i in image):
|
| 552 |
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
| 553 |
+
elif len(image) != len(self.controlnet.nets):
|
| 554 |
+
raise ValueError(
|
| 555 |
+
f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
for image_ in image:
|
| 559 |
+
self.check_image(image_, prompt, prompt_embeds)
|
| 560 |
+
else:
|
| 561 |
+
assert False
|
| 562 |
+
|
| 563 |
+
# Check `controlnet_conditioning_scale`
|
| 564 |
+
if (
|
| 565 |
+
isinstance(self.controlnet, ControlNetModel)
|
| 566 |
+
or is_compiled
|
| 567 |
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
| 568 |
+
):
|
| 569 |
+
if not isinstance(controlnet_conditioning_scale, float):
|
| 570 |
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
| 571 |
+
elif (
|
| 572 |
+
isinstance(self.controlnet, MultiControlNetModel)
|
| 573 |
+
or is_compiled
|
| 574 |
+
and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
|
| 575 |
+
):
|
| 576 |
+
if isinstance(controlnet_conditioning_scale, list):
|
| 577 |
+
if any(isinstance(i, list) for i in controlnet_conditioning_scale):
|
| 578 |
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
| 579 |
+
elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
|
| 580 |
+
self.controlnet.nets
|
| 581 |
+
):
|
| 582 |
+
raise ValueError(
|
| 583 |
+
"For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
|
| 584 |
+
" the same length as the number of controlnets"
|
| 585 |
+
)
|
| 586 |
+
else:
|
| 587 |
+
assert False
|
| 588 |
+
|
| 589 |
+
if not isinstance(control_guidance_start, (tuple, list)):
|
| 590 |
+
control_guidance_start = [control_guidance_start]
|
| 591 |
+
|
| 592 |
+
if not isinstance(control_guidance_end, (tuple, list)):
|
| 593 |
+
control_guidance_end = [control_guidance_end]
|
| 594 |
+
|
| 595 |
+
if len(control_guidance_start) != len(control_guidance_end):
|
| 596 |
+
raise ValueError(
|
| 597 |
+
f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
if isinstance(self.controlnet, MultiControlNetModel):
|
| 601 |
+
if len(control_guidance_start) != len(self.controlnet.nets):
|
| 602 |
+
raise ValueError(
|
| 603 |
+
f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
for start, end in zip(control_guidance_start, control_guidance_end):
|
| 607 |
+
if start >= end:
|
| 608 |
+
raise ValueError(
|
| 609 |
+
f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
|
| 610 |
+
)
|
| 611 |
+
if start < 0.0:
|
| 612 |
+
raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
|
| 613 |
+
if end > 1.0:
|
| 614 |
+
raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
|
| 615 |
+
|
| 616 |
+
def check_image(self, image, prompt, prompt_embeds):
|
| 617 |
+
image_is_pil = isinstance(image, PIL.Image.Image)
|
| 618 |
+
image_is_tensor = isinstance(image, torch.Tensor)
|
| 619 |
+
image_is_np = isinstance(image, np.ndarray)
|
| 620 |
+
image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
|
| 621 |
+
image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
|
| 622 |
+
image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
|
| 623 |
+
|
| 624 |
+
if (
|
| 625 |
+
not image_is_pil
|
| 626 |
+
and not image_is_tensor
|
| 627 |
+
and not image_is_np
|
| 628 |
+
and not image_is_pil_list
|
| 629 |
+
and not image_is_tensor_list
|
| 630 |
+
and not image_is_np_list
|
| 631 |
+
):
|
| 632 |
+
raise TypeError(
|
| 633 |
+
f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
if image_is_pil:
|
| 637 |
+
image_batch_size = 1
|
| 638 |
+
else:
|
| 639 |
+
image_batch_size = len(image)
|
| 640 |
+
|
| 641 |
+
if prompt is not None and isinstance(prompt, str):
|
| 642 |
+
prompt_batch_size = 1
|
| 643 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 644 |
+
prompt_batch_size = len(prompt)
|
| 645 |
+
elif prompt_embeds is not None:
|
| 646 |
+
prompt_batch_size = prompt_embeds.shape[0]
|
| 647 |
+
|
| 648 |
+
if image_batch_size != 1 and image_batch_size != prompt_batch_size:
|
| 649 |
+
raise ValueError(
|
| 650 |
+
f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
def prepare_image(
|
| 654 |
+
self,
|
| 655 |
+
image,
|
| 656 |
+
width,
|
| 657 |
+
height,
|
| 658 |
+
batch_size,
|
| 659 |
+
num_images_per_prompt,
|
| 660 |
+
device,
|
| 661 |
+
dtype,
|
| 662 |
+
do_classifier_free_guidance=False,
|
| 663 |
+
guess_mode=False,
|
| 664 |
+
):
|
| 665 |
+
image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
| 666 |
+
image_batch_size = image.shape[0]
|
| 667 |
+
|
| 668 |
+
if image_batch_size == 1:
|
| 669 |
+
repeat_by = batch_size
|
| 670 |
+
else:
|
| 671 |
+
# image batch size is the same as prompt batch size
|
| 672 |
+
repeat_by = num_images_per_prompt
|
| 673 |
+
|
| 674 |
+
image = image.repeat_interleave(repeat_by, dim=0)
|
| 675 |
+
|
| 676 |
+
image = image.to(device=device, dtype=dtype)
|
| 677 |
+
|
| 678 |
+
if do_classifier_free_guidance and not guess_mode:
|
| 679 |
+
image = torch.cat([image] * 2)
|
| 680 |
+
|
| 681 |
+
return image
|
| 682 |
+
|
| 683 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 684 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 685 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 686 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 687 |
+
raise ValueError(
|
| 688 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 689 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
if latents is None:
|
| 693 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 694 |
+
else:
|
| 695 |
+
latents = latents.to(device)
|
| 696 |
+
|
| 697 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 698 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 699 |
+
return latents
|
| 700 |
+
|
| 701 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
|
| 702 |
+
def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
|
| 703 |
+
r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
|
| 704 |
+
|
| 705 |
+
The suffixes after the scaling factors represent the stages where they are being applied.
|
| 706 |
+
|
| 707 |
+
Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
|
| 708 |
+
that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
|
| 709 |
+
|
| 710 |
+
Args:
|
| 711 |
+
s1 (`float`):
|
| 712 |
+
Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
|
| 713 |
+
mitigate "oversmoothing effect" in the enhanced denoising process.
|
| 714 |
+
s2 (`float`):
|
| 715 |
+
Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
|
| 716 |
+
mitigate "oversmoothing effect" in the enhanced denoising process.
|
| 717 |
+
b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
|
| 718 |
+
b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
|
| 719 |
+
"""
|
| 720 |
+
if not hasattr(self, "unet"):
|
| 721 |
+
raise ValueError("The pipeline must have `unet` for using FreeU.")
|
| 722 |
+
self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
|
| 723 |
+
|
| 724 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
|
| 725 |
+
def disable_freeu(self):
|
| 726 |
+
"""Disables the FreeU mechanism if enabled."""
|
| 727 |
+
self.unet.disable_freeu()
|
| 728 |
+
|
| 729 |
+
@torch.no_grad()
|
| 730 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 731 |
+
def __call__(
|
| 732 |
+
self,
|
| 733 |
+
prompt: Union[str, List[str]] = None,
|
| 734 |
+
image: PipelineImageInput = None,
|
| 735 |
+
height: Optional[int] = None,
|
| 736 |
+
width: Optional[int] = None,
|
| 737 |
+
num_inference_steps: int = 50,
|
| 738 |
+
guidance_scale: float = 7.5,
|
| 739 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 740 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 741 |
+
eta: float = 0.0,
|
| 742 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 743 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 744 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 745 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 746 |
+
output_type: Optional[str] = "pil",
|
| 747 |
+
return_dict: bool = True,
|
| 748 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 749 |
+
callback_steps: int = 1,
|
| 750 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 751 |
+
controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
|
| 752 |
+
guess_mode: bool = False,
|
| 753 |
+
control_guidance_start: Union[float, List[float]] = 0.0,
|
| 754 |
+
control_guidance_end: Union[float, List[float]] = 1.0,
|
| 755 |
+
clip_skip: Optional[int] = None,
|
| 756 |
+
):
|
| 757 |
+
r"""
|
| 758 |
+
The call function to the pipeline for generation.
|
| 759 |
+
|
| 760 |
+
Args:
|
| 761 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 762 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 763 |
+
image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
| 764 |
+
`List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
| 765 |
+
The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
|
| 766 |
+
specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
|
| 767 |
+
accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
|
| 768 |
+
and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
|
| 769 |
+
`init`, images must be passed as a list such that each element of the list can be correctly batched for
|
| 770 |
+
input to a single ControlNet.
|
| 771 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 772 |
+
The height in pixels of the generated image.
|
| 773 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 774 |
+
The width in pixels of the generated image.
|
| 775 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 776 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 777 |
+
expense of slower inference.
|
| 778 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 779 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 780 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 781 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 782 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 783 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 784 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 785 |
+
The number of images to generate per prompt.
|
| 786 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 787 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 788 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 789 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 790 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 791 |
+
generation deterministic.
|
| 792 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 793 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 794 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 795 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 796 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 797 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 798 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 799 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 800 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 801 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 802 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 803 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 804 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 805 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 806 |
+
plain tuple.
|
| 807 |
+
callback (`Callable`, *optional*):
|
| 808 |
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
| 809 |
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 810 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 811 |
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
| 812 |
+
every step.
|
| 813 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 814 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 815 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 816 |
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 817 |
+
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
|
| 818 |
+
to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
|
| 819 |
+
the corresponding scale as a list.
|
| 820 |
+
guess_mode (`bool`, *optional*, defaults to `False`):
|
| 821 |
+
The ControlNet encoder tries to recognize the content of the input image even if you remove all
|
| 822 |
+
prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
|
| 823 |
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
| 824 |
+
The percentage of total steps at which the ControlNet starts applying.
|
| 825 |
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 826 |
+
The percentage of total steps at which the ControlNet stops applying.
|
| 827 |
+
clip_skip (`int`, *optional*):
|
| 828 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 829 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 830 |
+
|
| 831 |
+
Examples:
|
| 832 |
+
|
| 833 |
+
Returns:
|
| 834 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 835 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
| 836 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
| 837 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
| 838 |
+
"not-safe-for-work" (nsfw) content.
|
| 839 |
+
"""
|
| 840 |
+
controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
|
| 841 |
+
|
| 842 |
+
# align format for control guidance
|
| 843 |
+
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
|
| 844 |
+
control_guidance_start = len(control_guidance_end) * [control_guidance_start]
|
| 845 |
+
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
|
| 846 |
+
control_guidance_end = len(control_guidance_start) * [control_guidance_end]
|
| 847 |
+
elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
|
| 848 |
+
mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
|
| 849 |
+
control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [
|
| 850 |
+
control_guidance_end
|
| 851 |
+
]
|
| 852 |
+
|
| 853 |
+
# 1. Check inputs. Raise error if not correct
|
| 854 |
+
self.check_inputs(
|
| 855 |
+
prompt,
|
| 856 |
+
image,
|
| 857 |
+
callback_steps,
|
| 858 |
+
negative_prompt,
|
| 859 |
+
prompt_embeds,
|
| 860 |
+
negative_prompt_embeds,
|
| 861 |
+
controlnet_conditioning_scale,
|
| 862 |
+
control_guidance_start,
|
| 863 |
+
control_guidance_end,
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
# 2. Define call parameters
|
| 867 |
+
if prompt is not None and isinstance(prompt, str):
|
| 868 |
+
batch_size = 1
|
| 869 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 870 |
+
batch_size = len(prompt)
|
| 871 |
+
else:
|
| 872 |
+
batch_size = prompt_embeds.shape[0]
|
| 873 |
+
|
| 874 |
+
device = self._execution_device
|
| 875 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 876 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 877 |
+
# corresponds to doing no classifier free guidance.
|
| 878 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 879 |
+
|
| 880 |
+
if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
|
| 881 |
+
controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
|
| 882 |
+
|
| 883 |
+
global_pool_conditions = (
|
| 884 |
+
controlnet.config.global_pool_conditions
|
| 885 |
+
if isinstance(controlnet, ControlNetModel)
|
| 886 |
+
else controlnet.nets[0].config.global_pool_conditions
|
| 887 |
+
)
|
| 888 |
+
guess_mode = guess_mode or global_pool_conditions
|
| 889 |
+
|
| 890 |
+
# 3. Encode input prompt
|
| 891 |
+
text_encoder_lora_scale = (
|
| 892 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 893 |
+
)
|
| 894 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 895 |
+
prompt,
|
| 896 |
+
device,
|
| 897 |
+
num_images_per_prompt,
|
| 898 |
+
do_classifier_free_guidance,
|
| 899 |
+
negative_prompt,
|
| 900 |
+
prompt_embeds=prompt_embeds,
|
| 901 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 902 |
+
lora_scale=text_encoder_lora_scale,
|
| 903 |
+
clip_skip=clip_skip,
|
| 904 |
+
)
|
| 905 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 906 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 907 |
+
# to avoid doing two forward passes
|
| 908 |
+
if do_classifier_free_guidance:
|
| 909 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 910 |
+
|
| 911 |
+
# 4. Prepare image
|
| 912 |
+
if isinstance(controlnet, ControlNetModel):
|
| 913 |
+
image = self.prepare_image(
|
| 914 |
+
image=image,
|
| 915 |
+
width=width,
|
| 916 |
+
height=height,
|
| 917 |
+
batch_size=batch_size * num_images_per_prompt,
|
| 918 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 919 |
+
device=device,
|
| 920 |
+
dtype=controlnet.dtype,
|
| 921 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 922 |
+
guess_mode=guess_mode,
|
| 923 |
+
)
|
| 924 |
+
height, width = image.shape[-2:]
|
| 925 |
+
elif isinstance(controlnet, MultiControlNetModel):
|
| 926 |
+
images = []
|
| 927 |
+
|
| 928 |
+
for image_ in image:
|
| 929 |
+
image_ = self.prepare_image(
|
| 930 |
+
image=image_,
|
| 931 |
+
width=width,
|
| 932 |
+
height=height,
|
| 933 |
+
batch_size=batch_size * num_images_per_prompt,
|
| 934 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 935 |
+
device=device,
|
| 936 |
+
dtype=controlnet.dtype,
|
| 937 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 938 |
+
guess_mode=guess_mode,
|
| 939 |
+
)
|
| 940 |
+
|
| 941 |
+
images.append(image_)
|
| 942 |
+
|
| 943 |
+
image = images
|
| 944 |
+
height, width = image[0].shape[-2:]
|
| 945 |
+
else:
|
| 946 |
+
assert False
|
| 947 |
+
|
| 948 |
+
# 5. Prepare timesteps
|
| 949 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 950 |
+
timesteps = self.scheduler.timesteps
|
| 951 |
+
|
| 952 |
+
# 6. Prepare latent variables
|
| 953 |
+
num_channels_latents = self.unet.config.in_channels
|
| 954 |
+
latents = self.prepare_latents(
|
| 955 |
+
batch_size * num_images_per_prompt,
|
| 956 |
+
num_channels_latents,
|
| 957 |
+
height,
|
| 958 |
+
width,
|
| 959 |
+
prompt_embeds.dtype,
|
| 960 |
+
device,
|
| 961 |
+
generator,
|
| 962 |
+
latents,
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 966 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 967 |
+
|
| 968 |
+
# 7.1 Create tensor stating which controlnets to keep
|
| 969 |
+
controlnet_keep = []
|
| 970 |
+
for i in range(len(timesteps)):
|
| 971 |
+
keeps = [
|
| 972 |
+
1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
|
| 973 |
+
for s, e in zip(control_guidance_start, control_guidance_end)
|
| 974 |
+
]
|
| 975 |
+
controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
|
| 976 |
+
|
| 977 |
+
# 8. Denoising loop
|
| 978 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 979 |
+
is_unet_compiled = is_compiled_module(self.unet)
|
| 980 |
+
is_controlnet_compiled = is_compiled_module(self.controlnet)
|
| 981 |
+
is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
|
| 982 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 983 |
+
for i, t in enumerate(timesteps):
|
| 984 |
+
# Relevant thread:
|
| 985 |
+
# https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
|
| 986 |
+
if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
|
| 987 |
+
torch._inductor.cudagraph_mark_step_begin()
|
| 988 |
+
# expand the latents if we are doing classifier free guidance
|
| 989 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 990 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 991 |
+
|
| 992 |
+
# controlnet(s) inference
|
| 993 |
+
null_text_inputs = self.tokenizer(
|
| 994 |
+
"", max_length=self.tokenizer.model_max_length, padding="max_length", truncation=True,
|
| 995 |
+
return_tensors="pt"
|
| 996 |
+
).input_ids
|
| 997 |
+
null_text_embeds = self.text_encoder(null_text_inputs.to(device=self.device))[0]
|
| 998 |
+
if guess_mode and do_classifier_free_guidance:
|
| 999 |
+
# Infer ControlNet only for the conditional batch.
|
| 1000 |
+
control_model_input = latents
|
| 1001 |
+
control_model_input = self.scheduler.scale_model_input(control_model_input, t)
|
| 1002 |
+
# controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
|
| 1003 |
+
controlnet_prompt_embeds = null_text_embeds.repeat(batch_size*2, 1, 1)
|
| 1004 |
+
else:
|
| 1005 |
+
control_model_input = latent_model_input
|
| 1006 |
+
# controlnet_prompt_embeds = prompt_embeds
|
| 1007 |
+
controlnet_prompt_embeds = null_text_embeds.repeat(batch_size*2, 1, 1)
|
| 1008 |
+
|
| 1009 |
+
if isinstance(controlnet_keep[i], list):
|
| 1010 |
+
cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
|
| 1011 |
+
else:
|
| 1012 |
+
controlnet_cond_scale = controlnet_conditioning_scale
|
| 1013 |
+
if isinstance(controlnet_cond_scale, list):
|
| 1014 |
+
controlnet_cond_scale = controlnet_cond_scale[0]
|
| 1015 |
+
cond_scale = controlnet_cond_scale * controlnet_keep[i]
|
| 1016 |
+
|
| 1017 |
+
down_block_res_samples, mid_block_res_sample = self.controlnet(
|
| 1018 |
+
control_model_input,
|
| 1019 |
+
t,
|
| 1020 |
+
encoder_hidden_states=controlnet_prompt_embeds,
|
| 1021 |
+
controlnet_cond=image,
|
| 1022 |
+
conditioning_scale=cond_scale,
|
| 1023 |
+
guess_mode=guess_mode,
|
| 1024 |
+
return_dict=False,
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
if guess_mode and do_classifier_free_guidance:
|
| 1028 |
+
# Infered ControlNet only for the conditional batch.
|
| 1029 |
+
# To apply the output of ControlNet to both the unconditional and conditional batches,
|
| 1030 |
+
# add 0 to the unconditional batch to keep it unchanged.
|
| 1031 |
+
down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
|
| 1032 |
+
mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
|
| 1033 |
+
|
| 1034 |
+
# predict the noise residual
|
| 1035 |
+
noise_pred = self.unet(
|
| 1036 |
+
latent_model_input,
|
| 1037 |
+
t,
|
| 1038 |
+
encoder_hidden_states=prompt_embeds,
|
| 1039 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 1040 |
+
down_block_additional_residuals=down_block_res_samples,
|
| 1041 |
+
mid_block_additional_residual=mid_block_res_sample,
|
| 1042 |
+
return_dict=False,
|
| 1043 |
+
)[0]
|
| 1044 |
+
|
| 1045 |
+
# perform guidance
|
| 1046 |
+
if do_classifier_free_guidance:
|
| 1047 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 1048 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 1049 |
+
|
| 1050 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 1051 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 1052 |
+
|
| 1053 |
+
# call the callback, if provided
|
| 1054 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 1055 |
+
progress_bar.update()
|
| 1056 |
+
if callback is not None and i % callback_steps == 0:
|
| 1057 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 1058 |
+
callback(step_idx, t, latents)
|
| 1059 |
+
|
| 1060 |
+
# If we do sequential model offloading, let's offload unet and controlnet
|
| 1061 |
+
# manually for max memory savings
|
| 1062 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 1063 |
+
self.unet.to("cpu")
|
| 1064 |
+
self.controlnet.to("cpu")
|
| 1065 |
+
torch.cuda.empty_cache()
|
| 1066 |
+
|
| 1067 |
+
if not output_type == "latent":
|
| 1068 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
| 1069 |
+
0
|
| 1070 |
+
]
|
| 1071 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
| 1072 |
+
else:
|
| 1073 |
+
image = latents
|
| 1074 |
+
has_nsfw_concept = None
|
| 1075 |
+
|
| 1076 |
+
if has_nsfw_concept is None:
|
| 1077 |
+
do_denormalize = [True] * image.shape[0]
|
| 1078 |
+
else:
|
| 1079 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 1080 |
+
|
| 1081 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 1082 |
+
|
| 1083 |
+
# Offload all models
|
| 1084 |
+
self.maybe_free_model_hooks()
|
| 1085 |
+
|
| 1086 |
+
if not return_dict:
|
| 1087 |
+
return (image, has_nsfw_concept)
|
| 1088 |
+
|
| 1089 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
| 1093 |
+
"""
|
| 1094 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
| 1095 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
| 1096 |
+
"""
|
| 1097 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
| 1098 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
| 1099 |
+
# rescale the results from guidance (fixes overexposure)
|
| 1100 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
| 1101 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
| 1102 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
| 1103 |
+
return noise_cfg
|
| 1104 |
+
|
| 1105 |
+
|
| 1106 |
+
class StableDiffusionPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin):
|
| 1107 |
+
r"""
|
| 1108 |
+
Pipeline for text-to-image generation using Stable Diffusion.
|
| 1109 |
+
|
| 1110 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 1111 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 1112 |
+
|
| 1113 |
+
The pipeline also inherits the following loading methods:
|
| 1114 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 1115 |
+
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
| 1116 |
+
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
| 1117 |
+
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
| 1118 |
+
|
| 1119 |
+
Args:
|
| 1120 |
+
vae ([`AutoencoderKL`]):
|
| 1121 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 1122 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
| 1123 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 1124 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
| 1125 |
+
A `CLIPTokenizer` to tokenize text.
|
| 1126 |
+
unet ([`UNet2DConditionModel`]):
|
| 1127 |
+
A `UNet2DConditionModel` to denoise the encoded image latents.
|
| 1128 |
+
scheduler ([`SchedulerMixin`]):
|
| 1129 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 1130 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 1131 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 1132 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 1133 |
+
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
| 1134 |
+
about a model's potential harms.
|
| 1135 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 1136 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 1137 |
+
"""
|
| 1138 |
+
model_cpu_offload_seq = "text_encoder->unet->vae"
|
| 1139 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
| 1140 |
+
_exclude_from_cpu_offload = ["safety_checker"]
|
| 1141 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 1142 |
+
|
| 1143 |
+
def __init__(
|
| 1144 |
+
self,
|
| 1145 |
+
vae: AutoencoderKL,
|
| 1146 |
+
text_encoder: CLIPTextModel,
|
| 1147 |
+
tokenizer: CLIPTokenizer,
|
| 1148 |
+
unet: UNet2DConditionModel,
|
| 1149 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 1150 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 1151 |
+
feature_extractor: CLIPImageProcessor,
|
| 1152 |
+
requires_safety_checker: bool = True,
|
| 1153 |
+
):
|
| 1154 |
+
super().__init__()
|
| 1155 |
+
self.register_modules(
|
| 1156 |
+
vae=vae,
|
| 1157 |
+
text_encoder=text_encoder,
|
| 1158 |
+
tokenizer=tokenizer,
|
| 1159 |
+
unet=unet,
|
| 1160 |
+
scheduler=scheduler,
|
| 1161 |
+
safety_checker=safety_checker,
|
| 1162 |
+
feature_extractor=feature_extractor,
|
| 1163 |
+
)
|
| 1164 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 1165 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 1166 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 1167 |
+
|
| 1168 |
+
def enable_vae_slicing(self):
|
| 1169 |
+
r"""
|
| 1170 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 1171 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 1172 |
+
"""
|
| 1173 |
+
self.vae.enable_slicing()
|
| 1174 |
+
|
| 1175 |
+
def disable_vae_slicing(self):
|
| 1176 |
+
r"""
|
| 1177 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
| 1178 |
+
computing decoding in one step.
|
| 1179 |
+
"""
|
| 1180 |
+
self.vae.disable_slicing()
|
| 1181 |
+
|
| 1182 |
+
def enable_vae_tiling(self):
|
| 1183 |
+
r"""
|
| 1184 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 1185 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 1186 |
+
processing larger images.
|
| 1187 |
+
"""
|
| 1188 |
+
self.vae.enable_tiling()
|
| 1189 |
+
|
| 1190 |
+
def disable_vae_tiling(self):
|
| 1191 |
+
r"""
|
| 1192 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
| 1193 |
+
computing decoding in one step.
|
| 1194 |
+
"""
|
| 1195 |
+
self.vae.disable_tiling()
|
| 1196 |
+
|
| 1197 |
+
def _encode_prompt(
|
| 1198 |
+
self,
|
| 1199 |
+
prompt,
|
| 1200 |
+
device,
|
| 1201 |
+
num_images_per_prompt,
|
| 1202 |
+
do_classifier_free_guidance,
|
| 1203 |
+
negative_prompt=None,
|
| 1204 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 1205 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 1206 |
+
lora_scale: Optional[float] = None,
|
| 1207 |
+
**kwargs,
|
| 1208 |
+
):
|
| 1209 |
+
deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
|
| 1210 |
+
deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
|
| 1211 |
+
|
| 1212 |
+
prompt_embeds_tuple = self.encode_prompt(
|
| 1213 |
+
prompt=prompt,
|
| 1214 |
+
device=device,
|
| 1215 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 1216 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 1217 |
+
negative_prompt=negative_prompt,
|
| 1218 |
+
prompt_embeds=prompt_embeds,
|
| 1219 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1220 |
+
lora_scale=lora_scale,
|
| 1221 |
+
**kwargs,
|
| 1222 |
+
)
|
| 1223 |
+
|
| 1224 |
+
# concatenate for backwards comp
|
| 1225 |
+
prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
|
| 1226 |
+
|
| 1227 |
+
return prompt_embeds
|
| 1228 |
+
|
| 1229 |
+
def encode_prompt(
|
| 1230 |
+
self,
|
| 1231 |
+
prompt,
|
| 1232 |
+
device,
|
| 1233 |
+
num_images_per_prompt,
|
| 1234 |
+
do_classifier_free_guidance,
|
| 1235 |
+
negative_prompt=None,
|
| 1236 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 1237 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 1238 |
+
lora_scale: Optional[float] = None,
|
| 1239 |
+
clip_skip: Optional[int] = None,
|
| 1240 |
+
):
|
| 1241 |
+
r"""
|
| 1242 |
+
Encodes the prompt into text encoder hidden states.
|
| 1243 |
+
|
| 1244 |
+
Args:
|
| 1245 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 1246 |
+
prompt to be encoded
|
| 1247 |
+
device: (`torch.device`):
|
| 1248 |
+
torch device
|
| 1249 |
+
num_images_per_prompt (`int`):
|
| 1250 |
+
number of images that should be generated per prompt
|
| 1251 |
+
do_classifier_free_guidance (`bool`):
|
| 1252 |
+
whether to use classifier free guidance or not
|
| 1253 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 1254 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 1255 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 1256 |
+
less than `1`).
|
| 1257 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 1258 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 1259 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 1260 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 1261 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 1262 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 1263 |
+
argument.
|
| 1264 |
+
lora_scale (`float`, *optional*):
|
| 1265 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 1266 |
+
clip_skip (`int`, *optional*):
|
| 1267 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 1268 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 1269 |
+
"""
|
| 1270 |
+
# set lora scale so that monkey patched LoRA
|
| 1271 |
+
# function of text encoder can correctly access it
|
| 1272 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 1273 |
+
self._lora_scale = lora_scale
|
| 1274 |
+
|
| 1275 |
+
# dynamically adjust the LoRA scale
|
| 1276 |
+
if not USE_PEFT_BACKEND:
|
| 1277 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 1278 |
+
else:
|
| 1279 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 1280 |
+
|
| 1281 |
+
if prompt is not None and isinstance(prompt, str):
|
| 1282 |
+
batch_size = 1
|
| 1283 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1284 |
+
batch_size = len(prompt)
|
| 1285 |
+
else:
|
| 1286 |
+
batch_size = prompt_embeds.shape[0]
|
| 1287 |
+
|
| 1288 |
+
if prompt_embeds is None:
|
| 1289 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 1290 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 1291 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 1292 |
+
|
| 1293 |
+
text_inputs = self.tokenizer(
|
| 1294 |
+
prompt,
|
| 1295 |
+
padding="max_length",
|
| 1296 |
+
max_length=self.tokenizer.model_max_length,
|
| 1297 |
+
truncation=True,
|
| 1298 |
+
return_tensors="pt",
|
| 1299 |
+
)
|
| 1300 |
+
text_input_ids = text_inputs.input_ids
|
| 1301 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 1302 |
+
|
| 1303 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 1304 |
+
text_input_ids, untruncated_ids
|
| 1305 |
+
):
|
| 1306 |
+
removed_text = self.tokenizer.batch_decode(
|
| 1307 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 1308 |
+
)
|
| 1309 |
+
logger.warning(
|
| 1310 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 1311 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 1312 |
+
)
|
| 1313 |
+
|
| 1314 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 1315 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 1316 |
+
else:
|
| 1317 |
+
attention_mask = None
|
| 1318 |
+
|
| 1319 |
+
if clip_skip is None:
|
| 1320 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 1321 |
+
prompt_embeds = prompt_embeds[0]
|
| 1322 |
+
else:
|
| 1323 |
+
prompt_embeds = self.text_encoder(
|
| 1324 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 1325 |
+
)
|
| 1326 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 1327 |
+
# all the hidden states from the encoder layers. Then index into
|
| 1328 |
+
# the tuple to access the hidden states from the desired layer.
|
| 1329 |
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
| 1330 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 1331 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 1332 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 1333 |
+
# layer.
|
| 1334 |
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
| 1335 |
+
|
| 1336 |
+
if self.text_encoder is not None:
|
| 1337 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 1338 |
+
elif self.unet is not None:
|
| 1339 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 1340 |
+
else:
|
| 1341 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 1342 |
+
|
| 1343 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 1344 |
+
|
| 1345 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 1346 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 1347 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 1348 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 1349 |
+
|
| 1350 |
+
# get unconditional embeddings for classifier free guidance
|
| 1351 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 1352 |
+
uncond_tokens: List[str]
|
| 1353 |
+
if negative_prompt is None:
|
| 1354 |
+
uncond_tokens = [""] * batch_size
|
| 1355 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 1356 |
+
raise TypeError(
|
| 1357 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 1358 |
+
f" {type(prompt)}."
|
| 1359 |
+
)
|
| 1360 |
+
elif isinstance(negative_prompt, str):
|
| 1361 |
+
uncond_tokens = [negative_prompt]
|
| 1362 |
+
elif batch_size != len(negative_prompt):
|
| 1363 |
+
raise ValueError(
|
| 1364 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 1365 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 1366 |
+
" the batch size of `prompt`."
|
| 1367 |
+
)
|
| 1368 |
+
else:
|
| 1369 |
+
uncond_tokens = negative_prompt
|
| 1370 |
+
|
| 1371 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 1372 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 1373 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 1374 |
+
|
| 1375 |
+
max_length = prompt_embeds.shape[1]
|
| 1376 |
+
uncond_input = self.tokenizer(
|
| 1377 |
+
uncond_tokens,
|
| 1378 |
+
padding="max_length",
|
| 1379 |
+
max_length=max_length,
|
| 1380 |
+
truncation=True,
|
| 1381 |
+
return_tensors="pt",
|
| 1382 |
+
)
|
| 1383 |
+
|
| 1384 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 1385 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 1386 |
+
else:
|
| 1387 |
+
attention_mask = None
|
| 1388 |
+
|
| 1389 |
+
negative_prompt_embeds = self.text_encoder(
|
| 1390 |
+
uncond_input.input_ids.to(device),
|
| 1391 |
+
attention_mask=attention_mask,
|
| 1392 |
+
)
|
| 1393 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 1394 |
+
|
| 1395 |
+
if do_classifier_free_guidance:
|
| 1396 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 1397 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 1398 |
+
|
| 1399 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 1400 |
+
|
| 1401 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 1402 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 1403 |
+
|
| 1404 |
+
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 1405 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 1406 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 1407 |
+
|
| 1408 |
+
return prompt_embeds, negative_prompt_embeds
|
| 1409 |
+
|
| 1410 |
+
def run_safety_checker(self, image, device, dtype):
|
| 1411 |
+
if self.safety_checker is None:
|
| 1412 |
+
has_nsfw_concept = None
|
| 1413 |
+
else:
|
| 1414 |
+
if torch.is_tensor(image):
|
| 1415 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
| 1416 |
+
else:
|
| 1417 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
| 1418 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
| 1419 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 1420 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 1421 |
+
)
|
| 1422 |
+
return image, has_nsfw_concept
|
| 1423 |
+
|
| 1424 |
+
def decode_latents(self, latents):
|
| 1425 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 1426 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 1427 |
+
|
| 1428 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 1429 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 1430 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 1431 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 1432 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 1433 |
+
return image
|
| 1434 |
+
|
| 1435 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 1436 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 1437 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 1438 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 1439 |
+
# and should be between [0, 1]
|
| 1440 |
+
|
| 1441 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 1442 |
+
extra_step_kwargs = {}
|
| 1443 |
+
if accepts_eta:
|
| 1444 |
+
extra_step_kwargs["eta"] = eta
|
| 1445 |
+
|
| 1446 |
+
# check if the scheduler accepts generator
|
| 1447 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 1448 |
+
if accepts_generator:
|
| 1449 |
+
extra_step_kwargs["generator"] = generator
|
| 1450 |
+
return extra_step_kwargs
|
| 1451 |
+
|
| 1452 |
+
def check_inputs(
|
| 1453 |
+
self,
|
| 1454 |
+
prompt,
|
| 1455 |
+
height,
|
| 1456 |
+
width,
|
| 1457 |
+
callback_steps,
|
| 1458 |
+
negative_prompt=None,
|
| 1459 |
+
prompt_embeds=None,
|
| 1460 |
+
negative_prompt_embeds=None,
|
| 1461 |
+
callback_on_step_end_tensor_inputs=None,
|
| 1462 |
+
):
|
| 1463 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 1464 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 1465 |
+
|
| 1466 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 1467 |
+
raise ValueError(
|
| 1468 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 1469 |
+
f" {type(callback_steps)}."
|
| 1470 |
+
)
|
| 1471 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 1472 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 1473 |
+
):
|
| 1474 |
+
raise ValueError(
|
| 1475 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 1476 |
+
)
|
| 1477 |
+
|
| 1478 |
+
if prompt is not None and prompt_embeds is not None:
|
| 1479 |
+
raise ValueError(
|
| 1480 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 1481 |
+
" only forward one of the two."
|
| 1482 |
+
)
|
| 1483 |
+
elif prompt is None and prompt_embeds is None:
|
| 1484 |
+
raise ValueError(
|
| 1485 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 1486 |
+
)
|
| 1487 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 1488 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 1489 |
+
|
| 1490 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 1491 |
+
raise ValueError(
|
| 1492 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 1493 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 1494 |
+
)
|
| 1495 |
+
|
| 1496 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 1497 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 1498 |
+
raise ValueError(
|
| 1499 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 1500 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 1501 |
+
f" {negative_prompt_embeds.shape}."
|
| 1502 |
+
)
|
| 1503 |
+
|
| 1504 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 1505 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 1506 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 1507 |
+
raise ValueError(
|
| 1508 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 1509 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 1510 |
+
)
|
| 1511 |
+
|
| 1512 |
+
if latents is None:
|
| 1513 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 1514 |
+
else:
|
| 1515 |
+
latents = latents.to(device)
|
| 1516 |
+
|
| 1517 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 1518 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 1519 |
+
return latents
|
| 1520 |
+
|
| 1521 |
+
def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
|
| 1522 |
+
r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
|
| 1523 |
+
|
| 1524 |
+
The suffixes after the scaling factors represent the stages where they are being applied.
|
| 1525 |
+
|
| 1526 |
+
Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
|
| 1527 |
+
that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
|
| 1528 |
+
|
| 1529 |
+
Args:
|
| 1530 |
+
s1 (`float`):
|
| 1531 |
+
Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
|
| 1532 |
+
mitigate "oversmoothing effect" in the enhanced denoising process.
|
| 1533 |
+
s2 (`float`):
|
| 1534 |
+
Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
|
| 1535 |
+
mitigate "oversmoothing effect" in the enhanced denoising process.
|
| 1536 |
+
b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
|
| 1537 |
+
b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
|
| 1538 |
+
"""
|
| 1539 |
+
if not hasattr(self, "unet"):
|
| 1540 |
+
raise ValueError("The pipeline must have `unet` for using FreeU.")
|
| 1541 |
+
self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
|
| 1542 |
+
|
| 1543 |
+
def disable_freeu(self):
|
| 1544 |
+
"""Disables the FreeU mechanism if enabled."""
|
| 1545 |
+
self.unet.disable_freeu()
|
| 1546 |
+
|
| 1547 |
+
# Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
|
| 1548 |
+
def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
|
| 1549 |
+
"""
|
| 1550 |
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
| 1551 |
+
|
| 1552 |
+
Args:
|
| 1553 |
+
timesteps (`torch.Tensor`):
|
| 1554 |
+
generate embedding vectors at these timesteps
|
| 1555 |
+
embedding_dim (`int`, *optional*, defaults to 512):
|
| 1556 |
+
dimension of the embeddings to generate
|
| 1557 |
+
dtype:
|
| 1558 |
+
data type of the generated embeddings
|
| 1559 |
+
|
| 1560 |
+
Returns:
|
| 1561 |
+
`torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
|
| 1562 |
+
"""
|
| 1563 |
+
assert len(w.shape) == 1
|
| 1564 |
+
w = w * 1000.0
|
| 1565 |
+
|
| 1566 |
+
half_dim = embedding_dim // 2
|
| 1567 |
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
| 1568 |
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
| 1569 |
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
| 1570 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 1571 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 1572 |
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
| 1573 |
+
assert emb.shape == (w.shape[0], embedding_dim)
|
| 1574 |
+
return emb
|
| 1575 |
+
|
| 1576 |
+
@property
|
| 1577 |
+
def guidance_scale(self):
|
| 1578 |
+
return self._guidance_scale
|
| 1579 |
+
|
| 1580 |
+
@property
|
| 1581 |
+
def guidance_rescale(self):
|
| 1582 |
+
return self._guidance_rescale
|
| 1583 |
+
|
| 1584 |
+
@property
|
| 1585 |
+
def clip_skip(self):
|
| 1586 |
+
return self._clip_skip
|
| 1587 |
+
|
| 1588 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 1589 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 1590 |
+
# corresponds to doing no classifier free guidance.
|
| 1591 |
+
@property
|
| 1592 |
+
def do_classifier_free_guidance(self):
|
| 1593 |
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
| 1594 |
+
|
| 1595 |
+
@property
|
| 1596 |
+
def cross_attention_kwargs(self):
|
| 1597 |
+
return self._cross_attention_kwargs
|
| 1598 |
+
|
| 1599 |
+
@property
|
| 1600 |
+
def num_timesteps(self):
|
| 1601 |
+
return self._num_timesteps
|
| 1602 |
+
|
| 1603 |
+
@torch.no_grad()
|
| 1604 |
+
def __call__(
|
| 1605 |
+
self,
|
| 1606 |
+
prompt: Union[str, List[str]] = None,
|
| 1607 |
+
height: Optional[int] = None,
|
| 1608 |
+
width: Optional[int] = None,
|
| 1609 |
+
num_inference_steps: int = 50,
|
| 1610 |
+
guidance_scale: float = 7.5,
|
| 1611 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 1612 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 1613 |
+
eta: float = 0.0,
|
| 1614 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 1615 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 1616 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 1617 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 1618 |
+
output_type: Optional[str] = "pil",
|
| 1619 |
+
return_dict: bool = True,
|
| 1620 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 1621 |
+
guidance_rescale: float = 0.0,
|
| 1622 |
+
clip_skip: Optional[int] = None,
|
| 1623 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 1624 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 1625 |
+
**kwargs,
|
| 1626 |
+
):
|
| 1627 |
+
r"""
|
| 1628 |
+
The call function to the pipeline for generation.
|
| 1629 |
+
|
| 1630 |
+
Args:
|
| 1631 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 1632 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 1633 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 1634 |
+
The height in pixels of the generated image.
|
| 1635 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 1636 |
+
The width in pixels of the generated image.
|
| 1637 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 1638 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 1639 |
+
expense of slower inference.
|
| 1640 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 1641 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 1642 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 1643 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 1644 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 1645 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 1646 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 1647 |
+
The number of images to generate per prompt.
|
| 1648 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 1649 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 1650 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 1651 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 1652 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 1653 |
+
generation deterministic.
|
| 1654 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 1655 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 1656 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 1657 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 1658 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 1659 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 1660 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 1661 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 1662 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 1663 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 1664 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 1665 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 1666 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 1667 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 1668 |
+
plain tuple.
|
| 1669 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 1670 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 1671 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 1672 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
| 1673 |
+
Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
|
| 1674 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
|
| 1675 |
+
using zero terminal SNR.
|
| 1676 |
+
clip_skip (`int`, *optional*):
|
| 1677 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 1678 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 1679 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 1680 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 1681 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 1682 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 1683 |
+
`callback_on_step_end_tensor_inputs`.
|
| 1684 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 1685 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 1686 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 1687 |
+
`._callback_tensor_inputs` attribute of your pipeine class.
|
| 1688 |
+
|
| 1689 |
+
Examples:
|
| 1690 |
+
|
| 1691 |
+
Returns:
|
| 1692 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 1693 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
| 1694 |
+
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
| 1695 |
+
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
| 1696 |
+
"not-safe-for-work" (nsfw) content.
|
| 1697 |
+
"""
|
| 1698 |
+
|
| 1699 |
+
callback = kwargs.pop("callback", None)
|
| 1700 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 1701 |
+
|
| 1702 |
+
if callback is not None:
|
| 1703 |
+
deprecate(
|
| 1704 |
+
"callback",
|
| 1705 |
+
"1.0.0",
|
| 1706 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 1707 |
+
)
|
| 1708 |
+
if callback_steps is not None:
|
| 1709 |
+
deprecate(
|
| 1710 |
+
"callback_steps",
|
| 1711 |
+
"1.0.0",
|
| 1712 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 1713 |
+
)
|
| 1714 |
+
|
| 1715 |
+
# 0. Default height and width to unet
|
| 1716 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 1717 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 1718 |
+
# to deal with lora scaling and other possible forward hooks
|
| 1719 |
+
|
| 1720 |
+
# 1. Check inputs. Raise error if not correct
|
| 1721 |
+
self.check_inputs(
|
| 1722 |
+
prompt,
|
| 1723 |
+
height,
|
| 1724 |
+
width,
|
| 1725 |
+
callback_steps,
|
| 1726 |
+
negative_prompt,
|
| 1727 |
+
prompt_embeds,
|
| 1728 |
+
negative_prompt_embeds,
|
| 1729 |
+
callback_on_step_end_tensor_inputs,
|
| 1730 |
+
)
|
| 1731 |
+
|
| 1732 |
+
self._guidance_scale = guidance_scale
|
| 1733 |
+
self._guidance_rescale = guidance_rescale
|
| 1734 |
+
self._clip_skip = clip_skip
|
| 1735 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 1736 |
+
|
| 1737 |
+
# 2. Define call parameters
|
| 1738 |
+
if prompt is not None and isinstance(prompt, str):
|
| 1739 |
+
batch_size = 1
|
| 1740 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1741 |
+
batch_size = len(prompt)
|
| 1742 |
+
else:
|
| 1743 |
+
batch_size = prompt_embeds.shape[0]
|
| 1744 |
+
|
| 1745 |
+
device = self._execution_device
|
| 1746 |
+
|
| 1747 |
+
# 3. Encode input prompt
|
| 1748 |
+
lora_scale = (
|
| 1749 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 1750 |
+
)
|
| 1751 |
+
|
| 1752 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 1753 |
+
prompt,
|
| 1754 |
+
device,
|
| 1755 |
+
num_images_per_prompt,
|
| 1756 |
+
self.do_classifier_free_guidance,
|
| 1757 |
+
negative_prompt,
|
| 1758 |
+
prompt_embeds=prompt_embeds,
|
| 1759 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1760 |
+
lora_scale=lora_scale,
|
| 1761 |
+
clip_skip=self.clip_skip,
|
| 1762 |
+
)
|
| 1763 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 1764 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 1765 |
+
# to avoid doing two forward passes
|
| 1766 |
+
if self.do_classifier_free_guidance:
|
| 1767 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 1768 |
+
|
| 1769 |
+
# 4. Prepare timesteps
|
| 1770 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 1771 |
+
timesteps = self.scheduler.timesteps
|
| 1772 |
+
|
| 1773 |
+
# 5. Prepare latent variables
|
| 1774 |
+
num_channels_latents = self.unet.config.in_channels
|
| 1775 |
+
latents = self.prepare_latents(
|
| 1776 |
+
batch_size * num_images_per_prompt,
|
| 1777 |
+
num_channels_latents,
|
| 1778 |
+
height,
|
| 1779 |
+
width,
|
| 1780 |
+
prompt_embeds.dtype,
|
| 1781 |
+
device,
|
| 1782 |
+
generator,
|
| 1783 |
+
latents,
|
| 1784 |
+
)
|
| 1785 |
+
|
| 1786 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 1787 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 1788 |
+
|
| 1789 |
+
# 6.5 Optionally get Guidance Scale Embedding
|
| 1790 |
+
timestep_cond = None
|
| 1791 |
+
if self.unet.config.time_cond_proj_dim is not None:
|
| 1792 |
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
| 1793 |
+
timestep_cond = self.get_guidance_scale_embedding(
|
| 1794 |
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
| 1795 |
+
).to(device=device, dtype=latents.dtype)
|
| 1796 |
+
|
| 1797 |
+
# 7. Denoising loop
|
| 1798 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 1799 |
+
self._num_timesteps = len(timesteps)
|
| 1800 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1801 |
+
for i, t in enumerate(timesteps):
|
| 1802 |
+
# expand the latents if we are doing classifier free guidance
|
| 1803 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 1804 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 1805 |
+
|
| 1806 |
+
# predict the noise residual
|
| 1807 |
+
noise_pred = self.unet(
|
| 1808 |
+
latent_model_input,
|
| 1809 |
+
t,
|
| 1810 |
+
encoder_hidden_states=prompt_embeds,
|
| 1811 |
+
timestep_cond=timestep_cond,
|
| 1812 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
| 1813 |
+
return_dict=False,
|
| 1814 |
+
)[0]
|
| 1815 |
+
|
| 1816 |
+
# perform guidance
|
| 1817 |
+
if self.do_classifier_free_guidance:
|
| 1818 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 1819 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 1820 |
+
|
| 1821 |
+
if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
|
| 1822 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 1823 |
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
|
| 1824 |
+
|
| 1825 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 1826 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 1827 |
+
|
| 1828 |
+
if callback_on_step_end is not None:
|
| 1829 |
+
callback_kwargs = {}
|
| 1830 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 1831 |
+
callback_kwargs[k] = locals()[k]
|
| 1832 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 1833 |
+
|
| 1834 |
+
latents = callback_outputs.pop("latents", latents)
|
| 1835 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 1836 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 1837 |
+
|
| 1838 |
+
# call the callback, if provided
|
| 1839 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 1840 |
+
progress_bar.update()
|
| 1841 |
+
if callback is not None and i % callback_steps == 0:
|
| 1842 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 1843 |
+
callback(step_idx, t, latents)
|
| 1844 |
+
|
| 1845 |
+
if not output_type == "latent":
|
| 1846 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
| 1847 |
+
0
|
| 1848 |
+
]
|
| 1849 |
+
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
| 1850 |
+
else:
|
| 1851 |
+
image = latents
|
| 1852 |
+
has_nsfw_concept = None
|
| 1853 |
+
|
| 1854 |
+
if has_nsfw_concept is None:
|
| 1855 |
+
do_denormalize = [True] * image.shape[0]
|
| 1856 |
+
else:
|
| 1857 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 1858 |
+
|
| 1859 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 1860 |
+
|
| 1861 |
+
# Offload all models
|
| 1862 |
+
self.maybe_free_model_hooks()
|
| 1863 |
+
|
| 1864 |
+
if not return_dict:
|
| 1865 |
+
return (image, has_nsfw_concept)
|
| 1866 |
+
|
| 1867 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
requirements.txt
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stable-Makeup · 推理依赖 — 全量锁版本,匹配 sky24h/Stable-Makeup-unofficial
|
| 2 |
+
# pip 会降级 ModelScope 预装包到指定版本,确保全链路兼容
|
| 3 |
+
torch>=2.2.0
|
| 4 |
+
torchvision>=0.17.0
|
| 5 |
+
transformers==4.42.4
|
| 6 |
+
diffusers==0.29.2
|
| 7 |
+
accelerate==0.33.0
|
| 8 |
+
peft==0.10.0
|
| 9 |
+
Pillow>=10.0.0
|
| 10 |
+
numpy>=1.26.0
|
| 11 |
+
opencv-python-headless>=4.8.0
|
| 12 |
+
matplotlib>=3.8.0
|
| 13 |
+
safetensors>=0.3.0
|
| 14 |
+
huggingface-hub>=0.25.2
|
| 15 |
+
gdown>=5.0
|
| 16 |
+
gradio==4.44.1
|
| 17 |
+
modelscope
|
| 18 |
+
spiga==0.0.6
|
| 19 |
+
tqdm
|
| 20 |
+
batch_face==1.5.4
|
| 21 |
+
scikit-image
|
| 22 |
+
imageio==2.34.2
|
| 23 |
+
imageio-ffmpeg==0.5.1
|
| 24 |
+
PyYAML>=6.0.0
|
spiga_draw.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from spiga.inference.config import ModelConfig
|
| 4 |
+
from spiga.inference.framework import SPIGAFramework
|
| 5 |
+
from batch_face import RetinaFace
|
| 6 |
+
import cv2
|
| 7 |
+
import os
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
# 延迟初始化
|
| 11 |
+
_processor = None
|
| 12 |
+
_detector = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _get_processor():
|
| 16 |
+
global _processor
|
| 17 |
+
if _processor is None:
|
| 18 |
+
import os, glob as _glob, shutil
|
| 19 |
+
from modelscope import snapshot_download
|
| 20 |
+
|
| 21 |
+
# 从 ModelScope 下载 SPIGA 权重
|
| 22 |
+
spiga_dir = snapshot_download("aprados/spiga", cache_dir="./models/spiga")
|
| 23 |
+
candidates = _glob.glob(os.path.join(spiga_dir, "spiga_300wpublic.pt"))
|
| 24 |
+
if not candidates:
|
| 25 |
+
raise FileNotFoundError("spiga_300wpublic.pt not found in downloaded model")
|
| 26 |
+
|
| 27 |
+
cfg = ModelConfig("300wpublic", load_model_url=False)
|
| 28 |
+
cfg.model_weights_path = candidates[0]
|
| 29 |
+
_processor = SPIGAFramework(cfg)
|
| 30 |
+
return _processor
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _get_detector():
|
| 34 |
+
global _detector
|
| 35 |
+
if _detector is None:
|
| 36 |
+
gpu_id = 0 if torch.cuda.is_available() else -1
|
| 37 |
+
_detector = RetinaFace(gpu_id=gpu_id)
|
| 38 |
+
return _detector
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def center_crop(image, size):
|
| 42 |
+
width, height = image.size
|
| 43 |
+
left = (width - size) // 2
|
| 44 |
+
top = (height - size) // 2
|
| 45 |
+
right = left + size
|
| 46 |
+
bottom = top + size
|
| 47 |
+
cropped_image = image.crop((left, top, right, bottom))
|
| 48 |
+
return cropped_image
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def resize(image, size):
|
| 52 |
+
width, height = image.size
|
| 53 |
+
if width > height:
|
| 54 |
+
new_width = size
|
| 55 |
+
new_height = int(height * (size / width))
|
| 56 |
+
else:
|
| 57 |
+
new_height = size
|
| 58 |
+
new_width = int(width * (size / height))
|
| 59 |
+
resized_image = image.resize((new_width, new_height))
|
| 60 |
+
return resized_image
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def preprocess(example, name, path):
|
| 64 |
+
image = resize(example, 512)
|
| 65 |
+
cropped_image = center_crop(image, 512)
|
| 66 |
+
cropped_image.save(path + name)
|
| 67 |
+
return cropped_image
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_landmarks(image, detector=None):
|
| 71 |
+
"""image: cv2 BGR numpy array"""
|
| 72 |
+
if detector is None:
|
| 73 |
+
detector = _get_detector()
|
| 74 |
+
if isinstance(image, Image.Image):
|
| 75 |
+
image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
|
| 76 |
+
|
| 77 |
+
faces = detector(image, cv=True) # batch_face API
|
| 78 |
+
if len(faces) == 0:
|
| 79 |
+
return []
|
| 80 |
+
|
| 81 |
+
box_ls = []
|
| 82 |
+
for face in faces:
|
| 83 |
+
box, score, lmks = face
|
| 84 |
+
x, y, x1, y1 = box
|
| 85 |
+
box_ls.append((x, y, x1 - x, y1 - y))
|
| 86 |
+
|
| 87 |
+
features = _get_processor().inference(image, box_ls)
|
| 88 |
+
landmarks = np.array(features['landmarks'])
|
| 89 |
+
return landmarks
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def parse_landmarks(landmarks):
|
| 93 |
+
ldm = []
|
| 94 |
+
for landmark in landmarks:
|
| 95 |
+
ldm.append([(float(x), float(y)) for x, y in landmark])
|
| 96 |
+
return ldm
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def bbox_from_landmarks(landmarks_):
|
| 100 |
+
landmarks = parse_landmarks(landmarks_)
|
| 101 |
+
bbox = []
|
| 102 |
+
for ldm in landmarks:
|
| 103 |
+
landmarks_x, landmarks_y = zip(*ldm)
|
| 104 |
+
x_min, x_max = min(landmarks_x), max(landmarks_x)
|
| 105 |
+
y_min, y_max = min(landmarks_y), max(landmarks_y)
|
| 106 |
+
width = x_max - x_min
|
| 107 |
+
height = y_max - y_min
|
| 108 |
+
x_min -= 5
|
| 109 |
+
y_min -= 5
|
| 110 |
+
width += 10
|
| 111 |
+
height += 10
|
| 112 |
+
bbox.append((x_min, y_min, width, height))
|
| 113 |
+
return bbox
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def spiga_process(example, detector=None):
|
| 117 |
+
if detector is None:
|
| 118 |
+
detector = _get_detector()
|
| 119 |
+
ldms = get_landmarks(example, detector)
|
| 120 |
+
if len(ldms) == 0:
|
| 121 |
+
return False
|
| 122 |
+
else:
|
| 123 |
+
image = example
|
| 124 |
+
image = np.array(image)
|
| 125 |
+
# BGR → RGB for SPIGA
|
| 126 |
+
image = image[:, :, ::-1]
|
| 127 |
+
bbox = bbox_from_landmarks(ldms)
|
| 128 |
+
features = _get_processor().inference(image, [*bbox])
|
| 129 |
+
landmarks = features["landmarks"]
|
| 130 |
+
spigas = landmarks
|
| 131 |
+
return spigas
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# "Segmentation" — bezier path rendering
|
| 135 |
+
|
| 136 |
+
import matplotlib.pyplot as plt
|
| 137 |
+
import matplotlib.patches as patches
|
| 138 |
+
from matplotlib.path import Path
|
| 139 |
+
import PIL
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_patch(landmarks, color='lime', closed=False):
|
| 143 |
+
contour = landmarks
|
| 144 |
+
ops = [Path.MOVETO] + [Path.LINETO] * (len(contour) - 1)
|
| 145 |
+
facecolor = (0, 0, 0, 0)
|
| 146 |
+
if closed:
|
| 147 |
+
contour.append(contour[0])
|
| 148 |
+
ops.append(Path.CLOSEPOLY)
|
| 149 |
+
facecolor = color
|
| 150 |
+
path = Path(contour, ops)
|
| 151 |
+
return patches.PathPatch(path, facecolor=facecolor, edgecolor=color, lw=4)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def conditioning_from_landmarks(landmarks_, size=512):
|
| 155 |
+
dpi = 72
|
| 156 |
+
fig, ax = plt.subplots(1, figsize=[size / dpi, size / dpi], tight_layout={'pad': 0})
|
| 157 |
+
fig.set_dpi(dpi)
|
| 158 |
+
|
| 159 |
+
black = np.zeros((size, size, 3))
|
| 160 |
+
ax.imshow(black)
|
| 161 |
+
|
| 162 |
+
for landmarks in landmarks_:
|
| 163 |
+
face_patch = get_patch(landmarks[0:17])
|
| 164 |
+
l_eyebrow = get_patch(landmarks[17:22], color='yellow')
|
| 165 |
+
r_eyebrow = get_patch(landmarks[22:27], color='yellow')
|
| 166 |
+
nose_v = get_patch(landmarks[27:31], color='orange')
|
| 167 |
+
nose_h = get_patch(landmarks[31:36], color='orange')
|
| 168 |
+
l_eye = get_patch(landmarks[36:42], color='magenta', closed=True)
|
| 169 |
+
r_eye = get_patch(landmarks[42:48], color='magenta', closed=True)
|
| 170 |
+
outer_lips = get_patch(landmarks[48:60], color='cyan', closed=True)
|
| 171 |
+
inner_lips = get_patch(landmarks[60:68], color='blue', closed=True)
|
| 172 |
+
|
| 173 |
+
ax.add_patch(face_patch)
|
| 174 |
+
ax.add_patch(l_eyebrow)
|
| 175 |
+
ax.add_patch(r_eyebrow)
|
| 176 |
+
ax.add_patch(nose_v)
|
| 177 |
+
ax.add_patch(nose_h)
|
| 178 |
+
ax.add_patch(l_eye)
|
| 179 |
+
ax.add_patch(r_eye)
|
| 180 |
+
ax.add_patch(outer_lips)
|
| 181 |
+
ax.add_patch(inner_lips)
|
| 182 |
+
|
| 183 |
+
plt.axis('off')
|
| 184 |
+
fig.canvas.draw()
|
| 185 |
+
|
| 186 |
+
buffer, (width, height) = fig.canvas.print_to_buffer()
|
| 187 |
+
assert width == height
|
| 188 |
+
assert width == size
|
| 189 |
+
|
| 190 |
+
buffer = np.frombuffer(buffer, np.uint8).reshape((height, width, 4))
|
| 191 |
+
buffer = buffer[:, :, 0:3]
|
| 192 |
+
plt.close(fig)
|
| 193 |
+
return PIL.Image.fromarray(buffer)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def spiga_segmentation(spiga, size):
|
| 197 |
+
landmarks = spiga
|
| 198 |
+
spiga_seg = conditioning_from_landmarks(landmarks, size=size)
|
| 199 |
+
return spiga_seg
|