Shufan Li commited on
Commit ·
358eadc
0
Parent(s):
First model version
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +35 -0
- .gitignore +3 -0
- assets/demo/an antique shop.jpg +0 -0
- assets/demo/clock ticking.wav +0 -0
- ckpts/imagebind_huge.pth +1 -0
- ckpts/llm +1 -0
- ckpts/prior/model.bin +1 -0
- ckpts/sdxl +1 -0
- demo.ipynb +0 -0
- instructany2pix/__init__.py +1 -0
- instructany2pix/ddim/pnp_pipeline.py +524 -0
- instructany2pix/ddim/sdxl_pipeline.py +990 -0
- instructany2pix/diffusion/sdxl_img2img_pipeline.py +70 -0
- instructany2pix/llm/constants.py +30 -0
- instructany2pix/llm/conversation.py +381 -0
- instructany2pix/llm/mm_utils.py +107 -0
- instructany2pix/llm/model/__init__.py +1 -0
- instructany2pix/llm/model/any2pix_arch.py +299 -0
- instructany2pix/llm/model/apply_delta.py +48 -0
- instructany2pix/llm/model/builder.py +136 -0
- instructany2pix/llm/model/consolidate.py +26 -0
- instructany2pix/llm/model/language_model/__init__.py +0 -0
- instructany2pix/llm/model/language_model/any2pix_llama.py +472 -0
- instructany2pix/llm/model/language_model/mpt/adapt_tokenizer.py +41 -0
- instructany2pix/llm/model/language_model/mpt/attention.py +300 -0
- instructany2pix/llm/model/language_model/mpt/blocks.py +41 -0
- instructany2pix/llm/model/language_model/mpt/configuration_mpt.py +118 -0
- instructany2pix/llm/model/language_model/mpt/custom_embedding.py +11 -0
- instructany2pix/llm/model/language_model/mpt/flash_attn_triton.py +484 -0
- instructany2pix/llm/model/language_model/mpt/hf_prefixlm_converter.py +415 -0
- instructany2pix/llm/model/language_model/mpt/meta_init_context.py +94 -0
- instructany2pix/llm/model/language_model/mpt/modeling_mpt.py +331 -0
- instructany2pix/llm/model/language_model/mpt/norm.py +56 -0
- instructany2pix/llm/model/language_model/mpt/param_init_fns.py +181 -0
- instructany2pix/llm/model/make_delta.py +48 -0
- instructany2pix/llm/model/multimodal_encoder/builder.py +12 -0
- instructany2pix/llm/model/multimodal_encoder/clip_encoder.py +81 -0
- instructany2pix/llm/model/multimodal_encoder/image_bind_encoder.py +93 -0
- instructany2pix/llm/model/multimodal_projector/builder.py +75 -0
- instructany2pix/llm/model/utils.py +5 -0
- instructany2pix/llm/model/vae/audio_vqvae.py +394 -0
- instructany2pix/llm/model/vae/builder.py +79 -0
- instructany2pix/llm/model/vae/clip.py +52 -0
- instructany2pix/llm/model/vae/image_vqvae.py +488 -0
- instructany2pix/llm/model/vae/modules/__init__.py +0 -0
- instructany2pix/llm/model/vae/modules/attention.py +261 -0
- instructany2pix/llm/model/vae/modules/blocks.py +835 -0
- instructany2pix/llm/model/vae/modules/blocks_spec.py +999 -0
- instructany2pix/llm/model/vae/modules/discriminator_spec.py +295 -0
- instructany2pix/llm/model/vae/modules/distributions.py +92 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
**/__pycache__
|
| 2 |
+
.ipynb_checkpoints
|
| 3 |
+
# ckpts
|
assets/demo/an antique shop.jpg
ADDED
|
assets/demo/clock ticking.wav
ADDED
|
Binary file (640 kB). View file
|
|
|
ckpts/imagebind_huge.pth
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/home/jacklishufan/AudioLDM2/.checkpoints/imagebind_huge.pth
|
ckpts/llm
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/home/jacklishufan/LLaVA/outputs/llava-v1.5-7b-pretrain-any2any2align/
|
ckpts/prior/model.bin
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/home/jacklishufan/AudioLDM2/diffusion_prior_3.bin
|
ckpts/sdxl
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/localhome/data/ckpts/jacklishufan/sdxl/
|
demo.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
instructany2pix/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .pipeline import InstructAny2PixPipeline
|
instructany2pix/ddim/pnp_pipeline.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Plug&Play Feature Injection
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
from diffusers import (
|
| 7 |
+
StableDiffusionXLPipeline,
|
| 8 |
+
StableDiffusionXLImg2ImgPipeline,
|
| 9 |
+
DDIMScheduler,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
|
| 13 |
+
rescale_noise_cfg,
|
| 14 |
+
StableDiffusionXLPipelineOutput,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
import PIL
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from tqdm import tqdm
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _get_add_time_ids(
|
| 24 |
+
self,
|
| 25 |
+
original_size,
|
| 26 |
+
crops_coords_top_left,
|
| 27 |
+
target_size,
|
| 28 |
+
aesthetic_score,
|
| 29 |
+
negative_aesthetic_score,
|
| 30 |
+
negative_original_size,
|
| 31 |
+
negative_crops_coords_top_left,
|
| 32 |
+
negative_target_size,
|
| 33 |
+
dtype,
|
| 34 |
+
):
|
| 35 |
+
if self.config.requires_aesthetics_score:
|
| 36 |
+
add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
|
| 37 |
+
add_neg_time_ids = list(
|
| 38 |
+
negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
|
| 39 |
+
)
|
| 40 |
+
else:
|
| 41 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 42 |
+
add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
|
| 43 |
+
|
| 44 |
+
passed_add_embed_dim = (
|
| 45 |
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
|
| 46 |
+
)
|
| 47 |
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
| 48 |
+
|
| 49 |
+
if (
|
| 50 |
+
expected_add_embed_dim > passed_add_embed_dim
|
| 51 |
+
and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
|
| 52 |
+
):
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
|
| 55 |
+
)
|
| 56 |
+
elif (
|
| 57 |
+
expected_add_embed_dim < passed_add_embed_dim
|
| 58 |
+
and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
|
| 59 |
+
):
|
| 60 |
+
raise ValueError(
|
| 61 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
|
| 62 |
+
)
|
| 63 |
+
elif expected_add_embed_dim != passed_add_embed_dim:
|
| 64 |
+
raise ValueError(
|
| 65 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 69 |
+
add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
|
| 70 |
+
|
| 71 |
+
return add_time_ids, add_neg_time_ids
|
| 72 |
+
|
| 73 |
+
def _backward_ddim(x_tm1, alpha_t, alpha_tm1, eps_xt):
|
| 74 |
+
"""
|
| 75 |
+
let a = alpha_t, b = alpha_{t - 1}
|
| 76 |
+
We have a > b,
|
| 77 |
+
x_{t} - x_{t - 1} = sqrt(a) ((sqrt(1/b) - sqrt(1/a)) * x_{t-1} + (sqrt(1/a - 1) - sqrt(1/b - 1)) * eps_{t-1})
|
| 78 |
+
From https://arxiv.org/pdf/2105.05233.pdf, section F.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
a, b = alpha_t, alpha_tm1
|
| 82 |
+
sa = a**0.5
|
| 83 |
+
sb = b**0.5
|
| 84 |
+
|
| 85 |
+
return sa * ((1 / sb) * x_tm1 + ((1 / a - 1) ** 0.5 - (1 / b - 1) ** 0.5) * eps_xt)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SDXLDDIMPipeline(StableDiffusionXLImg2ImgPipeline):
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@torch.no_grad()
|
| 92 |
+
def inverse(
|
| 93 |
+
self,
|
| 94 |
+
prompt: Union[str, List[str]] = None,
|
| 95 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 96 |
+
image: Union[
|
| 97 |
+
torch.FloatTensor,
|
| 98 |
+
PIL.Image.Image,
|
| 99 |
+
np.ndarray,
|
| 100 |
+
List[torch.FloatTensor],
|
| 101 |
+
List[PIL.Image.Image],
|
| 102 |
+
List[np.ndarray],
|
| 103 |
+
] = None,
|
| 104 |
+
strength: float = 0.3,
|
| 105 |
+
num_inference_steps: int = 50,
|
| 106 |
+
denoising_start: Optional[float] = None,
|
| 107 |
+
denoising_end: Optional[float] = None,
|
| 108 |
+
guidance_scale: float = 5.0,
|
| 109 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 110 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 111 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 112 |
+
eta: float = 0.0,
|
| 113 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 114 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 115 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 116 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 117 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 118 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 119 |
+
output_type: Optional[str] = "pil",
|
| 120 |
+
return_dict: bool = True,
|
| 121 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 122 |
+
callback_steps: int = 1,
|
| 123 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 124 |
+
guidance_rescale: float = 0.0,
|
| 125 |
+
original_size: Tuple[int, int] = None,
|
| 126 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 127 |
+
target_size: Tuple[int, int] = None,
|
| 128 |
+
aesthetic_score: float = 6.0,
|
| 129 |
+
negative_aesthetic_score: float = 2.5,
|
| 130 |
+
#clip_skip=None,
|
| 131 |
+
):
|
| 132 |
+
self.scheduler = DDIMScheduler.from_config(self.scheduler.config)
|
| 133 |
+
|
| 134 |
+
# 1. Check inputs. Raise error if not correct
|
| 135 |
+
self.check_inputs(
|
| 136 |
+
prompt,
|
| 137 |
+
prompt_2,
|
| 138 |
+
strength,
|
| 139 |
+
num_inference_steps,
|
| 140 |
+
callback_steps,
|
| 141 |
+
negative_prompt,
|
| 142 |
+
negative_prompt_2,
|
| 143 |
+
prompt_embeds,
|
| 144 |
+
negative_prompt_embeds,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# 2. Define call parameters
|
| 148 |
+
if prompt is not None and isinstance(prompt, str):
|
| 149 |
+
batch_size = 1
|
| 150 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 151 |
+
batch_size = len(prompt)
|
| 152 |
+
else:
|
| 153 |
+
batch_size = prompt_embeds.shape[0]
|
| 154 |
+
|
| 155 |
+
device = self._execution_device
|
| 156 |
+
|
| 157 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 158 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 159 |
+
# corresponds to doing no classifier free guidance.
|
| 160 |
+
do_classifier_free_guidance = False
|
| 161 |
+
# 3. Encode input prompt
|
| 162 |
+
text_encoder_lora_scale = (
|
| 163 |
+
cross_attention_kwargs.get("scale", None)
|
| 164 |
+
if cross_attention_kwargs is not None
|
| 165 |
+
else None
|
| 166 |
+
)
|
| 167 |
+
(
|
| 168 |
+
prompt_embeds,
|
| 169 |
+
negative_prompt_embeds,
|
| 170 |
+
pooled_prompt_embeds,
|
| 171 |
+
negative_pooled_prompt_embeds,
|
| 172 |
+
) = self.encode_prompt(
|
| 173 |
+
prompt=prompt,
|
| 174 |
+
prompt_2=prompt_2,
|
| 175 |
+
device=device,
|
| 176 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 177 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 178 |
+
negative_prompt=negative_prompt,
|
| 179 |
+
negative_prompt_2=negative_prompt_2,
|
| 180 |
+
prompt_embeds=prompt_embeds,
|
| 181 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 182 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 183 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 184 |
+
lora_scale=text_encoder_lora_scale,
|
| 185 |
+
#clip_skip=clip_skip,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# 4. Preprocess image
|
| 189 |
+
image = self.image_processor.preprocess(image)
|
| 190 |
+
|
| 191 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 192 |
+
|
| 193 |
+
# 6. Prepare latent variables
|
| 194 |
+
latents = self.prepare_latents(
|
| 195 |
+
image,
|
| 196 |
+
None,
|
| 197 |
+
batch_size,
|
| 198 |
+
num_images_per_prompt,
|
| 199 |
+
prompt_embeds.dtype,
|
| 200 |
+
device,
|
| 201 |
+
generator,
|
| 202 |
+
False,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
height, width = latents.shape[-2:]
|
| 206 |
+
height = height * self.vae_scale_factor
|
| 207 |
+
width = width * self.vae_scale_factor
|
| 208 |
+
|
| 209 |
+
original_size = original_size or (height, width)
|
| 210 |
+
target_size = target_size or (height, width)
|
| 211 |
+
|
| 212 |
+
# 8. Prepare added time ids & embeddings
|
| 213 |
+
add_text_embeds = pooled_prompt_embeds
|
| 214 |
+
negative_original_size = None
|
| 215 |
+
negative_crops_coords_top_left = None
|
| 216 |
+
negative_target_size = None
|
| 217 |
+
if negative_original_size is None:
|
| 218 |
+
negative_original_size = original_size
|
| 219 |
+
if negative_target_size is None:
|
| 220 |
+
negative_target_size = target_size
|
| 221 |
+
negative_crops_coords_top_left = (0,0)
|
| 222 |
+
if self.text_encoder_2 is None:
|
| 223 |
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
| 224 |
+
else:
|
| 225 |
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
| 226 |
+
|
| 227 |
+
add_time_ids, add_neg_time_ids = _get_add_time_ids(self,
|
| 228 |
+
original_size,
|
| 229 |
+
crops_coords_top_left,
|
| 230 |
+
target_size,
|
| 231 |
+
aesthetic_score,
|
| 232 |
+
negative_aesthetic_score,
|
| 233 |
+
negative_original_size,
|
| 234 |
+
negative_crops_coords_top_left,
|
| 235 |
+
negative_target_size,
|
| 236 |
+
dtype=prompt_embeds.dtype,
|
| 237 |
+
#text_encoder_projection_dim=text_encoder_projection_dim,
|
| 238 |
+
)
|
| 239 |
+
add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
|
| 240 |
+
|
| 241 |
+
prompt_embeds = prompt_embeds.to(device)
|
| 242 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 243 |
+
add_time_ids = add_time_ids.to(device)
|
| 244 |
+
|
| 245 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 246 |
+
prev_timestep = None
|
| 247 |
+
|
| 248 |
+
for t in tqdm(reversed(self.scheduler.timesteps)):
|
| 249 |
+
latent_model_input = latents
|
| 250 |
+
noise_pred = self.unet(
|
| 251 |
+
latent_model_input,
|
| 252 |
+
t,
|
| 253 |
+
encoder_hidden_states=prompt_embeds,
|
| 254 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 255 |
+
added_cond_kwargs={k:v for k,v in added_cond_kwargs.items()},
|
| 256 |
+
return_dict=False,
|
| 257 |
+
)[0]
|
| 258 |
+
|
| 259 |
+
alpha_prod_t = self.scheduler.alphas_cumprod[t]
|
| 260 |
+
alpha_prod_t_prev = (
|
| 261 |
+
self.scheduler.alphas_cumprod[prev_timestep]
|
| 262 |
+
if prev_timestep is not None
|
| 263 |
+
else self.scheduler.final_alpha_cumprod
|
| 264 |
+
)
|
| 265 |
+
prev_timestep = t
|
| 266 |
+
|
| 267 |
+
latents = _backward_ddim(
|
| 268 |
+
x_tm1=latents,
|
| 269 |
+
alpha_t=alpha_prod_t,
|
| 270 |
+
alpha_tm1=alpha_prod_t_prev,
|
| 271 |
+
eps_xt=noise_pred,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
image = latents
|
| 275 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class SDXLPNPPipeline(StableDiffusionXLPipeline):
|
| 279 |
+
def __init__(
|
| 280 |
+
self,
|
| 281 |
+
*args,
|
| 282 |
+
**kwargs,
|
| 283 |
+
):
|
| 284 |
+
super().__init__(*args, **kwargs)
|
| 285 |
+
self.feature_bags = {}
|
| 286 |
+
|
| 287 |
+
def __call__(
|
| 288 |
+
self,
|
| 289 |
+
prompt: Union[str, List[str]] = None,
|
| 290 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 291 |
+
height: Optional[int] = None,
|
| 292 |
+
width: Optional[int] = None,
|
| 293 |
+
num_inference_steps: int = 50,
|
| 294 |
+
denoising_end: Optional[float] = None,
|
| 295 |
+
guidance_scale: float = 5.0,
|
| 296 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 297 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 298 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 299 |
+
eta: float = 0.0,
|
| 300 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 301 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 302 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 303 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 304 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 305 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 306 |
+
output_type: Optional[str] = "pil",
|
| 307 |
+
return_dict: bool = True,
|
| 308 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 309 |
+
callback_steps: int = 1,
|
| 310 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 311 |
+
guidance_rescale: float = 0.0,
|
| 312 |
+
original_size: Optional[Tuple[int, int]] = None,
|
| 313 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 314 |
+
target_size: Optional[Tuple[int, int]] = None,
|
| 315 |
+
):
|
| 316 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
| 317 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
| 318 |
+
|
| 319 |
+
original_size = original_size or (height, width)
|
| 320 |
+
target_size = target_size or (height, width)
|
| 321 |
+
|
| 322 |
+
# 1. Check inputs. Raise error if not correct
|
| 323 |
+
self.check_inputs(
|
| 324 |
+
prompt,
|
| 325 |
+
prompt_2,
|
| 326 |
+
height,
|
| 327 |
+
width,
|
| 328 |
+
callback_steps,
|
| 329 |
+
negative_prompt,
|
| 330 |
+
negative_prompt_2,
|
| 331 |
+
prompt_embeds,
|
| 332 |
+
negative_prompt_embeds,
|
| 333 |
+
pooled_prompt_embeds,
|
| 334 |
+
negative_pooled_prompt_embeds,
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
# 2. Define call parameters
|
| 338 |
+
if prompt is not None and isinstance(prompt, str):
|
| 339 |
+
batch_size = 1
|
| 340 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 341 |
+
batch_size = len(prompt)
|
| 342 |
+
else:
|
| 343 |
+
batch_size = prompt_embeds.shape[0]
|
| 344 |
+
|
| 345 |
+
device = self._execution_device
|
| 346 |
+
|
| 347 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 348 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 349 |
+
# corresponds to doing no classifier free guidance.
|
| 350 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 351 |
+
|
| 352 |
+
# 3. Encode input prompt
|
| 353 |
+
text_encoder_lora_scale = (
|
| 354 |
+
cross_attention_kwargs.get("scale", None)
|
| 355 |
+
if cross_attention_kwargs is not None
|
| 356 |
+
else None
|
| 357 |
+
)
|
| 358 |
+
(
|
| 359 |
+
prompt_embeds,
|
| 360 |
+
negative_prompt_embeds,
|
| 361 |
+
pooled_prompt_embeds,
|
| 362 |
+
negative_pooled_prompt_embeds,
|
| 363 |
+
) = self.encode_prompt(
|
| 364 |
+
prompt=prompt,
|
| 365 |
+
prompt_2=prompt_2,
|
| 366 |
+
device=device,
|
| 367 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 368 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 369 |
+
negative_prompt=negative_prompt,
|
| 370 |
+
negative_prompt_2=negative_prompt_2,
|
| 371 |
+
prompt_embeds=prompt_embeds,
|
| 372 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 373 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 374 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 375 |
+
lora_scale=text_encoder_lora_scale,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
# 4. Prepare timesteps
|
| 379 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 380 |
+
|
| 381 |
+
timesteps = self.scheduler.timesteps
|
| 382 |
+
|
| 383 |
+
# 5. Prepare latent variables
|
| 384 |
+
num_channels_latents = self.unet.config.in_channels
|
| 385 |
+
latents = self.prepare_latents(
|
| 386 |
+
batch_size * num_images_per_prompt,
|
| 387 |
+
num_channels_latents,
|
| 388 |
+
height,
|
| 389 |
+
width,
|
| 390 |
+
prompt_embeds.dtype,
|
| 391 |
+
device,
|
| 392 |
+
generator,
|
| 393 |
+
latents,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 397 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 398 |
+
|
| 399 |
+
# 7. Prepare added time ids & embeddings
|
| 400 |
+
add_text_embeds = pooled_prompt_embeds
|
| 401 |
+
add_time_ids = self._get_add_time_ids(
|
| 402 |
+
original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
if do_classifier_free_guidance:
|
| 406 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
| 407 |
+
add_text_embeds = torch.cat(
|
| 408 |
+
[negative_pooled_prompt_embeds, add_text_embeds], dim=0
|
| 409 |
+
)
|
| 410 |
+
add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
|
| 411 |
+
|
| 412 |
+
prompt_embeds = prompt_embeds.to(device)
|
| 413 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 414 |
+
add_time_ids = add_time_ids.to(device).repeat(
|
| 415 |
+
batch_size * num_images_per_prompt, 1
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# 8. Denoising loop
|
| 419 |
+
num_warmup_steps = max(
|
| 420 |
+
len(timesteps) - num_inference_steps * self.scheduler.order, 0
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
# 7.1 Apply denoising_end
|
| 424 |
+
if (
|
| 425 |
+
denoising_end is not None
|
| 426 |
+
and type(denoising_end) == float
|
| 427 |
+
and denoising_end > 0
|
| 428 |
+
and denoising_end < 1
|
| 429 |
+
):
|
| 430 |
+
discrete_timestep_cutoff = int(
|
| 431 |
+
round(
|
| 432 |
+
self.scheduler.config.num_train_timesteps
|
| 433 |
+
- (denoising_end * self.scheduler.config.num_train_timesteps)
|
| 434 |
+
)
|
| 435 |
+
)
|
| 436 |
+
num_inference_steps = len(
|
| 437 |
+
list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps))
|
| 438 |
+
)
|
| 439 |
+
timesteps = timesteps[:num_inference_steps]
|
| 440 |
+
|
| 441 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 442 |
+
for i, t in enumerate(timesteps):
|
| 443 |
+
# expand the latents if we are doing classifier free guidance
|
| 444 |
+
# print(t)
|
| 445 |
+
latent_model_input = (
|
| 446 |
+
torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
latent_model_input = self.scheduler.scale_model_input(
|
| 450 |
+
latent_model_input, t
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# predict the noise residual
|
| 454 |
+
|
| 455 |
+
added_cond_kwargs = {
|
| 456 |
+
"text_embeds": add_text_embeds[:1, ...],
|
| 457 |
+
"time_ids": add_time_ids[:1, ...],
|
| 458 |
+
}
|
| 459 |
+
noise_pred_text, feats = self.unet(
|
| 460 |
+
latent_model_input[:1, ...],
|
| 461 |
+
t,
|
| 462 |
+
encoder_hidden_states=prompt_embeds[:1, ...],
|
| 463 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 464 |
+
return_dict=False,
|
| 465 |
+
)[0]
|
| 466 |
+
|
| 467 |
+
added_cond_kwargs = {
|
| 468 |
+
"text_embeds": add_text_embeds[1:2, ...],
|
| 469 |
+
"time_ids": add_time_ids[1:2, ...],
|
| 470 |
+
}
|
| 471 |
+
noise_pred_uncond, feats = self.unet(
|
| 472 |
+
latent_model_input[1:2, ...],
|
| 473 |
+
t,
|
| 474 |
+
encoder_hidden_states=prompt_embeds[1:2, ...],
|
| 475 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 476 |
+
return_dict=False,
|
| 477 |
+
)[0]
|
| 478 |
+
|
| 479 |
+
noise_pred = noise_pred_uncond + guidance_scale * (
|
| 480 |
+
noise_pred_text - noise_pred_uncond
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 484 |
+
latents = self.scheduler.step(
|
| 485 |
+
noise_pred, t, latents, **extra_step_kwargs, return_dict=False
|
| 486 |
+
)[0]
|
| 487 |
+
|
| 488 |
+
# call the callback, if provided
|
| 489 |
+
if i == len(timesteps) - 1 or (
|
| 490 |
+
(i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
|
| 491 |
+
):
|
| 492 |
+
progress_bar.update()
|
| 493 |
+
if callback is not None and i % callback_steps == 0:
|
| 494 |
+
callback(i, t, latents)
|
| 495 |
+
|
| 496 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 497 |
+
if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
|
| 498 |
+
self.upcast_vae()
|
| 499 |
+
latents = latents.to(
|
| 500 |
+
next(iter(self.vae.post_quant_conv.parameters())).dtype
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
if not output_type == "latent":
|
| 504 |
+
image = self.vae.decode(
|
| 505 |
+
latents / self.vae.config.scaling_factor, return_dict=False
|
| 506 |
+
)[0]
|
| 507 |
+
else:
|
| 508 |
+
image = latents
|
| 509 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
| 510 |
+
|
| 511 |
+
# apply watermark if available
|
| 512 |
+
if self.watermark is not None:
|
| 513 |
+
image = self.watermark.apply_watermark(image)
|
| 514 |
+
|
| 515 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 516 |
+
|
| 517 |
+
# Offload last model to CPU
|
| 518 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 519 |
+
self.final_offload_hook.offload()
|
| 520 |
+
|
| 521 |
+
if not return_dict:
|
| 522 |
+
return (image,)
|
| 523 |
+
|
| 524 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
instructany2pix/ddim/sdxl_pipeline.py
ADDED
|
@@ -0,0 +1,990 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import os
|
| 17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
|
| 21 |
+
|
| 22 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 23 |
+
from diffusers.loaders import (
|
| 24 |
+
FromSingleFileMixin,
|
| 25 |
+
LoraLoaderMixin,
|
| 26 |
+
TextualInversionLoaderMixin,
|
| 27 |
+
)
|
| 28 |
+
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
| 29 |
+
from diffusers.models.attention_processor import (
|
| 30 |
+
AttnProcessor2_0,
|
| 31 |
+
LoRAAttnProcessor2_0,
|
| 32 |
+
LoRAXFormersAttnProcessor,
|
| 33 |
+
XFormersAttnProcessor,
|
| 34 |
+
)
|
| 35 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
| 36 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
| 37 |
+
from diffusers.utils import (
|
| 38 |
+
is_accelerate_available,
|
| 39 |
+
is_accelerate_version,
|
| 40 |
+
is_invisible_watermark_available,
|
| 41 |
+
logging,
|
| 42 |
+
replace_example_docstring,
|
| 43 |
+
)
|
| 44 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 45 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 46 |
+
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if is_invisible_watermark_available():
|
| 50 |
+
from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 54 |
+
|
| 55 |
+
EXAMPLE_DOC_STRING = """
|
| 56 |
+
Examples:
|
| 57 |
+
```py
|
| 58 |
+
>>> import torch
|
| 59 |
+
>>> from diffusers import StableDiffusionXLPipeline
|
| 60 |
+
|
| 61 |
+
>>> pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 62 |
+
... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 63 |
+
... )
|
| 64 |
+
>>> pipe = pipe.to("cuda")
|
| 65 |
+
|
| 66 |
+
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
| 67 |
+
>>> image = pipe(prompt).images[0]
|
| 68 |
+
```
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
| 73 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
| 74 |
+
"""
|
| 75 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
| 76 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
| 77 |
+
"""
|
| 78 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
| 79 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
| 80 |
+
# rescale the results from guidance (fixes overexposure)
|
| 81 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
| 82 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
| 83 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
| 84 |
+
return noise_cfg
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class StableDiffusionXLPipeline(DiffusionPipeline, FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin):
|
| 88 |
+
r"""
|
| 89 |
+
Pipeline for text-to-image generation using Stable Diffusion XL.
|
| 90 |
+
|
| 91 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
| 92 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
| 93 |
+
|
| 94 |
+
In addition the pipeline inherits the following loading methods:
|
| 95 |
+
- *LoRA*: [`StableDiffusionXLPipeline.load_lora_weights`]
|
| 96 |
+
- *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
|
| 97 |
+
|
| 98 |
+
as well as the following saving methods:
|
| 99 |
+
- *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
vae ([`AutoencoderKL`]):
|
| 103 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 104 |
+
text_encoder ([`CLIPTextModel`]):
|
| 105 |
+
Frozen text-encoder. Stable Diffusion XL uses the text portion of
|
| 106 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
| 107 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 108 |
+
text_encoder_2 ([` CLIPTextModelWithProjection`]):
|
| 109 |
+
Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
|
| 110 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
| 111 |
+
specifically the
|
| 112 |
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
| 113 |
+
variant.
|
| 114 |
+
tokenizer (`CLIPTokenizer`):
|
| 115 |
+
Tokenizer of class
|
| 116 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 117 |
+
tokenizer_2 (`CLIPTokenizer`):
|
| 118 |
+
Second Tokenizer of class
|
| 119 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 120 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
| 121 |
+
scheduler ([`SchedulerMixin`]):
|
| 122 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 123 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 124 |
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
| 125 |
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
| 126 |
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
| 127 |
+
add_watermarker (`bool`, *optional*):
|
| 128 |
+
Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
|
| 129 |
+
watermark output images. If not defined, it will default to True if the package is installed, otherwise no
|
| 130 |
+
watermarker will be used.
|
| 131 |
+
"""
|
| 132 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
|
| 133 |
+
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
vae: AutoencoderKL,
|
| 137 |
+
text_encoder: CLIPTextModel,
|
| 138 |
+
text_encoder_2: CLIPTextModelWithProjection,
|
| 139 |
+
tokenizer: CLIPTokenizer,
|
| 140 |
+
tokenizer_2: CLIPTokenizer,
|
| 141 |
+
unet: UNet2DConditionModel,
|
| 142 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 143 |
+
force_zeros_for_empty_prompt: bool = True,
|
| 144 |
+
add_watermarker: Optional[bool] = False,
|
| 145 |
+
):
|
| 146 |
+
super().__init__()
|
| 147 |
+
|
| 148 |
+
self.register_modules(
|
| 149 |
+
vae=vae,
|
| 150 |
+
text_encoder=text_encoder,
|
| 151 |
+
text_encoder_2=text_encoder_2,
|
| 152 |
+
tokenizer=tokenizer,
|
| 153 |
+
tokenizer_2=tokenizer_2,
|
| 154 |
+
unet=unet,
|
| 155 |
+
scheduler=scheduler,
|
| 156 |
+
)
|
| 157 |
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
| 158 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 159 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 160 |
+
self.default_sample_size = self.unet.config.sample_size
|
| 161 |
+
|
| 162 |
+
add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
|
| 163 |
+
|
| 164 |
+
if add_watermarker:
|
| 165 |
+
self.watermark = StableDiffusionXLWatermarker()
|
| 166 |
+
else:
|
| 167 |
+
self.watermark = None
|
| 168 |
+
|
| 169 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
|
| 170 |
+
def enable_vae_slicing(self):
|
| 171 |
+
r"""
|
| 172 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
| 173 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
| 174 |
+
"""
|
| 175 |
+
self.vae.enable_slicing()
|
| 176 |
+
|
| 177 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
|
| 178 |
+
def disable_vae_slicing(self):
|
| 179 |
+
r"""
|
| 180 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
| 181 |
+
computing decoding in one step.
|
| 182 |
+
"""
|
| 183 |
+
self.vae.disable_slicing()
|
| 184 |
+
|
| 185 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
|
| 186 |
+
def enable_vae_tiling(self):
|
| 187 |
+
r"""
|
| 188 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
| 189 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
| 190 |
+
processing larger images.
|
| 191 |
+
"""
|
| 192 |
+
self.vae.enable_tiling()
|
| 193 |
+
|
| 194 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
|
| 195 |
+
def disable_vae_tiling(self):
|
| 196 |
+
r"""
|
| 197 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
| 198 |
+
computing decoding in one step.
|
| 199 |
+
"""
|
| 200 |
+
self.vae.disable_tiling()
|
| 201 |
+
|
| 202 |
+
def encode_prompt(
|
| 203 |
+
self,
|
| 204 |
+
prompt: str,
|
| 205 |
+
prompt_2: Optional[str] = None,
|
| 206 |
+
device: Optional[torch.device] = None,
|
| 207 |
+
num_images_per_prompt: int = 1,
|
| 208 |
+
do_classifier_free_guidance: bool = True,
|
| 209 |
+
negative_prompt: Optional[str] = None,
|
| 210 |
+
negative_prompt_2: Optional[str] = None,
|
| 211 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 212 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 213 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 214 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 215 |
+
lora_scale: Optional[float] = None,
|
| 216 |
+
):
|
| 217 |
+
r"""
|
| 218 |
+
Encodes the prompt into text encoder hidden states.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 222 |
+
prompt to be encoded
|
| 223 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 224 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 225 |
+
used in both text-encoders
|
| 226 |
+
device: (`torch.device`):
|
| 227 |
+
torch device
|
| 228 |
+
num_images_per_prompt (`int`):
|
| 229 |
+
number of images that should be generated per prompt
|
| 230 |
+
do_classifier_free_guidance (`bool`):
|
| 231 |
+
whether to use classifier free guidance or not
|
| 232 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 233 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 234 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 235 |
+
less than `1`).
|
| 236 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 237 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 238 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
| 239 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 240 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 241 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 242 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 243 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 244 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 245 |
+
argument.
|
| 246 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 247 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 248 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 249 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 250 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 251 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 252 |
+
input argument.
|
| 253 |
+
lora_scale (`float`, *optional*):
|
| 254 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 255 |
+
"""
|
| 256 |
+
device = device or self._execution_device
|
| 257 |
+
|
| 258 |
+
# set lora scale so that monkey patched LoRA
|
| 259 |
+
# function of text encoder can correctly access it
|
| 260 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 261 |
+
self._lora_scale = lora_scale
|
| 262 |
+
|
| 263 |
+
# dynamically adjust the LoRA scale
|
| 264 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 265 |
+
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
| 266 |
+
|
| 267 |
+
if prompt is not None and isinstance(prompt, str):
|
| 268 |
+
batch_size = 1
|
| 269 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 270 |
+
batch_size = len(prompt)
|
| 271 |
+
else:
|
| 272 |
+
batch_size = prompt_embeds.shape[0]
|
| 273 |
+
|
| 274 |
+
# Define tokenizers and text encoders
|
| 275 |
+
tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
|
| 276 |
+
text_encoders = (
|
| 277 |
+
[self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if prompt_embeds is None:
|
| 281 |
+
prompt_2 = prompt_2 or prompt
|
| 282 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 283 |
+
prompt_embeds_list = []
|
| 284 |
+
prompts = [prompt, prompt_2]
|
| 285 |
+
for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
|
| 286 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 287 |
+
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
| 288 |
+
|
| 289 |
+
text_inputs = tokenizer(
|
| 290 |
+
prompt,
|
| 291 |
+
padding="max_length",
|
| 292 |
+
max_length=tokenizer.model_max_length,
|
| 293 |
+
truncation=True,
|
| 294 |
+
return_tensors="pt",
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
text_input_ids = text_inputs.input_ids
|
| 298 |
+
untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 299 |
+
|
| 300 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 301 |
+
text_input_ids, untruncated_ids
|
| 302 |
+
):
|
| 303 |
+
removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
|
| 304 |
+
logger.warning(
|
| 305 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 306 |
+
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
prompt_embeds = text_encoder(
|
| 310 |
+
text_input_ids.to(device),
|
| 311 |
+
output_hidden_states=True,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 315 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
| 316 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
| 317 |
+
|
| 318 |
+
prompt_embeds_list.append(prompt_embeds)
|
| 319 |
+
|
| 320 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
| 321 |
+
|
| 322 |
+
# get unconditional embeddings for classifier free guidance
|
| 323 |
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
| 324 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
| 325 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
| 326 |
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
| 327 |
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 328 |
+
negative_prompt = negative_prompt or ""
|
| 329 |
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
| 330 |
+
|
| 331 |
+
uncond_tokens: List[str]
|
| 332 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 333 |
+
raise TypeError(
|
| 334 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 335 |
+
f" {type(prompt)}."
|
| 336 |
+
)
|
| 337 |
+
elif isinstance(negative_prompt, str):
|
| 338 |
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
| 339 |
+
elif batch_size != len(negative_prompt):
|
| 340 |
+
raise ValueError(
|
| 341 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 342 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 343 |
+
" the batch size of `prompt`."
|
| 344 |
+
)
|
| 345 |
+
else:
|
| 346 |
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
| 347 |
+
|
| 348 |
+
negative_prompt_embeds_list = []
|
| 349 |
+
for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
|
| 350 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 351 |
+
negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
|
| 352 |
+
|
| 353 |
+
max_length = prompt_embeds.shape[1]
|
| 354 |
+
uncond_input = tokenizer(
|
| 355 |
+
negative_prompt,
|
| 356 |
+
padding="max_length",
|
| 357 |
+
max_length=max_length,
|
| 358 |
+
truncation=True,
|
| 359 |
+
return_tensors="pt",
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
negative_prompt_embeds = text_encoder(
|
| 363 |
+
uncond_input.input_ids.to(device),
|
| 364 |
+
output_hidden_states=True,
|
| 365 |
+
)
|
| 366 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 367 |
+
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
| 368 |
+
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
| 369 |
+
|
| 370 |
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
| 371 |
+
|
| 372 |
+
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
| 373 |
+
|
| 374 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
| 375 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 376 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 377 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 378 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 379 |
+
|
| 380 |
+
if do_classifier_free_guidance:
|
| 381 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 382 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 383 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
| 384 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 385 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 386 |
+
|
| 387 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 388 |
+
bs_embed * num_images_per_prompt, -1
|
| 389 |
+
)
|
| 390 |
+
if do_classifier_free_guidance:
|
| 391 |
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 392 |
+
bs_embed * num_images_per_prompt, -1
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
| 396 |
+
|
| 397 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 398 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 399 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 400 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 401 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 402 |
+
# and should be between [0, 1]
|
| 403 |
+
|
| 404 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 405 |
+
extra_step_kwargs = {}
|
| 406 |
+
if accepts_eta:
|
| 407 |
+
extra_step_kwargs["eta"] = eta
|
| 408 |
+
|
| 409 |
+
# check if the scheduler accepts generator
|
| 410 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 411 |
+
if accepts_generator:
|
| 412 |
+
extra_step_kwargs["generator"] = generator
|
| 413 |
+
return extra_step_kwargs
|
| 414 |
+
|
| 415 |
+
def check_inputs(
|
| 416 |
+
self,
|
| 417 |
+
prompt,
|
| 418 |
+
prompt_2,
|
| 419 |
+
height,
|
| 420 |
+
width,
|
| 421 |
+
callback_steps,
|
| 422 |
+
negative_prompt=None,
|
| 423 |
+
negative_prompt_2=None,
|
| 424 |
+
prompt_embeds=None,
|
| 425 |
+
negative_prompt_embeds=None,
|
| 426 |
+
pooled_prompt_embeds=None,
|
| 427 |
+
negative_pooled_prompt_embeds=None,
|
| 428 |
+
):
|
| 429 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 430 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 431 |
+
|
| 432 |
+
if (callback_steps is None) or (
|
| 433 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
| 434 |
+
):
|
| 435 |
+
raise ValueError(
|
| 436 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 437 |
+
f" {type(callback_steps)}."
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
if prompt is not None and prompt_embeds is not None:
|
| 441 |
+
raise ValueError(
|
| 442 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 443 |
+
" only forward one of the two."
|
| 444 |
+
)
|
| 445 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
| 446 |
+
raise ValueError(
|
| 447 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 448 |
+
" only forward one of the two."
|
| 449 |
+
)
|
| 450 |
+
elif prompt is None and prompt_embeds is None:
|
| 451 |
+
raise ValueError(
|
| 452 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 453 |
+
)
|
| 454 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 455 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 456 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
| 457 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
| 458 |
+
|
| 459 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 460 |
+
raise ValueError(
|
| 461 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 462 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 463 |
+
)
|
| 464 |
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
| 465 |
+
raise ValueError(
|
| 466 |
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
| 467 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 471 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 472 |
+
raise ValueError(
|
| 473 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 474 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 475 |
+
f" {negative_prompt_embeds.shape}."
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
| 479 |
+
raise ValueError(
|
| 480 |
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
| 484 |
+
raise ValueError(
|
| 485 |
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 489 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 490 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 491 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 492 |
+
raise ValueError(
|
| 493 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 494 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
if latents is None:
|
| 498 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 499 |
+
else:
|
| 500 |
+
latents = latents.to(device)
|
| 501 |
+
|
| 502 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 503 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 504 |
+
return latents
|
| 505 |
+
|
| 506 |
+
def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
|
| 507 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 508 |
+
|
| 509 |
+
passed_add_embed_dim = (
|
| 510 |
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
|
| 511 |
+
)
|
| 512 |
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
| 513 |
+
|
| 514 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
| 515 |
+
raise ValueError(
|
| 516 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 520 |
+
return add_time_ids
|
| 521 |
+
|
| 522 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
| 523 |
+
def upcast_vae(self):
|
| 524 |
+
dtype = self.vae.dtype
|
| 525 |
+
self.vae.to(dtype=torch.float32)
|
| 526 |
+
use_torch_2_0_or_xformers = isinstance(
|
| 527 |
+
self.vae.decoder.mid_block.attentions[0].processor,
|
| 528 |
+
(
|
| 529 |
+
AttnProcessor2_0,
|
| 530 |
+
XFormersAttnProcessor,
|
| 531 |
+
LoRAXFormersAttnProcessor,
|
| 532 |
+
LoRAAttnProcessor2_0,
|
| 533 |
+
),
|
| 534 |
+
)
|
| 535 |
+
# if xformers or torch_2_0 is used attention block does not need
|
| 536 |
+
# to be in float32 which can save lots of memory
|
| 537 |
+
if use_torch_2_0_or_xformers:
|
| 538 |
+
self.vae.post_quant_conv.to(dtype)
|
| 539 |
+
self.vae.decoder.conv_in.to(dtype)
|
| 540 |
+
self.vae.decoder.mid_block.to(dtype)
|
| 541 |
+
|
| 542 |
+
@torch.no_grad()
|
| 543 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 544 |
+
def __call__(
|
| 545 |
+
self,
|
| 546 |
+
prompt: Union[str, List[str]] = None,
|
| 547 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 548 |
+
height: Optional[int] = None,
|
| 549 |
+
width: Optional[int] = None,
|
| 550 |
+
num_inference_steps: int = 50,
|
| 551 |
+
denoising_end: Optional[float] = None,
|
| 552 |
+
guidance_scale: float = 5.0,
|
| 553 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 554 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 555 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 556 |
+
eta: float = 0.0,
|
| 557 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 558 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 559 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 560 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 561 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 562 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 563 |
+
output_type: Optional[str] = "pil",
|
| 564 |
+
return_dict: bool = True,
|
| 565 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
| 566 |
+
callback_steps: int = 1,
|
| 567 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 568 |
+
guidance_rescale: float = 0.0,
|
| 569 |
+
original_size: Optional[Tuple[int, int]] = None,
|
| 570 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 571 |
+
target_size: Optional[Tuple[int, int]] = None,
|
| 572 |
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
| 573 |
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 574 |
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
| 575 |
+
):
|
| 576 |
+
r"""
|
| 577 |
+
Function invoked when calling the pipeline for generation.
|
| 578 |
+
|
| 579 |
+
Args:
|
| 580 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 581 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 582 |
+
instead.
|
| 583 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 584 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 585 |
+
used in both text-encoders
|
| 586 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 587 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 588 |
+
Anything below 512 pixels won't work well for
|
| 589 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 590 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 591 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
| 592 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
| 593 |
+
Anything below 512 pixels won't work well for
|
| 594 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 595 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 596 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 597 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 598 |
+
expense of slower inference.
|
| 599 |
+
denoising_end (`float`, *optional*):
|
| 600 |
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
| 601 |
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
| 602 |
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
| 603 |
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
| 604 |
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
| 605 |
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
| 606 |
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
| 607 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 608 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 609 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 610 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 611 |
+
usually at the expense of lower image quality.
|
| 612 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 613 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 614 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 615 |
+
less than `1`).
|
| 616 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 617 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 618 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
| 619 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 620 |
+
The number of images to generate per prompt.
|
| 621 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 622 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 623 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 624 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 625 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 626 |
+
to make generation deterministic.
|
| 627 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 628 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 629 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 630 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 631 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 632 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 633 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 634 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 635 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 636 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 637 |
+
argument.
|
| 638 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 639 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 640 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 641 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 642 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 643 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 644 |
+
input argument.
|
| 645 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 646 |
+
The output format of the generate image. Choose between
|
| 647 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 648 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 649 |
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
| 650 |
+
of a plain tuple.
|
| 651 |
+
callback (`Callable`, *optional*):
|
| 652 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
| 653 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 654 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 655 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
| 656 |
+
called at every step.
|
| 657 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 658 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 659 |
+
`self.processor` in
|
| 660 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 661 |
+
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
| 662 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
| 663 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
| 664 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
| 665 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
| 666 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 667 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
| 668 |
+
`original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
|
| 669 |
+
explained in section 2.2 of
|
| 670 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 671 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 672 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
| 673 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
| 674 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 675 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 676 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 677 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
| 678 |
+
not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
|
| 679 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 680 |
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 681 |
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
| 682 |
+
micro-conditioning as explained in section 2.2 of
|
| 683 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 684 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 685 |
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 686 |
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
| 687 |
+
micro-conditioning as explained in section 2.2 of
|
| 688 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 689 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 690 |
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 691 |
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
| 692 |
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 693 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 694 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 695 |
+
|
| 696 |
+
Examples:
|
| 697 |
+
|
| 698 |
+
Returns:
|
| 699 |
+
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
|
| 700 |
+
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
|
| 701 |
+
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
| 702 |
+
"""
|
| 703 |
+
# 0. Default height and width to unet
|
| 704 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
| 705 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
| 706 |
+
|
| 707 |
+
original_size = original_size or (height, width)
|
| 708 |
+
target_size = target_size or (height, width)
|
| 709 |
+
|
| 710 |
+
# 1. Check inputs. Raise error if not correct
|
| 711 |
+
self.check_inputs(
|
| 712 |
+
prompt,
|
| 713 |
+
prompt_2,
|
| 714 |
+
height,
|
| 715 |
+
width,
|
| 716 |
+
callback_steps,
|
| 717 |
+
negative_prompt,
|
| 718 |
+
negative_prompt_2,
|
| 719 |
+
prompt_embeds,
|
| 720 |
+
negative_prompt_embeds,
|
| 721 |
+
pooled_prompt_embeds,
|
| 722 |
+
negative_pooled_prompt_embeds,
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
# 2. Define call parameters
|
| 726 |
+
if prompt is not None and isinstance(prompt, str):
|
| 727 |
+
batch_size = 1
|
| 728 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 729 |
+
batch_size = len(prompt)
|
| 730 |
+
else:
|
| 731 |
+
batch_size = prompt_embeds.shape[0]
|
| 732 |
+
|
| 733 |
+
device = self._execution_device
|
| 734 |
+
|
| 735 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 736 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 737 |
+
# corresponds to doing no classifier free guidance.
|
| 738 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
| 739 |
+
|
| 740 |
+
# 3. Encode input prompt
|
| 741 |
+
text_encoder_lora_scale = (
|
| 742 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 743 |
+
)
|
| 744 |
+
(
|
| 745 |
+
prompt_embeds,
|
| 746 |
+
negative_prompt_embeds,
|
| 747 |
+
pooled_prompt_embeds,
|
| 748 |
+
negative_pooled_prompt_embeds,
|
| 749 |
+
) = self.encode_prompt(
|
| 750 |
+
prompt=prompt,
|
| 751 |
+
prompt_2=prompt_2,
|
| 752 |
+
device=device,
|
| 753 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 754 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 755 |
+
negative_prompt=negative_prompt,
|
| 756 |
+
negative_prompt_2=negative_prompt_2,
|
| 757 |
+
prompt_embeds=prompt_embeds,
|
| 758 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 759 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 760 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 761 |
+
lora_scale=text_encoder_lora_scale,
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
# 4. Prepare timesteps
|
| 765 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 766 |
+
|
| 767 |
+
timesteps = self.scheduler.timesteps
|
| 768 |
+
|
| 769 |
+
# 5. Prepare latent variables
|
| 770 |
+
num_channels_latents = self.unet.config.in_channels
|
| 771 |
+
latents = self.prepare_latents(
|
| 772 |
+
batch_size * num_images_per_prompt,
|
| 773 |
+
num_channels_latents,
|
| 774 |
+
height,
|
| 775 |
+
width,
|
| 776 |
+
prompt_embeds.dtype,
|
| 777 |
+
device,
|
| 778 |
+
generator,
|
| 779 |
+
latents,
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 783 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 784 |
+
|
| 785 |
+
# 7. Prepare added time ids & embeddings
|
| 786 |
+
add_text_embeds = pooled_prompt_embeds
|
| 787 |
+
add_time_ids = self._get_add_time_ids(
|
| 788 |
+
original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
|
| 789 |
+
)
|
| 790 |
+
if negative_original_size is not None and negative_target_size is not None:
|
| 791 |
+
negative_add_time_ids = self._get_add_time_ids(
|
| 792 |
+
negative_original_size,
|
| 793 |
+
negative_crops_coords_top_left,
|
| 794 |
+
negative_target_size,
|
| 795 |
+
dtype=prompt_embeds.dtype,
|
| 796 |
+
)
|
| 797 |
+
else:
|
| 798 |
+
negative_add_time_ids = add_time_ids
|
| 799 |
+
|
| 800 |
+
if do_classifier_free_guidance:
|
| 801 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
| 802 |
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
| 803 |
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
| 804 |
+
|
| 805 |
+
prompt_embeds = prompt_embeds.to(device)
|
| 806 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 807 |
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
| 808 |
+
|
| 809 |
+
# 8. Denoising loop
|
| 810 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
| 811 |
+
|
| 812 |
+
# 7.1 Apply denoising_end
|
| 813 |
+
if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
|
| 814 |
+
discrete_timestep_cutoff = int(
|
| 815 |
+
round(
|
| 816 |
+
self.scheduler.config.num_train_timesteps
|
| 817 |
+
- (denoising_end * self.scheduler.config.num_train_timesteps)
|
| 818 |
+
)
|
| 819 |
+
)
|
| 820 |
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
| 821 |
+
timesteps = timesteps[:num_inference_steps]
|
| 822 |
+
|
| 823 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 824 |
+
for i, t in enumerate(timesteps):
|
| 825 |
+
# expand the latents if we are doing classifier free guidance
|
| 826 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 827 |
+
|
| 828 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 829 |
+
|
| 830 |
+
# predict the noise residual
|
| 831 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 832 |
+
noise_pred = self.unet(
|
| 833 |
+
latent_model_input,
|
| 834 |
+
t,
|
| 835 |
+
encoder_hidden_states=prompt_embeds,
|
| 836 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 837 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 838 |
+
return_dict=False,
|
| 839 |
+
)[0]
|
| 840 |
+
|
| 841 |
+
# perform guidance
|
| 842 |
+
if do_classifier_free_guidance:
|
| 843 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 844 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 845 |
+
|
| 846 |
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
| 847 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 848 |
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
| 849 |
+
|
| 850 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 851 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 852 |
+
|
| 853 |
+
# call the callback, if provided
|
| 854 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 855 |
+
progress_bar.update()
|
| 856 |
+
if callback is not None and i % callback_steps == 0:
|
| 857 |
+
callback(i, t, latents)
|
| 858 |
+
|
| 859 |
+
if not output_type == "latent":
|
| 860 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 861 |
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
| 862 |
+
|
| 863 |
+
if needs_upcasting:
|
| 864 |
+
self.upcast_vae()
|
| 865 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 866 |
+
|
| 867 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 868 |
+
|
| 869 |
+
# cast back to fp16 if needed
|
| 870 |
+
if needs_upcasting:
|
| 871 |
+
self.vae.to(dtype=torch.float16)
|
| 872 |
+
else:
|
| 873 |
+
image = latents
|
| 874 |
+
|
| 875 |
+
if not output_type == "latent":
|
| 876 |
+
# apply watermark if available
|
| 877 |
+
if self.watermark is not None:
|
| 878 |
+
image = self.watermark.apply_watermark(image)
|
| 879 |
+
|
| 880 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 881 |
+
|
| 882 |
+
# Offload all models
|
| 883 |
+
self.maybe_free_model_hooks()
|
| 884 |
+
|
| 885 |
+
if not return_dict:
|
| 886 |
+
return (image,)
|
| 887 |
+
|
| 888 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
| 889 |
+
|
| 890 |
+
# Overrride to properly handle the loading and unloading of the additional text encoder.
|
| 891 |
+
def load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
|
| 892 |
+
# We could have accessed the unet config from `lora_state_dict()` too. We pass
|
| 893 |
+
# it here explicitly to be able to tell that it's coming from an SDXL
|
| 894 |
+
# pipeline.
|
| 895 |
+
|
| 896 |
+
# Remove any existing hooks.
|
| 897 |
+
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
|
| 898 |
+
from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
|
| 899 |
+
else:
|
| 900 |
+
raise ImportError("Offloading requires `accelerate v0.17.0` or higher.")
|
| 901 |
+
|
| 902 |
+
is_model_cpu_offload = False
|
| 903 |
+
is_sequential_cpu_offload = False
|
| 904 |
+
recursive = False
|
| 905 |
+
for _, component in self.components.items():
|
| 906 |
+
if isinstance(component, torch.nn.Module):
|
| 907 |
+
if hasattr(component, "_hf_hook"):
|
| 908 |
+
is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
|
| 909 |
+
is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
|
| 910 |
+
logger.info(
|
| 911 |
+
"Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
|
| 912 |
+
)
|
| 913 |
+
recursive = is_sequential_cpu_offload
|
| 914 |
+
remove_hook_from_module(component, recurse=recursive)
|
| 915 |
+
state_dict, network_alphas = self.lora_state_dict(
|
| 916 |
+
pretrained_model_name_or_path_or_dict,
|
| 917 |
+
unet_config=self.unet.config,
|
| 918 |
+
**kwargs,
|
| 919 |
+
)
|
| 920 |
+
self.load_lora_into_unet(state_dict, network_alphas=network_alphas, unet=self.unet)
|
| 921 |
+
|
| 922 |
+
text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
|
| 923 |
+
if len(text_encoder_state_dict) > 0:
|
| 924 |
+
self.load_lora_into_text_encoder(
|
| 925 |
+
text_encoder_state_dict,
|
| 926 |
+
network_alphas=network_alphas,
|
| 927 |
+
text_encoder=self.text_encoder,
|
| 928 |
+
prefix="text_encoder",
|
| 929 |
+
lora_scale=self.lora_scale,
|
| 930 |
+
)
|
| 931 |
+
|
| 932 |
+
text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
|
| 933 |
+
if len(text_encoder_2_state_dict) > 0:
|
| 934 |
+
self.load_lora_into_text_encoder(
|
| 935 |
+
text_encoder_2_state_dict,
|
| 936 |
+
network_alphas=network_alphas,
|
| 937 |
+
text_encoder=self.text_encoder_2,
|
| 938 |
+
prefix="text_encoder_2",
|
| 939 |
+
lora_scale=self.lora_scale,
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
# Offload back.
|
| 943 |
+
if is_model_cpu_offload:
|
| 944 |
+
self.enable_model_cpu_offload()
|
| 945 |
+
elif is_sequential_cpu_offload:
|
| 946 |
+
self.enable_sequential_cpu_offload()
|
| 947 |
+
|
| 948 |
+
@classmethod
|
| 949 |
+
def save_lora_weights(
|
| 950 |
+
self,
|
| 951 |
+
save_directory: Union[str, os.PathLike],
|
| 952 |
+
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 953 |
+
text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 954 |
+
text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
| 955 |
+
is_main_process: bool = True,
|
| 956 |
+
weight_name: str = None,
|
| 957 |
+
save_function: Callable = None,
|
| 958 |
+
safe_serialization: bool = True,
|
| 959 |
+
):
|
| 960 |
+
state_dict = {}
|
| 961 |
+
|
| 962 |
+
def pack_weights(layers, prefix):
|
| 963 |
+
layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
| 964 |
+
layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
|
| 965 |
+
return layers_state_dict
|
| 966 |
+
|
| 967 |
+
if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
|
| 968 |
+
raise ValueError(
|
| 969 |
+
"You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
if unet_lora_layers:
|
| 973 |
+
state_dict.update(pack_weights(unet_lora_layers, "unet"))
|
| 974 |
+
|
| 975 |
+
if text_encoder_lora_layers and text_encoder_2_lora_layers:
|
| 976 |
+
state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
|
| 977 |
+
state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
|
| 978 |
+
|
| 979 |
+
self.write_lora_layers(
|
| 980 |
+
state_dict=state_dict,
|
| 981 |
+
save_directory=save_directory,
|
| 982 |
+
is_main_process=is_main_process,
|
| 983 |
+
weight_name=weight_name,
|
| 984 |
+
save_function=save_function,
|
| 985 |
+
safe_serialization=safe_serialization,
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
def _remove_text_encoder_monkey_patch(self):
|
| 989 |
+
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
|
| 990 |
+
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
|
instructany2pix/diffusion/sdxl_img2img_pipeline.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
#from diffusers import StableDiffusionXLImg2ImgPipeline,StableDiffusionXLPipeline
|
| 3 |
+
from ..ddim.sdxl_pipeline import StableDiffusionXLPipeline
|
| 4 |
+
from diffusers.utils import load_image
|
| 5 |
+
from diffusers.models.unet_2d_condition import UNet2DConditionOutput
|
| 6 |
+
import diffusers
|
| 7 |
+
from diffusers import (
|
| 8 |
+
AutoencoderKL,
|
| 9 |
+
DDPMScheduler,
|
| 10 |
+
StableDiffusionXLPipeline,
|
| 11 |
+
UNet2DConditionModel,
|
| 12 |
+
StableDiffusionXLImg2ImgPipeline
|
| 13 |
+
)
|
| 14 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 15 |
+
from torch import nn
|
| 16 |
+
from torch import FloatTensor,Tensor
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class UnCLipXL(UNet2DConditionModel):
|
| 21 |
+
|
| 22 |
+
def __init__(self, adapt_project_dim=[1024,1024*4,2048],adapt_project_dim_2=[768,1024*4,1280],sample_size: int | None = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ..., mid_block_type: str | None = "UNetMidBlock2DCrossAttn", up_block_types: Tuple[str] = ..., only_cross_attention: bool | Tuple[bool] = False, block_out_channels: Tuple[int] = ..., layers_per_block: int | Tuple[int] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, dropout: float = 0, act_fn: str = "silu", norm_num_groups: int | None = 32, norm_eps: float = 0.00001, cross_attention_dim: int | Tuple[int] = 1280, transformer_layers_per_block: int | Tuple[int] | Tuple[Tuple] = 1, reverse_transformer_layers_per_block: Tuple[Tuple[int]] | None = None, encoder_hid_dim: int | None = None, encoder_hid_dim_type: str | None = None, attention_head_dim: int | Tuple[int] = 8, num_attention_heads: int | Tuple[int] | None = None, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: str | None = None, addition_embed_type: str | None = None, addition_time_embed_dim: int | None = None, num_class_embeds: int | None = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", resnet_skip_time_act: bool = False, resnet_out_scale_factor: int = 1, time_embedding_type: str = "positional", time_embedding_dim: int | None = None, time_embedding_act_fn: str | None = None, timestep_post_act: str | None = None, time_cond_proj_dim: int | None = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, projection_class_embeddings_input_dim: int | None = None, attention_type: str = "default", class_embeddings_concat: bool = False, mid_block_only_cross_attention: bool | None = None, cross_attention_norm: str | None = None, addition_embed_type_num_heads=64):
|
| 23 |
+
super().__init__(sample_size, in_channels, out_channels, center_input_sample, flip_sin_to_cos, freq_shift, down_block_types, mid_block_type, up_block_types, only_cross_attention, block_out_channels, layers_per_block, downsample_padding, mid_block_scale_factor, dropout, act_fn, norm_num_groups, norm_eps, cross_attention_dim, transformer_layers_per_block, reverse_transformer_layers_per_block, encoder_hid_dim, encoder_hid_dim_type, attention_head_dim, num_attention_heads, dual_cross_attention, use_linear_projection, class_embed_type, addition_embed_type, addition_time_embed_dim, num_class_embeds, upcast_attention, resnet_time_scale_shift, resnet_skip_time_act, resnet_out_scale_factor, time_embedding_type, time_embedding_dim, time_embedding_act_fn, timestep_post_act, time_cond_proj_dim, conv_in_kernel, conv_out_kernel, projection_class_embeddings_input_dim, attention_type, class_embeddings_concat, mid_block_only_cross_attention, cross_attention_norm, addition_embed_type_num_heads)
|
| 24 |
+
self.adapt_project_dim = adapt_project_dim
|
| 25 |
+
self.adapt_project_dim_2 = adapt_project_dim_2
|
| 26 |
+
self.add_prjection()
|
| 27 |
+
|
| 28 |
+
def add_prjection(self):
|
| 29 |
+
adapt_project_dim = self.adapt_project_dim
|
| 30 |
+
adapt_project_dim_2 = self.adapt_project_dim_2
|
| 31 |
+
self.projector_unclip = nn.Sequential(
|
| 32 |
+
nn.Linear(adapt_project_dim[0],adapt_project_dim[1]),
|
| 33 |
+
nn.GELU(),
|
| 34 |
+
nn.Linear(adapt_project_dim[1],adapt_project_dim[2]),
|
| 35 |
+
)
|
| 36 |
+
self.projector_unclip2 = nn.Sequential(
|
| 37 |
+
nn.Linear(adapt_project_dim_2[0],adapt_project_dim_2[1]),
|
| 38 |
+
nn.GELU(),
|
| 39 |
+
nn.Linear(adapt_project_dim_2[1],adapt_project_dim_2[2]),
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def forward(self, sample: FloatTensor, timestep: Tensor | float | int, encoder_hidden_states: Tensor, class_labels: Tensor | None = None, timestep_cond: Tensor | None = None, attention_mask: Tensor | None = None, cross_attention_kwargs: Dict[str, Any] | None = None, added_cond_kwargs: Dict[str, Tensor] | None = None, down_block_additional_residuals: Tuple[Tensor] | None = None, mid_block_additional_residual: Tensor | None = None, down_intrablock_additional_residuals: Tuple[Tensor] | None = None, encoder_attention_mask: Tensor | None = None, return_dict: bool = True) -> UNet2DConditionOutput | Tuple:
|
| 43 |
+
added_cond_kwargs['text_embeds'] = self.projector_unclip2(added_cond_kwargs['text_embeds'].to(encoder_hidden_states))
|
| 44 |
+
encoder_hidden_states = self.projector_unclip(encoder_hidden_states)
|
| 45 |
+
return super().forward(sample, timestep, encoder_hidden_states, class_labels, timestep_cond, attention_mask, cross_attention_kwargs, added_cond_kwargs, down_block_additional_residuals, mid_block_additional_residual, down_intrablock_additional_residuals, encoder_attention_mask, return_dict)
|
| 46 |
+
|
| 47 |
+
def process_clip(batch,clip_processor=None):
|
| 48 |
+
image = batch['pixel_values']
|
| 49 |
+
image = clip_processor(image)
|
| 50 |
+
batch['clip_input'] = image
|
| 51 |
+
return batch
|
| 52 |
+
|
| 53 |
+
def build_sdxl(pretrained = "stabilityai/stable-diffusion-xl-base-1.0",
|
| 54 |
+
ckpt="/localhome/data/ckpts/jacklishufan/sdxl/"):
|
| 55 |
+
unet = UnCLipXL.from_pretrained(
|
| 56 |
+
ckpt, subfolder="unet"
|
| 57 |
+
)
|
| 58 |
+
vae = AutoencoderKL.from_pretrained(
|
| 59 |
+
pretrained,
|
| 60 |
+
subfolder="vae" ,
|
| 61 |
+
# revision=args.revision,
|
| 62 |
+
)
|
| 63 |
+
pipeline = StableDiffusionXLPipeline.from_pretrained(
|
| 64 |
+
pretrained,
|
| 65 |
+
vae=vae,
|
| 66 |
+
unet=unet,
|
| 67 |
+
#revision=args.revision,
|
| 68 |
+
torch_dtype=torch.float16,
|
| 69 |
+
)
|
| 70 |
+
return pipeline
|
instructany2pix/llm/constants.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
| 2 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
| 3 |
+
|
| 4 |
+
LOGDIR = "."
|
| 5 |
+
|
| 6 |
+
# Model Constants
|
| 7 |
+
IGNORE_INDEX = -100
|
| 8 |
+
IMAGE_TOKEN_INDEX = -200
|
| 9 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
| 10 |
+
DEFAULT_AUDIO_TOKEN = "<audio>"
|
| 11 |
+
DEFAULT_VIDEO_TOKEN = "<video>"
|
| 12 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
| 13 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
| 14 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
| 15 |
+
DEFAULT_IM_GEN_START_TOKEN = "<im_gen_start>"
|
| 16 |
+
DEFAULT_AUDIO_GEN_START_TOKEN = "<au_gen_start>"
|
| 17 |
+
DEFAULT_VIDEO_GEN_START_TOKEN = "<vd_gen_start>"
|
| 18 |
+
DEFAULT_IM_GEN_END_TOKEN = "<im_gen_end>"
|
| 19 |
+
DEFAULT_IM_GEN_TOKEN = "<im_gen>"
|
| 20 |
+
DEFAULT_AUDIO_GEN_TOKEN = "<audio_gen>"
|
| 21 |
+
DEFAULT_VIDEO_GEN_TOKEN = "<video_gen>"
|
| 22 |
+
DEFAULT_AUDIO_GEN_START_TOKEN = "<audio_gen_start>"
|
| 23 |
+
DEFAULT_MSK_TOKEN = '<mask_gen>'
|
| 24 |
+
DEFAULT_BASE_TOKEN = '<base>'
|
| 25 |
+
DEFAULT_BASE_NULL_TOKEN = '<base_null>'
|
| 26 |
+
|
| 27 |
+
class REPLACEMENT_TYPE:
|
| 28 |
+
INPUT = 0
|
| 29 |
+
BASE = 1
|
| 30 |
+
GEN = 2
|
instructany2pix/llm/conversation.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from enum import auto, Enum
|
| 3 |
+
from typing import List, Tuple
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class SeparatorStyle(Enum):
|
| 7 |
+
"""Different separator style."""
|
| 8 |
+
SINGLE = auto()
|
| 9 |
+
TWO = auto()
|
| 10 |
+
MPT = auto()
|
| 11 |
+
PLAIN = auto()
|
| 12 |
+
LLAMA_2 = auto()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclasses.dataclass
|
| 16 |
+
class Conversation:
|
| 17 |
+
"""A class that keeps all conversation history."""
|
| 18 |
+
system: str
|
| 19 |
+
roles: List[str]
|
| 20 |
+
messages: List[List[str]]
|
| 21 |
+
offset: int
|
| 22 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
| 23 |
+
sep: str = "###"
|
| 24 |
+
sep2: str = None
|
| 25 |
+
version: str = "Unknown"
|
| 26 |
+
|
| 27 |
+
skip_next: bool = False
|
| 28 |
+
|
| 29 |
+
def get_prompt(self):
|
| 30 |
+
messages = self.messages
|
| 31 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
| 32 |
+
messages = self.messages.copy()
|
| 33 |
+
init_role, init_msg = messages[0].copy()
|
| 34 |
+
init_msg = init_msg[0].replace("<image>", "").strip()
|
| 35 |
+
if 'mmtag' in self.version:
|
| 36 |
+
messages[0] = (init_role, init_msg)
|
| 37 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
| 38 |
+
messages.insert(1, (self.roles[1], "Received."))
|
| 39 |
+
else:
|
| 40 |
+
messages[0] = (init_role, "<image>\n" + init_msg)
|
| 41 |
+
|
| 42 |
+
if self.sep_style == SeparatorStyle.SINGLE:
|
| 43 |
+
ret = self.system + self.sep
|
| 44 |
+
for role, message in messages:
|
| 45 |
+
if message:
|
| 46 |
+
if type(message) is tuple:
|
| 47 |
+
message, _, _ = message
|
| 48 |
+
ret += role + ": " + message + self.sep
|
| 49 |
+
else:
|
| 50 |
+
ret += role + ":"
|
| 51 |
+
elif self.sep_style == SeparatorStyle.TWO:
|
| 52 |
+
seps = [self.sep, self.sep2]
|
| 53 |
+
ret = self.system + seps[0]
|
| 54 |
+
for i, (role, message) in enumerate(messages):
|
| 55 |
+
if message:
|
| 56 |
+
if type(message) is tuple:
|
| 57 |
+
message, _, _ = message
|
| 58 |
+
ret += role + ": " + message + seps[i % 2]
|
| 59 |
+
else:
|
| 60 |
+
ret += role + ":"
|
| 61 |
+
elif self.sep_style == SeparatorStyle.MPT:
|
| 62 |
+
ret = self.system + self.sep
|
| 63 |
+
for role, message in messages:
|
| 64 |
+
if message:
|
| 65 |
+
if type(message) is tuple:
|
| 66 |
+
message, _, _ = message
|
| 67 |
+
ret += role + message + self.sep
|
| 68 |
+
else:
|
| 69 |
+
ret += role
|
| 70 |
+
elif self.sep_style == SeparatorStyle.LLAMA_2:
|
| 71 |
+
wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
|
| 72 |
+
wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
|
| 73 |
+
ret = ""
|
| 74 |
+
|
| 75 |
+
for i, (role, message) in enumerate(messages):
|
| 76 |
+
if i == 0:
|
| 77 |
+
assert message, "first message should not be none"
|
| 78 |
+
assert role == self.roles[0], "first message should come from user"
|
| 79 |
+
if message:
|
| 80 |
+
if type(message) is tuple:
|
| 81 |
+
message, _, _ = message
|
| 82 |
+
if i == 0: message = wrap_sys(self.system) + message
|
| 83 |
+
if i % 2 == 0:
|
| 84 |
+
message = wrap_inst(message)
|
| 85 |
+
ret += self.sep + message
|
| 86 |
+
else:
|
| 87 |
+
ret += " " + message + " " + self.sep2
|
| 88 |
+
else:
|
| 89 |
+
ret += ""
|
| 90 |
+
ret = ret.lstrip(self.sep)
|
| 91 |
+
elif self.sep_style == SeparatorStyle.PLAIN:
|
| 92 |
+
seps = [self.sep, self.sep2]
|
| 93 |
+
ret = self.system
|
| 94 |
+
for i, (role, message) in enumerate(messages):
|
| 95 |
+
if message:
|
| 96 |
+
if type(message) is tuple:
|
| 97 |
+
message, _, _ = message
|
| 98 |
+
ret += message + seps[i % 2]
|
| 99 |
+
else:
|
| 100 |
+
ret += ""
|
| 101 |
+
else:
|
| 102 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
| 103 |
+
|
| 104 |
+
return ret
|
| 105 |
+
|
| 106 |
+
def append_message(self, role, message):
|
| 107 |
+
self.messages.append([role, message])
|
| 108 |
+
|
| 109 |
+
def get_images(self, return_pil=False):
|
| 110 |
+
images = []
|
| 111 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 112 |
+
if i % 2 == 0:
|
| 113 |
+
if type(msg) is tuple:
|
| 114 |
+
import base64
|
| 115 |
+
from io import BytesIO
|
| 116 |
+
from PIL import Image
|
| 117 |
+
msg, image, image_process_mode = msg
|
| 118 |
+
if image_process_mode == "Pad":
|
| 119 |
+
def expand2square(pil_img, background_color=(122, 116, 104)):
|
| 120 |
+
width, height = pil_img.size
|
| 121 |
+
if width == height:
|
| 122 |
+
return pil_img
|
| 123 |
+
elif width > height:
|
| 124 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 125 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 126 |
+
return result
|
| 127 |
+
else:
|
| 128 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 129 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 130 |
+
return result
|
| 131 |
+
image = expand2square(image)
|
| 132 |
+
elif image_process_mode in ["Default", "Crop"]:
|
| 133 |
+
pass
|
| 134 |
+
elif image_process_mode == "Resize":
|
| 135 |
+
image = image.resize((336, 336))
|
| 136 |
+
else:
|
| 137 |
+
raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
|
| 138 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
| 139 |
+
aspect_ratio = max_hw / min_hw
|
| 140 |
+
max_len, min_len = 800, 400
|
| 141 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 142 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
| 143 |
+
W, H = image.size
|
| 144 |
+
if longest_edge != max(image.size):
|
| 145 |
+
if H > W:
|
| 146 |
+
H, W = longest_edge, shortest_edge
|
| 147 |
+
else:
|
| 148 |
+
H, W = shortest_edge, longest_edge
|
| 149 |
+
image = image.resize((W, H))
|
| 150 |
+
if return_pil:
|
| 151 |
+
images.append(image)
|
| 152 |
+
else:
|
| 153 |
+
buffered = BytesIO()
|
| 154 |
+
image.save(buffered, format="PNG")
|
| 155 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 156 |
+
images.append(img_b64_str)
|
| 157 |
+
return images
|
| 158 |
+
|
| 159 |
+
def to_gradio_chatbot(self):
|
| 160 |
+
ret = []
|
| 161 |
+
for i, (role, msg) in enumerate(self.messages[self.offset:]):
|
| 162 |
+
if i % 2 == 0:
|
| 163 |
+
if type(msg) is tuple:
|
| 164 |
+
import base64
|
| 165 |
+
from io import BytesIO
|
| 166 |
+
msg, image, image_process_mode = msg
|
| 167 |
+
max_hw, min_hw = max(image.size), min(image.size)
|
| 168 |
+
aspect_ratio = max_hw / min_hw
|
| 169 |
+
max_len, min_len = 800, 400
|
| 170 |
+
shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
|
| 171 |
+
longest_edge = int(shortest_edge * aspect_ratio)
|
| 172 |
+
W, H = image.size
|
| 173 |
+
if H > W:
|
| 174 |
+
H, W = longest_edge, shortest_edge
|
| 175 |
+
else:
|
| 176 |
+
H, W = shortest_edge, longest_edge
|
| 177 |
+
image = image.resize((W, H))
|
| 178 |
+
buffered = BytesIO()
|
| 179 |
+
image.save(buffered, format="JPEG")
|
| 180 |
+
img_b64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 181 |
+
img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
|
| 182 |
+
msg = img_str + msg.replace('<image>', '').strip()
|
| 183 |
+
ret.append([msg, None])
|
| 184 |
+
else:
|
| 185 |
+
ret.append([msg, None])
|
| 186 |
+
else:
|
| 187 |
+
ret[-1][-1] = msg
|
| 188 |
+
return ret
|
| 189 |
+
|
| 190 |
+
def copy(self):
|
| 191 |
+
return Conversation(
|
| 192 |
+
system=self.system,
|
| 193 |
+
roles=self.roles,
|
| 194 |
+
messages=[[x, y] for x, y in self.messages],
|
| 195 |
+
offset=self.offset,
|
| 196 |
+
sep_style=self.sep_style,
|
| 197 |
+
sep=self.sep,
|
| 198 |
+
sep2=self.sep2,
|
| 199 |
+
version=self.version)
|
| 200 |
+
|
| 201 |
+
def dict(self):
|
| 202 |
+
if len(self.get_images()) > 0:
|
| 203 |
+
return {
|
| 204 |
+
"system": self.system,
|
| 205 |
+
"roles": self.roles,
|
| 206 |
+
"messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
|
| 207 |
+
"offset": self.offset,
|
| 208 |
+
"sep": self.sep,
|
| 209 |
+
"sep2": self.sep2,
|
| 210 |
+
}
|
| 211 |
+
return {
|
| 212 |
+
"system": self.system,
|
| 213 |
+
"roles": self.roles,
|
| 214 |
+
"messages": self.messages,
|
| 215 |
+
"offset": self.offset,
|
| 216 |
+
"sep": self.sep,
|
| 217 |
+
"sep2": self.sep2,
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
conv_vicuna_v0 = Conversation(
|
| 222 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 223 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 224 |
+
roles=("Human", "Assistant"),
|
| 225 |
+
messages=(
|
| 226 |
+
("Human", "What are the key differences between renewable and non-renewable energy sources?"),
|
| 227 |
+
("Assistant",
|
| 228 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
| 229 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
| 230 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
| 231 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
| 232 |
+
"renewable and non-renewable energy sources:\n"
|
| 233 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
| 234 |
+
"energy sources are finite and will eventually run out.\n"
|
| 235 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
| 236 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
| 237 |
+
"and other negative effects.\n"
|
| 238 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
| 239 |
+
"have lower operational costs than non-renewable sources.\n"
|
| 240 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
| 241 |
+
"locations than non-renewable sources.\n"
|
| 242 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
| 243 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
| 244 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
| 245 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
|
| 246 |
+
),
|
| 247 |
+
offset=2,
|
| 248 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 249 |
+
sep="###",
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
conv_vicuna_v1 = Conversation(
|
| 253 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 254 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
| 255 |
+
roles=("USER", "ASSISTANT"),
|
| 256 |
+
version="v1",
|
| 257 |
+
messages=(),
|
| 258 |
+
offset=0,
|
| 259 |
+
sep_style=SeparatorStyle.TWO,
|
| 260 |
+
sep=" ",
|
| 261 |
+
sep2="</s>",
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
conv_llama_2 = Conversation(
|
| 265 |
+
system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
|
| 266 |
+
|
| 267 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
|
| 268 |
+
roles=("USER", "ASSISTANT"),
|
| 269 |
+
version="llama_v2",
|
| 270 |
+
messages=(),
|
| 271 |
+
offset=0,
|
| 272 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
| 273 |
+
sep="<s>",
|
| 274 |
+
sep2="</s>",
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
conv_llava_llama_2 = Conversation(
|
| 278 |
+
system="You are a helpful language and vision assistant. "
|
| 279 |
+
"You are able to understand the visual content that the user provides, "
|
| 280 |
+
"and assist the user with a variety of tasks using natural language.",
|
| 281 |
+
roles=("USER", "ASSISTANT"),
|
| 282 |
+
version="llama_v2",
|
| 283 |
+
messages=(),
|
| 284 |
+
offset=0,
|
| 285 |
+
sep_style=SeparatorStyle.LLAMA_2,
|
| 286 |
+
sep="<s>",
|
| 287 |
+
sep2="</s>",
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
conv_mpt = Conversation(
|
| 291 |
+
system="""<|im_start|>system
|
| 292 |
+
A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
|
| 293 |
+
roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
|
| 294 |
+
version="mpt",
|
| 295 |
+
messages=(),
|
| 296 |
+
offset=0,
|
| 297 |
+
sep_style=SeparatorStyle.MPT,
|
| 298 |
+
sep="<|im_end|>",
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
conv_llava_plain = Conversation(
|
| 302 |
+
system="",
|
| 303 |
+
roles=("", ""),
|
| 304 |
+
messages=(
|
| 305 |
+
),
|
| 306 |
+
offset=0,
|
| 307 |
+
sep_style=SeparatorStyle.PLAIN,
|
| 308 |
+
sep="\n",
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
conv_llava_v0 = Conversation(
|
| 312 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 313 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 314 |
+
roles=("Human", "Assistant"),
|
| 315 |
+
messages=(
|
| 316 |
+
),
|
| 317 |
+
offset=0,
|
| 318 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 319 |
+
sep="###",
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
conv_llava_v0_mmtag = Conversation(
|
| 323 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 324 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
| 325 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
| 326 |
+
roles=("Human", "Assistant"),
|
| 327 |
+
messages=(
|
| 328 |
+
),
|
| 329 |
+
offset=0,
|
| 330 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 331 |
+
sep="###",
|
| 332 |
+
version="v0_mmtag",
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
conv_llava_v1 = Conversation(
|
| 336 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
| 337 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
| 338 |
+
roles=("USER", "ASSISTANT"),
|
| 339 |
+
version="v1",
|
| 340 |
+
messages=(),
|
| 341 |
+
offset=0,
|
| 342 |
+
sep_style=SeparatorStyle.TWO,
|
| 343 |
+
sep=" ",
|
| 344 |
+
sep2="</s>",
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
conv_llava_v1_mmtag = Conversation(
|
| 348 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
| 349 |
+
"The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
|
| 350 |
+
"The visual content will be provided with the following format: <Image>visual content</Image>.",
|
| 351 |
+
roles=("USER", "ASSISTANT"),
|
| 352 |
+
messages=(),
|
| 353 |
+
offset=0,
|
| 354 |
+
sep_style=SeparatorStyle.TWO,
|
| 355 |
+
sep=" ",
|
| 356 |
+
sep2="</s>",
|
| 357 |
+
version="v1_mmtag",
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
default_conversation = conv_vicuna_v0
|
| 361 |
+
conv_templates = {
|
| 362 |
+
"default": conv_vicuna_v0,
|
| 363 |
+
"v0": conv_vicuna_v0,
|
| 364 |
+
"v1": conv_vicuna_v1,
|
| 365 |
+
"vicuna_v1": conv_vicuna_v1,
|
| 366 |
+
"llama_2": conv_llama_2,
|
| 367 |
+
|
| 368 |
+
"plain": conv_llava_plain,
|
| 369 |
+
"v0_plain": conv_llava_plain,
|
| 370 |
+
"llava_v0": conv_llava_v0,
|
| 371 |
+
"v0_mmtag": conv_llava_v0_mmtag,
|
| 372 |
+
"llava_v1": conv_llava_v1,
|
| 373 |
+
"v1_mmtag": conv_llava_v1_mmtag,
|
| 374 |
+
"llava_llama_2": conv_llava_llama_2,
|
| 375 |
+
|
| 376 |
+
"mpt": conv_mpt,
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
if __name__ == "__main__":
|
| 381 |
+
print(default_conversation.get_prompt())
|
instructany2pix/llm/mm_utils.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
from PIL import Image
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
import base64
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import StoppingCriteria
|
| 8 |
+
from instructany2pix.llm.constants import IMAGE_TOKEN_INDEX
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_image_from_base64(image):
|
| 12 |
+
return Image.open(BytesIO(base64.b64decode(image)))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def expand2square(pil_img, background_color):
|
| 16 |
+
width, height = pil_img.size
|
| 17 |
+
if width == height:
|
| 18 |
+
return pil_img
|
| 19 |
+
elif width > height:
|
| 20 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
| 21 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
| 22 |
+
return result
|
| 23 |
+
else:
|
| 24 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
| 25 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
| 26 |
+
return result
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def process_images(images, image_processor, model_cfg):
|
| 30 |
+
image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
|
| 31 |
+
new_images = []
|
| 32 |
+
if image_aspect_ratio == 'pad':
|
| 33 |
+
for image in images:
|
| 34 |
+
image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean))
|
| 35 |
+
image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
| 36 |
+
new_images.append(image)
|
| 37 |
+
else:
|
| 38 |
+
return image_processor(images, return_tensors='pt')['pixel_values']
|
| 39 |
+
if all(x.shape == new_images[0].shape for x in new_images):
|
| 40 |
+
new_images = torch.stack(new_images, dim=0)
|
| 41 |
+
return new_images
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
|
| 45 |
+
prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('<image>')]
|
| 46 |
+
|
| 47 |
+
def insert_separator(X, sep):
|
| 48 |
+
return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
|
| 49 |
+
|
| 50 |
+
input_ids = []
|
| 51 |
+
offset = 0
|
| 52 |
+
if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
|
| 53 |
+
offset = 1
|
| 54 |
+
input_ids.append(prompt_chunks[0][0])
|
| 55 |
+
|
| 56 |
+
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
|
| 57 |
+
input_ids.extend(x[offset:])
|
| 58 |
+
|
| 59 |
+
if return_tensors is not None:
|
| 60 |
+
if return_tensors == 'pt':
|
| 61 |
+
return torch.tensor(input_ids, dtype=torch.long)
|
| 62 |
+
raise ValueError(f'Unsupported tensor type: {return_tensors}')
|
| 63 |
+
return input_ids
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_model_name_from_path(model_path):
|
| 67 |
+
model_path = model_path.strip("/")
|
| 68 |
+
model_paths = model_path.split("/")
|
| 69 |
+
if model_paths[-1].startswith('checkpoint-'):
|
| 70 |
+
return model_paths[-2] + "_" + model_paths[-1]
|
| 71 |
+
else:
|
| 72 |
+
return model_paths[-1]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class KeywordsStoppingCriteria(StoppingCriteria):
|
| 78 |
+
def __init__(self, keywords, tokenizer, input_ids):
|
| 79 |
+
self.keywords = keywords
|
| 80 |
+
self.keyword_ids = []
|
| 81 |
+
self.max_keyword_len = 0
|
| 82 |
+
for keyword in keywords:
|
| 83 |
+
cur_keyword_ids = tokenizer(keyword).input_ids
|
| 84 |
+
if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
|
| 85 |
+
cur_keyword_ids = cur_keyword_ids[1:]
|
| 86 |
+
if len(cur_keyword_ids) > self.max_keyword_len:
|
| 87 |
+
self.max_keyword_len = len(cur_keyword_ids)
|
| 88 |
+
self.keyword_ids.append(torch.tensor(cur_keyword_ids))
|
| 89 |
+
self.tokenizer = tokenizer
|
| 90 |
+
self.start_len = input_ids.shape[1]
|
| 91 |
+
|
| 92 |
+
def call_bse(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 93 |
+
assert output_ids.shape[0] == 1, "Only support batch size 1 (yet)" # TODO
|
| 94 |
+
offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
|
| 95 |
+
self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
|
| 96 |
+
for keyword_id in self.keyword_ids:
|
| 97 |
+
if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
|
| 98 |
+
return True
|
| 99 |
+
outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
|
| 100 |
+
for keyword in self.keywords:
|
| 101 |
+
if keyword in outputs:
|
| 102 |
+
return True
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
|
| 106 |
+
res = [self.call_bse(output_ids[i:i+1],scores=None,**kwargs) for i,z in enumerate(output_ids) ]
|
| 107 |
+
return all(res)
|
instructany2pix/llm/model/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .language_model.any2pix_llama import InstructAny2PixLMForCausalLM, InstructAny2PixLMConfig
|
instructany2pix/llm/model/any2pix_arch.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Haotian Liu
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from abc import ABC, abstractmethod
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
|
| 21 |
+
from .multimodal_encoder.builder import build_vision_tower
|
| 22 |
+
from .multimodal_projector.builder import build_vision_projector,build_vision_predictor
|
| 23 |
+
|
| 24 |
+
from instructany2pix.llm.constants import (IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN,
|
| 25 |
+
DEFAULT_IM_END_TOKEN,DEFAULT_IM_GEN_TOKEN,DEFAULT_MSK_TOKEN,DEFAULT_IM_GEN_START_TOKEN,
|
| 26 |
+
DEFAULT_AUDIO_GEN_TOKEN,DEFAULT_AUDIO_GEN_START_TOKEN,DEFAULT_AUDIO_TOKEN,
|
| 27 |
+
DEFAULT_BASE_TOKEN,DEFAULT_VIDEO_TOKEN,DEFAULT_BASE_NULL_TOKEN)
|
| 28 |
+
import logging
|
| 29 |
+
from .vae.builder import build_vae,VQVAE
|
| 30 |
+
class InstructAny2PixLMMetaModel:
|
| 31 |
+
|
| 32 |
+
def __init__(self, config):
|
| 33 |
+
super(InstructAny2PixLMMetaModel, self).__init__(config)
|
| 34 |
+
|
| 35 |
+
if hasattr(config, "mm_vision_tower"):
|
| 36 |
+
print("pre_init")
|
| 37 |
+
self.vision_tower = build_vision_tower(config, delay_load=False)
|
| 38 |
+
self.mm_projector = build_vision_projector(config)
|
| 39 |
+
self.vae = VQVAE(self.config.vae_image,self.config.vae_audio)
|
| 40 |
+
self.generator_processor = self.vae.processor
|
| 41 |
+
self.vae_projector_image = build_vision_projector(self.config,input_size=self.vae.embed_dim_image)
|
| 42 |
+
self.vae_projector_audio = build_vision_projector(self.config,input_size=self.vae.embed_dim_audio)
|
| 43 |
+
self.vae_predictor_image = build_vision_predictor(self.config,output_size=self.vae.vocab_size_image)
|
| 44 |
+
self.vae_predictor_audio = build_vision_predictor(self.config,output_size=self.vae.vocab_size_audio)
|
| 45 |
+
|
| 46 |
+
#raise NotImplemented
|
| 47 |
+
|
| 48 |
+
def get_vision_tower(self):
|
| 49 |
+
vision_tower = getattr(self, 'vision_tower', None)
|
| 50 |
+
if type(vision_tower) is list:
|
| 51 |
+
vision_tower = vision_tower[0]
|
| 52 |
+
return vision_tower
|
| 53 |
+
|
| 54 |
+
def get_vae(self):
|
| 55 |
+
return self.vae
|
| 56 |
+
|
| 57 |
+
def initialize_vision_modules(self, model_args, fsdp=None):
|
| 58 |
+
vision_tower = model_args.vision_tower
|
| 59 |
+
mm_vision_select_layer = model_args.mm_vision_select_layer
|
| 60 |
+
mm_vision_select_feature = model_args.mm_vision_select_feature
|
| 61 |
+
pretrain_mm_mlp_adapter = model_args.pretrain_mm_mlp_adapter
|
| 62 |
+
print('load_vision_tower')
|
| 63 |
+
self.config.mm_vision_tower = vision_tower
|
| 64 |
+
|
| 65 |
+
vision_tower = build_vision_tower(model_args)
|
| 66 |
+
|
| 67 |
+
if fsdp is not None and len(fsdp) > 0:
|
| 68 |
+
self.vision_tower = [vision_tower]
|
| 69 |
+
else:
|
| 70 |
+
self.vision_tower = vision_tower
|
| 71 |
+
|
| 72 |
+
self.config.use_mm_proj = True
|
| 73 |
+
self.config.mm_projector_type = getattr(model_args, 'mm_projector_type', 'linear')
|
| 74 |
+
self.config.mm_hidden_size = vision_tower.hidden_size
|
| 75 |
+
self.config.mm_vision_select_layer = mm_vision_select_layer
|
| 76 |
+
self.config.mm_vision_select_feature = mm_vision_select_feature
|
| 77 |
+
|
| 78 |
+
self.mm_projector = build_vision_projector(self.config)
|
| 79 |
+
|
| 80 |
+
if pretrain_mm_mlp_adapter is not None:
|
| 81 |
+
mm_projector_weights = torch.load(pretrain_mm_mlp_adapter, map_location='cpu')
|
| 82 |
+
def get_w(weights, keyword):
|
| 83 |
+
return {k.split(keyword + '.')[1]: v for k, v in weights.items() if keyword in k}
|
| 84 |
+
|
| 85 |
+
self.mm_projector.load_state_dict(get_w(mm_projector_weights, 'mm_projector'))
|
| 86 |
+
# generation
|
| 87 |
+
self.config.vae_image = ''
|
| 88 |
+
self.config.vae_audio = ''
|
| 89 |
+
if model_args.vae_image:
|
| 90 |
+
self.config.vae_image = model_args.vae_image
|
| 91 |
+
if model_args.vae_audio:
|
| 92 |
+
self.config.vae_audio = model_args.vae_audio
|
| 93 |
+
print('load_vae')
|
| 94 |
+
self.vae = VQVAE(self.config.vae_image,self.config.vae_audio)
|
| 95 |
+
self.generator_processor = self.vae.processor
|
| 96 |
+
self.vae_projector_image = build_vision_projector(self.config,input_size=self.vae.embed_dim_image)
|
| 97 |
+
self.vae_projector_audio = build_vision_projector(self.config,input_size=self.vae.embed_dim_audio)
|
| 98 |
+
self.vae_predictor_image = build_vision_predictor(self.config,output_size=self.vae.vocab_size_image)
|
| 99 |
+
self.vae_predictor_audio = build_vision_predictor(self.config,output_size=self.vae.vocab_size_audio)
|
| 100 |
+
|
| 101 |
+
class InstructAny2PixLMMetaForCausalLM(ABC):
|
| 102 |
+
|
| 103 |
+
@abstractmethod
|
| 104 |
+
def get_model(self):
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
+
def get_vision_tower(self):
|
| 108 |
+
return self.get_model().get_vision_tower()
|
| 109 |
+
|
| 110 |
+
def get_vae(self):
|
| 111 |
+
return self.get_model().get_vae()
|
| 112 |
+
|
| 113 |
+
def encode_images(self, images):
|
| 114 |
+
image_features = self.get_model().get_vision_tower()(images)
|
| 115 |
+
image_features = self.get_model().mm_projector(image_features)
|
| 116 |
+
return image_features
|
| 117 |
+
|
| 118 |
+
def prepare_inputs_labels_for_multimodal(
|
| 119 |
+
self, input_ids, attention_mask, past_key_values, labels, images,novision=False
|
| 120 |
+
):
|
| 121 |
+
vision_tower = self.get_vision_tower()
|
| 122 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1 or novision:
|
| 123 |
+
if past_key_values is not None and vision_tower is not None and images is not None and input_ids.shape[1] == 1:
|
| 124 |
+
attention_mask = torch.ones((attention_mask.shape[0], past_key_values[-1][-1].shape[-2] + 1), dtype=attention_mask.dtype, device=attention_mask.device)
|
| 125 |
+
return None, attention_mask, past_key_values, self.get_model().embed_tokens(input_ids), labels
|
| 126 |
+
|
| 127 |
+
if False: # and type(images) is list or images.ndim == 5:
|
| 128 |
+
concat_images = torch.cat([image for image in images], dim=0)
|
| 129 |
+
image_features = self.encode_images(concat_images)
|
| 130 |
+
split_sizes = [image.shape[0] for image in images]
|
| 131 |
+
image_features = torch.split(image_features, split_sizes, dim=0)
|
| 132 |
+
image_features = [x.flatten(0, 1) for x in image_features]
|
| 133 |
+
else:
|
| 134 |
+
assert type(images)== dict
|
| 135 |
+
image_features = self.encode_images(images)
|
| 136 |
+
|
| 137 |
+
new_input_embeds = []
|
| 138 |
+
new_labels = [] if labels is not None else None
|
| 139 |
+
cur_image_idx = 0
|
| 140 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
| 141 |
+
if (cur_input_ids == IMAGE_TOKEN_INDEX).sum() == 0:
|
| 142 |
+
# multimodal LLM, but the current sample is not multimodal
|
| 143 |
+
# FIXME: this is a hacky fix, for deepspeed zero3 to work
|
| 144 |
+
half_len = cur_input_ids.shape[0] // 2
|
| 145 |
+
cur_image_features = image_features[cur_image_idx]
|
| 146 |
+
cur_input_embeds_1 = self.get_model().embed_tokens(cur_input_ids[:half_len])
|
| 147 |
+
cur_input_embeds_2 = self.get_model().embed_tokens(cur_input_ids[half_len:])
|
| 148 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0], cur_input_embeds_2], dim=0)
|
| 149 |
+
new_input_embeds.append(cur_input_embeds)
|
| 150 |
+
if labels is not None:
|
| 151 |
+
new_labels.append(labels[batch_idx])
|
| 152 |
+
cur_image_idx += 1
|
| 153 |
+
continue
|
| 154 |
+
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
| 155 |
+
cur_new_input_embeds = []
|
| 156 |
+
if labels is not None:
|
| 157 |
+
cur_labels = labels[batch_idx]
|
| 158 |
+
cur_new_labels = []
|
| 159 |
+
assert cur_labels.shape == cur_input_ids.shape
|
| 160 |
+
while image_token_indices.numel() > 0:
|
| 161 |
+
cur_image_features = image_features[cur_image_idx]
|
| 162 |
+
if len(cur_image_features.shape) == 1:
|
| 163 |
+
cur_image_features = cur_image_features[None,]
|
| 164 |
+
image_token_start = image_token_indices[0]
|
| 165 |
+
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
| 166 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start-1]).detach())
|
| 167 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start-1:image_token_start]))
|
| 168 |
+
cur_new_input_embeds.append(cur_image_features)
|
| 169 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[image_token_start+1:image_token_start+2]))
|
| 170 |
+
if labels is not None:
|
| 171 |
+
cur_new_labels.append(cur_labels[:image_token_start])
|
| 172 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
|
| 173 |
+
cur_new_labels.append(cur_labels[image_token_start:image_token_start+1])
|
| 174 |
+
cur_labels = cur_labels[image_token_start+2:]
|
| 175 |
+
else:
|
| 176 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids[:image_token_start]))
|
| 177 |
+
cur_new_input_embeds.append(cur_image_features)
|
| 178 |
+
if labels is not None:
|
| 179 |
+
cur_new_labels.append(cur_labels[:image_token_start])
|
| 180 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=labels.device, dtype=labels.dtype))
|
| 181 |
+
cur_labels = cur_labels[image_token_start+1:]
|
| 182 |
+
cur_image_idx += 1
|
| 183 |
+
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
| 184 |
+
cur_input_ids = cur_input_ids[image_token_start+2:]
|
| 185 |
+
else:
|
| 186 |
+
cur_input_ids = cur_input_ids[image_token_start+1:]
|
| 187 |
+
image_token_indices = torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0]
|
| 188 |
+
if cur_input_ids.numel() > 0:
|
| 189 |
+
if getattr(self.config, 'tune_mm_mlp_adapter', False) and getattr(self.config, 'mm_use_im_start_end', False):
|
| 190 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids).detach())
|
| 191 |
+
else:
|
| 192 |
+
cur_new_input_embeds.append(self.get_model().embed_tokens(cur_input_ids))
|
| 193 |
+
if labels is not None:
|
| 194 |
+
cur_new_labels.append(cur_labels)
|
| 195 |
+
cur_new_input_embeds = [x.to(device=self.device) for x in cur_new_input_embeds]
|
| 196 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds, dim=0)
|
| 197 |
+
new_input_embeds.append(cur_new_input_embeds)
|
| 198 |
+
if labels is not None:
|
| 199 |
+
cur_new_labels = torch.cat(cur_new_labels, dim=0)
|
| 200 |
+
new_labels.append(cur_new_labels)
|
| 201 |
+
|
| 202 |
+
if any(x.shape != new_input_embeds[0].shape for x in new_input_embeds):
|
| 203 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
| 204 |
+
|
| 205 |
+
new_input_embeds_align = []
|
| 206 |
+
for cur_new_embed in new_input_embeds:
|
| 207 |
+
cur_new_embed = torch.cat((cur_new_embed, torch.zeros((max_len - cur_new_embed.shape[0], cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)), dim=0)
|
| 208 |
+
new_input_embeds_align.append(cur_new_embed)
|
| 209 |
+
new_input_embeds = torch.stack(new_input_embeds_align, dim=0)
|
| 210 |
+
|
| 211 |
+
if labels is not None:
|
| 212 |
+
new_labels_align = []
|
| 213 |
+
_new_labels = new_labels
|
| 214 |
+
for cur_new_label in new_labels:
|
| 215 |
+
cur_new_label = torch.cat((cur_new_label, torch.full((max_len - cur_new_label.shape[0],), IGNORE_INDEX, dtype=cur_new_label.dtype, device=cur_new_label.device)), dim=0)
|
| 216 |
+
new_labels_align.append(cur_new_label)
|
| 217 |
+
new_labels = torch.stack(new_labels_align, dim=0)
|
| 218 |
+
|
| 219 |
+
if attention_mask is not None:
|
| 220 |
+
new_attention_mask = []
|
| 221 |
+
for cur_attention_mask, cur_new_labels, cur_new_labels_align in zip(attention_mask, _new_labels, new_labels):
|
| 222 |
+
new_attn_mask_pad_left = torch.full((cur_new_labels.shape[0] - labels.shape[1],), True, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 223 |
+
new_attn_mask_pad_right = torch.full((cur_new_labels_align.shape[0] - cur_new_labels.shape[0],), False, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 224 |
+
cur_new_attention_mask = torch.cat((new_attn_mask_pad_left, cur_attention_mask, new_attn_mask_pad_right), dim=0)
|
| 225 |
+
new_attention_mask.append(cur_new_attention_mask)
|
| 226 |
+
attention_mask = torch.stack(new_attention_mask, dim=0)
|
| 227 |
+
assert attention_mask.shape == new_labels.shape
|
| 228 |
+
else:
|
| 229 |
+
new_input_embeds = torch.stack(new_input_embeds, dim=0)
|
| 230 |
+
if labels is not None:
|
| 231 |
+
new_labels = torch.stack(new_labels, dim=0)
|
| 232 |
+
|
| 233 |
+
if attention_mask is not None:
|
| 234 |
+
new_attn_mask_pad_left = torch.full((attention_mask.shape[0], new_input_embeds.shape[1] - input_ids.shape[1]), True, dtype=attention_mask.dtype, device=attention_mask.device)
|
| 235 |
+
attention_mask = torch.cat((new_attn_mask_pad_left, attention_mask), dim=1)
|
| 236 |
+
assert attention_mask.shape == new_input_embeds.shape[:2]
|
| 237 |
+
|
| 238 |
+
return None, attention_mask, past_key_values, new_input_embeds, new_labels
|
| 239 |
+
|
| 240 |
+
def initialize_vision_tokenizer(self, model_args, tokenizer,pre_init=False):
|
| 241 |
+
if not pre_init:
|
| 242 |
+
if model_args.mm_use_im_patch_token:
|
| 243 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 244 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 245 |
+
|
| 246 |
+
if model_args.mm_use_im_start_end:
|
| 247 |
+
num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 248 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 249 |
+
|
| 250 |
+
if num_new_tokens > 0:
|
| 251 |
+
input_embeddings = self.get_input_embeddings().weight.data
|
| 252 |
+
output_embeddings = self.get_output_embeddings().weight.data
|
| 253 |
+
|
| 254 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(
|
| 255 |
+
dim=0, keepdim=True)
|
| 256 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(
|
| 257 |
+
dim=0, keepdim=True)
|
| 258 |
+
|
| 259 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
| 260 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
| 261 |
+
|
| 262 |
+
if model_args.tune_mm_mlp_adapter:
|
| 263 |
+
for p in self.get_input_embeddings().parameters():
|
| 264 |
+
p.requires_grad = True
|
| 265 |
+
for p in self.get_output_embeddings().parameters():
|
| 266 |
+
p.requires_grad = False
|
| 267 |
+
|
| 268 |
+
if model_args.pretrain_mm_mlp_adapter:
|
| 269 |
+
mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location='cpu')
|
| 270 |
+
embed_tokens_weight = mm_projector_weights['model.embed_tokens.weight']
|
| 271 |
+
assert num_new_tokens == 2
|
| 272 |
+
if input_embeddings.shape == embed_tokens_weight.shape:
|
| 273 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
|
| 274 |
+
elif embed_tokens_weight.shape[0] == num_new_tokens:
|
| 275 |
+
input_embeddings[-num_new_tokens:] = embed_tokens_weight
|
| 276 |
+
else:
|
| 277 |
+
raise ValueError(f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}.")
|
| 278 |
+
elif model_args.mm_use_im_patch_token:
|
| 279 |
+
if model_args.tune_mm_mlp_adapter:
|
| 280 |
+
for p in self.get_input_embeddings().parameters():
|
| 281 |
+
p.requires_grad = False
|
| 282 |
+
for p in self.get_output_embeddings().parameters():
|
| 283 |
+
p.requires_grad = False
|
| 284 |
+
|
| 285 |
+
if model_args.mm_use_gen:
|
| 286 |
+
tokenizer.add_tokens([DEFAULT_IM_GEN_START_TOKEN,DEFAULT_IM_GEN_TOKEN,DEFAULT_MSK_TOKEN,DEFAULT_AUDIO_GEN_TOKEN,DEFAULT_AUDIO_GEN_START_TOKEN,DEFAULT_AUDIO_TOKEN,
|
| 287 |
+
DEFAULT_VIDEO_TOKEN,DEFAULT_BASE_TOKEN,DEFAULT_BASE_NULL_TOKEN], special_tokens=True)
|
| 288 |
+
self.resize_token_embeddings(len(tokenizer))
|
| 289 |
+
#tokenizer(DEFAULT_IM_GEN_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 290 |
+
self.DEFAULT_IM_GEN_TOKEN_IDX = tokenizer(DEFAULT_IM_GEN_START_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 291 |
+
self.DEFAULT_IM_GEN_TOKEN_IDX = tokenizer(DEFAULT_IM_GEN_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 292 |
+
self.DEFAULT_MSK_TOKEN_IDX = tokenizer(DEFAULT_MSK_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 293 |
+
self.DEFAULT_AUDIO_GEN_TOKEN_IDX = tokenizer(DEFAULT_AUDIO_GEN_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 294 |
+
self.DEFAULT_AUDIO_GEN_START_TOKEN_IDX = tokenizer(DEFAULT_AUDIO_GEN_START_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 295 |
+
self.DEFAULT_AUDIO_TOKEN_IDX = tokenizer(DEFAULT_AUDIO_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 296 |
+
self.DEFAULT_VIDEO_TOKEN_IDX = tokenizer(DEFAULT_VIDEO_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 297 |
+
self.DEFAULT_BASE_TOKEN_IDX = tokenizer(DEFAULT_BASE_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 298 |
+
self.DEFAULT_BASE_NULL_TOKEN_IDX = tokenizer(DEFAULT_BASE_NULL_TOKEN,add_special_tokens=False)['input_ids'][0]
|
| 299 |
+
self.tokenizer = tokenizer
|
instructany2pix/llm/model/apply_delta.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Usage:
|
| 3 |
+
python3 -m fastchat.model.apply_delta --base ~/model_weights/llama-7b --target ~/model_weights/vicuna-7b --delta lmsys/vicuna-7b-delta
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 10 |
+
from ..model import InstructAny2PixLMForCausalLM
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def apply_delta(base_model_path, target_model_path, delta_path):
|
| 14 |
+
print("Loading base model")
|
| 15 |
+
base = AutoModelForCausalLM.from_pretrained(
|
| 16 |
+
base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 17 |
+
|
| 18 |
+
print("Loading delta")
|
| 19 |
+
delta = InstructAny2PixLMForCausalLM.from_pretrained(delta_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 20 |
+
delta_tokenizer = AutoTokenizer.from_pretrained(delta_path)
|
| 21 |
+
|
| 22 |
+
print("Applying delta")
|
| 23 |
+
for name, param in tqdm(delta.state_dict().items(), desc="Applying delta"):
|
| 24 |
+
if name not in base.state_dict():
|
| 25 |
+
assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
|
| 26 |
+
continue
|
| 27 |
+
if param.data.shape == base.state_dict()[name].shape:
|
| 28 |
+
param.data += base.state_dict()[name]
|
| 29 |
+
else:
|
| 30 |
+
assert name in ['model.embed_tokens.weight', 'lm_head.weight'], \
|
| 31 |
+
f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
|
| 32 |
+
bparam = base.state_dict()[name]
|
| 33 |
+
param.data[:bparam.shape[0], :bparam.shape[1]] += bparam
|
| 34 |
+
|
| 35 |
+
print("Saving target model")
|
| 36 |
+
delta.save_pretrained(target_model_path)
|
| 37 |
+
delta_tokenizer.save_pretrained(target_model_path)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
parser = argparse.ArgumentParser()
|
| 42 |
+
parser.add_argument("--base-model-path", type=str, required=True)
|
| 43 |
+
parser.add_argument("--target-model-path", type=str, required=True)
|
| 44 |
+
parser.add_argument("--delta-path", type=str, required=True)
|
| 45 |
+
|
| 46 |
+
args = parser.parse_args()
|
| 47 |
+
|
| 48 |
+
apply_delta(args.base_model_path, args.target_model_path, args.delta_path)
|
instructany2pix/llm/model/builder.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Haotian Liu
|
| 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 os
|
| 17 |
+
import warnings
|
| 18 |
+
import shutil
|
| 19 |
+
|
| 20 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig
|
| 21 |
+
import torch
|
| 22 |
+
from . import *
|
| 23 |
+
from instructany2pix.llm.constants import DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN,DEFAULT_AUDIO_TOKEN
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_pretrained_model(model_path, model_base, model_name, load_8bit=False, load_4bit=False, device_map="auto", device="cuda"):
|
| 27 |
+
kwargs = {"device_map": device_map}
|
| 28 |
+
|
| 29 |
+
if load_8bit:
|
| 30 |
+
kwargs['load_in_8bit'] = True
|
| 31 |
+
elif load_4bit:
|
| 32 |
+
kwargs['load_in_4bit'] = True
|
| 33 |
+
kwargs['quantization_config'] = BitsAndBytesConfig(
|
| 34 |
+
load_in_4bit=True,
|
| 35 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 36 |
+
bnb_4bit_use_double_quant=True,
|
| 37 |
+
bnb_4bit_quant_type='nf4'
|
| 38 |
+
)
|
| 39 |
+
else:
|
| 40 |
+
kwargs['torch_dtype'] = torch.float16
|
| 41 |
+
|
| 42 |
+
if 'instructany2pix' in model_name.lower():
|
| 43 |
+
if 'lora' in model_name.lower() and model_base is None:
|
| 44 |
+
warnings.warn('There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged.')
|
| 45 |
+
if 'lora' in model_name.lower() and model_base is not None:
|
| 46 |
+
lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
| 47 |
+
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 48 |
+
print('Loading instructany2pix from base model...')
|
| 49 |
+
model = InstructAny2PixLMForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs)
|
| 50 |
+
token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
|
| 51 |
+
if model.lm_head.weight.shape[0] != token_num:
|
| 52 |
+
model.lm_head.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
|
| 53 |
+
model.model.embed_tokens.weight = torch.nn.Parameter(torch.empty(token_num, tokem_dim, device=model.device, dtype=model.dtype))
|
| 54 |
+
|
| 55 |
+
print('Loading additional instructany2pix weights...')
|
| 56 |
+
if os.path.exists(os.path.join(model_path, 'non_lora_trainables.bin')):
|
| 57 |
+
non_lora_trainables = torch.load(os.path.join(model_path, 'non_lora_trainables.bin'), map_location='cpu')
|
| 58 |
+
else:
|
| 59 |
+
# this is probably from HF Hub
|
| 60 |
+
from huggingface_hub import hf_hub_download
|
| 61 |
+
def load_from_hf(repo_id, filename, subfolder=None):
|
| 62 |
+
cache_file = hf_hub_download(
|
| 63 |
+
repo_id=repo_id,
|
| 64 |
+
filename=filename,
|
| 65 |
+
subfolder=subfolder)
|
| 66 |
+
return torch.load(cache_file, map_location='cpu')
|
| 67 |
+
non_lora_trainables = load_from_hf(model_path, 'non_lora_trainables.bin')
|
| 68 |
+
non_lora_trainables = {(k[11:] if k.startswith('base_model.') else k): v for k, v in non_lora_trainables.items()}
|
| 69 |
+
if any(k.startswith('model.model.') for k in non_lora_trainables):
|
| 70 |
+
non_lora_trainables = {(k[6:] if k.startswith('model.') else k): v for k, v in non_lora_trainables.items()}
|
| 71 |
+
model.load_state_dict(non_lora_trainables, strict=False)
|
| 72 |
+
|
| 73 |
+
from peft import PeftModel
|
| 74 |
+
print('Loading LoRA weights...')
|
| 75 |
+
model = PeftModel.from_pretrained(model, model_path)
|
| 76 |
+
print('Merging LoRA weights...')
|
| 77 |
+
model = model.merge_and_unload()
|
| 78 |
+
print('Model is loaded...')
|
| 79 |
+
elif model_base is not None:
|
| 80 |
+
# this may be mm projector only
|
| 81 |
+
print('Loading InstructAny2Pix from base model...')
|
| 82 |
+
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 83 |
+
cfg_pretrained = AutoConfig.from_pretrained(model_path)
|
| 84 |
+
model = InstructAny2PixLMForCausalLM.from_pretrained(model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs)
|
| 85 |
+
|
| 86 |
+
mm_projector_weights = torch.load(os.path.join(model_path, 'mm_projector.bin'), map_location='cpu')
|
| 87 |
+
mm_projector_weights = {k: v.to(torch.float16) for k, v in mm_projector_weights.items()}
|
| 88 |
+
model.load_state_dict(mm_projector_weights, strict=False)
|
| 89 |
+
else:
|
| 90 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 91 |
+
model = InstructAny2PixLMForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
|
| 92 |
+
else:
|
| 93 |
+
# Load language model
|
| 94 |
+
if model_base is not None:
|
| 95 |
+
# PEFT model
|
| 96 |
+
from peft import PeftModel
|
| 97 |
+
tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
|
| 98 |
+
model = AutoModelForCausalLM.from_pretrained(model_base, torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
|
| 99 |
+
print(f"Loading LoRA weights from {model_path}")
|
| 100 |
+
model = PeftModel.from_pretrained(model, model_path)
|
| 101 |
+
print(f"Merging weights")
|
| 102 |
+
model = model.merge_and_unload()
|
| 103 |
+
print('Convert to FP16...')
|
| 104 |
+
model.to(torch.float16)
|
| 105 |
+
else:
|
| 106 |
+
use_fast = False
|
| 107 |
+
if 'mpt' in model_name.lower():
|
| 108 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
|
| 109 |
+
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs)
|
| 110 |
+
else:
|
| 111 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 112 |
+
model = AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
|
| 113 |
+
|
| 114 |
+
image_processor = None
|
| 115 |
+
|
| 116 |
+
if 'instructany2pix' in model_name.lower():
|
| 117 |
+
mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
|
| 118 |
+
mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
|
| 119 |
+
if mm_use_im_patch_token:
|
| 120 |
+
tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
|
| 121 |
+
if mm_use_im_start_end:
|
| 122 |
+
tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
|
| 123 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 124 |
+
|
| 125 |
+
vision_tower = model.get_vision_tower()
|
| 126 |
+
if not vision_tower.is_loaded:
|
| 127 |
+
vision_tower.load_model()
|
| 128 |
+
vision_tower.to(device=device, dtype=torch.float16)
|
| 129 |
+
image_processor = vision_tower.image_processor
|
| 130 |
+
|
| 131 |
+
if hasattr(model.config, "max_sequence_length"):
|
| 132 |
+
context_len = model.config.max_sequence_length
|
| 133 |
+
else:
|
| 134 |
+
context_len = 2048
|
| 135 |
+
|
| 136 |
+
return tokenizer, model, image_processor, context_len
|
instructany2pix/llm/model/consolidate.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import argparse
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
+
from . import *
|
| 7 |
+
from .utils import auto_upgrade
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def consolidate_ckpt(src_path, dst_path):
|
| 11 |
+
print("Loading model")
|
| 12 |
+
auto_upgrade(src_path)
|
| 13 |
+
src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 14 |
+
src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
|
| 15 |
+
src_model.save_pretrained(dst_path)
|
| 16 |
+
src_tokenizer.save_pretrained(dst_path)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if __name__ == "__main__":
|
| 20 |
+
parser = argparse.ArgumentParser()
|
| 21 |
+
parser.add_argument("--src", type=str, required=True)
|
| 22 |
+
parser.add_argument("--dst", type=str, required=True)
|
| 23 |
+
|
| 24 |
+
args = parser.parse_args()
|
| 25 |
+
|
| 26 |
+
consolidate_ckpt(args.src, args.dst)
|
instructany2pix/llm/model/language_model/__init__.py
ADDED
|
File without changes
|
instructany2pix/llm/model/language_model/any2pix_llama.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Haotian Liu
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from typing import List, Optional, Tuple, Union,Dict
|
| 17 |
+
from einops import rearrange
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from torch.nn import CrossEntropyLoss
|
| 21 |
+
|
| 22 |
+
from transformers import AutoConfig, AutoModelForCausalLM, \
|
| 23 |
+
LlamaConfig, LlamaModel, LlamaForCausalLM
|
| 24 |
+
|
| 25 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast,ModelOutput
|
| 26 |
+
|
| 27 |
+
from ..any2pix_arch import InstructAny2PixLMMetaModel, InstructAny2PixLMMetaForCausalLM
|
| 28 |
+
from instructany2pix.llm.constants import IGNORE_INDEX
|
| 29 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
| 30 |
+
import logging
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
class InstructAny2PixLMConfig(LlamaConfig):
|
| 35 |
+
model_type = "instructany2pix"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class InstructAny2PixLMModel(InstructAny2PixLMMetaModel, LlamaModel):
|
| 39 |
+
config_class = InstructAny2PixLMConfig
|
| 40 |
+
|
| 41 |
+
def __init__(self, config: LlamaConfig):
|
| 42 |
+
super(InstructAny2PixLMModel, self).__init__(config)
|
| 43 |
+
|
| 44 |
+
def forward(
|
| 45 |
+
self,
|
| 46 |
+
input_ids: torch.LongTensor = None,
|
| 47 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 48 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 49 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 50 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 51 |
+
use_cache: Optional[bool] = None,
|
| 52 |
+
output_attentions: Optional[bool] = None,
|
| 53 |
+
output_hidden_states: Optional[bool] = None,
|
| 54 |
+
return_dict: Optional[bool] = None,
|
| 55 |
+
#replacement_mask = None
|
| 56 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 57 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 58 |
+
output_hidden_states = (
|
| 59 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 60 |
+
)
|
| 61 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 62 |
+
|
| 63 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 64 |
+
|
| 65 |
+
# retrieve input_ids and inputs_embeds
|
| 66 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 67 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 68 |
+
elif input_ids is not None:
|
| 69 |
+
batch_size, seq_length = input_ids.shape
|
| 70 |
+
elif inputs_embeds is not None:
|
| 71 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 72 |
+
else:
|
| 73 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 74 |
+
|
| 75 |
+
seq_length_with_past = seq_length
|
| 76 |
+
past_key_values_length = 0
|
| 77 |
+
|
| 78 |
+
if past_key_values is not None:
|
| 79 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
| 80 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 81 |
+
|
| 82 |
+
if position_ids is None:
|
| 83 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 84 |
+
position_ids = torch.arange(
|
| 85 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 86 |
+
)
|
| 87 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
| 88 |
+
else:
|
| 89 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
| 90 |
+
|
| 91 |
+
if inputs_embeds is None:
|
| 92 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 93 |
+
# embed positions
|
| 94 |
+
if attention_mask is None:
|
| 95 |
+
attention_mask = torch.ones(
|
| 96 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
| 100 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 101 |
+
)
|
| 102 |
+
# if replacement_mask is not None and len(attention_mask.shape) == 4:
|
| 103 |
+
# replacement_mask = replacement_mask[:,None,:] & replacement_mask[:,:,None] # B X N X N
|
| 104 |
+
# replacement_mask = replacement_mask[:,None] # B X H X N X N
|
| 105 |
+
# attention_mask[replacement_mask] = 0.0
|
| 106 |
+
hidden_states = inputs_embeds
|
| 107 |
+
|
| 108 |
+
if self.gradient_checkpointing and self.training:
|
| 109 |
+
if use_cache:
|
| 110 |
+
logger.warning_once(
|
| 111 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 112 |
+
)
|
| 113 |
+
use_cache = False
|
| 114 |
+
|
| 115 |
+
# decoder layers
|
| 116 |
+
all_hidden_states = () if output_hidden_states else None
|
| 117 |
+
all_self_attns = () if output_attentions else None
|
| 118 |
+
next_decoder_cache = () if use_cache else None
|
| 119 |
+
|
| 120 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 121 |
+
if output_hidden_states:
|
| 122 |
+
all_hidden_states += (hidden_states,)
|
| 123 |
+
|
| 124 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 125 |
+
|
| 126 |
+
if self.gradient_checkpointing and self.training:
|
| 127 |
+
|
| 128 |
+
def create_custom_forward(module):
|
| 129 |
+
def custom_forward(*inputs):
|
| 130 |
+
# None for past_key_value
|
| 131 |
+
return module(*inputs, output_attentions, None)
|
| 132 |
+
|
| 133 |
+
return custom_forward
|
| 134 |
+
|
| 135 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 136 |
+
create_custom_forward(decoder_layer),
|
| 137 |
+
hidden_states,
|
| 138 |
+
attention_mask,
|
| 139 |
+
position_ids,
|
| 140 |
+
None,
|
| 141 |
+
)
|
| 142 |
+
else:
|
| 143 |
+
layer_outputs = decoder_layer(
|
| 144 |
+
hidden_states,
|
| 145 |
+
attention_mask=attention_mask,
|
| 146 |
+
position_ids=position_ids,
|
| 147 |
+
past_key_value=past_key_value,
|
| 148 |
+
output_attentions=output_attentions,
|
| 149 |
+
use_cache=use_cache,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
hidden_states = layer_outputs[0]
|
| 153 |
+
|
| 154 |
+
if use_cache:
|
| 155 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 156 |
+
|
| 157 |
+
if output_attentions:
|
| 158 |
+
all_self_attns += (layer_outputs[1],)
|
| 159 |
+
|
| 160 |
+
hidden_states = self.norm(hidden_states)
|
| 161 |
+
|
| 162 |
+
# add hidden states from the last decoder layer
|
| 163 |
+
if output_hidden_states:
|
| 164 |
+
all_hidden_states += (hidden_states,)
|
| 165 |
+
|
| 166 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 167 |
+
if not return_dict:
|
| 168 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 169 |
+
return BaseModelOutputWithPast(
|
| 170 |
+
last_hidden_state=hidden_states,
|
| 171 |
+
past_key_values=next_cache,
|
| 172 |
+
hidden_states=all_hidden_states,
|
| 173 |
+
attentions=all_self_attns,
|
| 174 |
+
)
|
| 175 |
+
from instructany2pix.llm.constants import REPLACEMENT_TYPE
|
| 176 |
+
|
| 177 |
+
class InstructAny2PixLMForCausalLM(LlamaForCausalLM, InstructAny2PixLMMetaForCausalLM):
|
| 178 |
+
config_class = InstructAny2PixLMConfig
|
| 179 |
+
|
| 180 |
+
def __init__(self, config):
|
| 181 |
+
super(LlamaForCausalLM, self).__init__(config)
|
| 182 |
+
self.model = InstructAny2PixLMModel(config)
|
| 183 |
+
|
| 184 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 185 |
+
#self.lm_head_img = nn.Linear(3, config.vocab_size, bias=False) # FIXME: Add config
|
| 186 |
+
# Initialize weights and apply final processing
|
| 187 |
+
self.post_init()
|
| 188 |
+
|
| 189 |
+
def get_model(self):
|
| 190 |
+
return self.model
|
| 191 |
+
|
| 192 |
+
def forward(
|
| 193 |
+
self,
|
| 194 |
+
input_ids: torch.LongTensor = None,
|
| 195 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 196 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 197 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 198 |
+
labels: Optional[torch.LongTensor] = None,
|
| 199 |
+
use_cache: Optional[bool] = None,
|
| 200 |
+
output_attentions: Optional[bool] = None,
|
| 201 |
+
output_hidden_states: Optional[bool] = None,
|
| 202 |
+
images: Optional[Dict] = None,
|
| 203 |
+
return_dict: Optional[bool] = None,
|
| 204 |
+
generation_target: Optional[Dict] = None,
|
| 205 |
+
return_generations=True,
|
| 206 |
+
extra_inputs=None,
|
| 207 |
+
extra_replacement=None,
|
| 208 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 209 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 210 |
+
output_hidden_states = (
|
| 211 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 212 |
+
)
|
| 213 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 214 |
+
|
| 215 |
+
if self.training:
|
| 216 |
+
encodings = self.get_model().get_vae()(generation_target)
|
| 217 |
+
else:
|
| 218 |
+
encodings = {}
|
| 219 |
+
# encode vae for
|
| 220 |
+
replacement_mask = torch.zeros_like(input_ids,dtype=bool).to(input_ids.device)
|
| 221 |
+
if 'image' in encodings:
|
| 222 |
+
quant_image,ind_image,info_image = encodings['image']
|
| 223 |
+
n = quant_image.shape[0]
|
| 224 |
+
if info_image:
|
| 225 |
+
ind_image = ind_image.view(n,-1)
|
| 226 |
+
loss_fct_img = nn.CrossEntropyLoss()
|
| 227 |
+
img_loss_obj = 'ar'
|
| 228 |
+
else:
|
| 229 |
+
ind_image = quant_image.squeeze(-1).squeeze(-1).unsqueeze(1)
|
| 230 |
+
loss_fct_img = nn.MSELoss()
|
| 231 |
+
img_loss_obj = 'latent'
|
| 232 |
+
img_embded = self.get_model().vae_projector_image(rearrange(quant_image,'n c h w -> n (h w) c') )
|
| 233 |
+
replacement_mask_img = input_ids == self.DEFAULT_IM_GEN_TOKEN_IDX
|
| 234 |
+
replacement_mask = replacement_mask | replacement_mask_img
|
| 235 |
+
if 'audio' in encodings:
|
| 236 |
+
quant_audio,ind_audio,info_audio = encodings['audio']
|
| 237 |
+
n = quant_audio.shape[0]
|
| 238 |
+
if info_audio:
|
| 239 |
+
ind_audio = ind_audio.view(n,-1)
|
| 240 |
+
loss_fct_aud = nn.CrossEntropyLoss()
|
| 241 |
+
audloss_obj = 'ar'
|
| 242 |
+
else:
|
| 243 |
+
ind_aud = quant_audio.squeeze(1)# N H W C -> N L C
|
| 244 |
+
loss_fct_aud = nn.MSELoss()
|
| 245 |
+
aud_loss_obj = 'latent'
|
| 246 |
+
audio_embded = self.get_model().vae_projector_audio(rearrange(quant_audio,'n h w c-> n (h w) c') )
|
| 247 |
+
replacement_mask_audio = input_ids == self.DEFAULT_AUDIO_GEN_TOKEN_IDX
|
| 248 |
+
replacement_mask = replacement_mask | replacement_mask_audio
|
| 249 |
+
|
| 250 |
+
# replacement_audio = input_ids == self.DEFAULT_AUDIO_GEN_TOKEN_IDX
|
| 251 |
+
# audio_input_embded = self.get_model().vae_projector_audio(rearrange(quant_audio,'n h w c-> n (h w) c') )
|
| 252 |
+
|
| 253 |
+
raw_input_ids = input_ids
|
| 254 |
+
input_ids, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, attention_mask, past_key_values, labels, images,novision=True)
|
| 255 |
+
if extra_replacement is not None:
|
| 256 |
+
if self.training:
|
| 257 |
+
extra_replacement_mask = (raw_input_ids == self.DEFAULT_VIDEO_TOKEN_IDX ) # | (
|
| 258 |
+
# raw_input_ids == self.DEFAULT_IM_GEN_TOKEN_IDX) | (raw_input_ids == self.DEFAULT_BASE_TOKEN_IDX) self.get_model().vae_projector_image[0].weight.grad
|
| 259 |
+
if extra_replacement['mask'].shape[0] != inputs_embeds[extra_replacement_mask].shape[0]:
|
| 260 |
+
print("SKIPPED")
|
| 261 |
+
extra_replacement['mask'] = torch.zeros(inputs_embeds[extra_replacement_mask].shape[0]).to(extra_replacement['mask'])
|
| 262 |
+
z = torch.zeros_like(inputs_embeds)
|
| 263 |
+
z2 = self.get_model().vae_projector_image(
|
| 264 |
+
extra_replacement['data'][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT])
|
| 265 |
+
a,b = torch.where(extra_replacement_mask)
|
| 266 |
+
z[a[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT],b[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT]] += z2
|
| 267 |
+
inputs_embeds[extra_replacement_mask][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT] = 0.0
|
| 268 |
+
z = z + inputs_embeds
|
| 269 |
+
inputs_embeds = z
|
| 270 |
+
print("Replaced:",len(extra_replacement['mask']==REPLACEMENT_TYPE.INPUT))
|
| 271 |
+
extra_tgt_mask = (extra_replacement['mask']==REPLACEMENT_TYPE.BASE )| (extra_replacement['mask']==REPLACEMENT_TYPE.GEN)
|
| 272 |
+
extra_replacement_gt = extra_replacement['data'][extra_tgt_mask]
|
| 273 |
+
loss_fn_extra = nn.L1Loss()
|
| 274 |
+
if extra_replacement_gt.shape[0]==0:
|
| 275 |
+
loss_fn_extra = None
|
| 276 |
+
else:
|
| 277 |
+
assert labels is None
|
| 278 |
+
extra_replacement_mask = (raw_input_ids == self.DEFAULT_VIDEO_TOKEN_IDX )
|
| 279 |
+
#print(len(extra_replacement['mask']==REPLACEMENT_TYPE.INPUT))
|
| 280 |
+
|
| 281 |
+
z = torch.zeros_like(inputs_embeds)
|
| 282 |
+
z2 = self.get_model().vae_projector_image(
|
| 283 |
+
extra_replacement['data'][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT])
|
| 284 |
+
#print("z2",z2)
|
| 285 |
+
a,b = torch.where(extra_replacement_mask)
|
| 286 |
+
a = a[:extra_replacement['mask'].shape[0]]
|
| 287 |
+
b = b[:extra_replacement['mask'].shape[0]]
|
| 288 |
+
z[a[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT],b[extra_replacement['mask']==REPLACEMENT_TYPE.INPUT]] += z2
|
| 289 |
+
inputs_embeds[extra_replacement_mask][:extra_replacement['mask'].shape[0]][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT] = 0.0
|
| 290 |
+
z = z + inputs_embeds
|
| 291 |
+
inputs_embeds = z
|
| 292 |
+
#print("HERE")
|
| 293 |
+
#print(inputs_embeds[extra_replacement_mask][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT])
|
| 294 |
+
|
| 295 |
+
# inputs_embeds[extra_replacement_mask][:extra_replacement['mask'].shape[0]][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT] = self.get_model().vae_projector_image(
|
| 296 |
+
# extra_replacement['data'][extra_replacement['mask']==REPLACEMENT_TYPE.INPUT].to(inputs_embeds))
|
| 297 |
+
# z.sum().backward()
|
| 298 |
+
if self.training:
|
| 299 |
+
for replace_info in generation_target['info']:
|
| 300 |
+
ii = replace_info['idx']
|
| 301 |
+
mm = replace_info['modality']
|
| 302 |
+
if mm == 'image':
|
| 303 |
+
inputs_embeds[replace_info['batch']][replacement_mask_img[replace_info['batch']]] = img_embded[ii]
|
| 304 |
+
#labels[replace_info['batch']][torch.where(replacement_mask_img[ii])[0]-1] just for sanity check <gen start>, <gen> ....
|
| 305 |
+
elif mm == 'audio':
|
| 306 |
+
inputs_embeds[replace_info['batch']][replacement_mask_audio[replace_info['batch']]] = audio_embded[ii]
|
| 307 |
+
# labels[labels==self.DEFAULT_IM_GEN_TOKEN_IDX] = IGNORE_INDEX
|
| 308 |
+
# labels[labels==self.DEFAULT_AUDIO_GEN_TOKEN_IDX] = IGNORE_INDEX
|
| 309 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 310 |
+
|
| 311 |
+
if extra_inputs is not None:
|
| 312 |
+
if 'audio' in extra_inputs:
|
| 313 |
+
audio_in = extra_inputs['audio'].squeeze(1) # N 8 768
|
| 314 |
+
audio_in = self.get_model().vae_projector_audio(audio_in)
|
| 315 |
+
msk_in = raw_input_ids == self.DEFAULT_AUDIO_TOKEN_IDX
|
| 316 |
+
for rinfo in extra_inputs['info']:
|
| 317 |
+
l_mask = msk_in[rinfo['bn']]
|
| 318 |
+
if l_mask.sum() !=8:
|
| 319 |
+
continue
|
| 320 |
+
else:
|
| 321 |
+
inputs_embeds[rinfo['bn'],l_mask]=audio_in[rinfo['idx']]
|
| 322 |
+
# hack, assume has N audio inp
|
| 323 |
+
|
| 324 |
+
outputs = self.model(
|
| 325 |
+
input_ids=input_ids,
|
| 326 |
+
attention_mask=attention_mask,
|
| 327 |
+
past_key_values=past_key_values,
|
| 328 |
+
inputs_embeds=inputs_embeds,
|
| 329 |
+
use_cache=use_cache,
|
| 330 |
+
output_attentions=output_attentions,
|
| 331 |
+
output_hidden_states=output_hidden_states,
|
| 332 |
+
return_dict=return_dict,
|
| 333 |
+
# replacement_mask=replacement_mask, # allow looking into future for images
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
hidden_states = outputs[0]
|
| 337 |
+
logits = self.lm_head(hidden_states)
|
| 338 |
+
|
| 339 |
+
loss = None
|
| 340 |
+
img_decode = None
|
| 341 |
+
aud_decode=None
|
| 342 |
+
individual_losses = {}
|
| 343 |
+
extra_gen = None
|
| 344 |
+
extra_gen_idx = None
|
| 345 |
+
if labels is not None:
|
| 346 |
+
# Shift so that tokens < n predict n
|
| 347 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 348 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 349 |
+
hidden_states.shape
|
| 350 |
+
output_vae_img = []
|
| 351 |
+
target_vae_img = []
|
| 352 |
+
output_vae_audio = []
|
| 353 |
+
target_vae_audio = []
|
| 354 |
+
for replace_info in generation_target['info']:
|
| 355 |
+
ii = replace_info['idx']
|
| 356 |
+
mm = replace_info['modality']
|
| 357 |
+
if mm == 'image':
|
| 358 |
+
output_vae_img.append(hidden_states[replace_info['batch']][:-1][replacement_mask_img[replace_info['batch']][1:]])
|
| 359 |
+
target_vae_img.append(ind_image[ii])
|
| 360 |
+
#labels[replace_info['batch']][torch.where(replacement_mask_img[ii])[0]-1] just for sanity check <gen start>, <gen> ....
|
| 361 |
+
elif mm == 'audio':
|
| 362 |
+
output_vae_audio.append(hidden_states[replace_info['batch']][:-1][replacement_mask_audio[replace_info['batch']][1:]])
|
| 363 |
+
target_vae_audio.append(ind_aud[ii])
|
| 364 |
+
loss_fct = CrossEntropyLoss()
|
| 365 |
+
|
| 366 |
+
#prediction = logits_img.argmax(-1)
|
| 367 |
+
|
| 368 |
+
# Flatten the tokens
|
| 369 |
+
|
| 370 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 371 |
+
shift_labels = shift_labels.view(-1)
|
| 372 |
+
# Enable model/pipeline parallelism
|
| 373 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 374 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 375 |
+
loss_lang = loss.detach().item()
|
| 376 |
+
individual_losses['loss_lang'] = loss_lang
|
| 377 |
+
if len(output_vae_img):
|
| 378 |
+
logits_img = self.get_model().vae_predictor_image(torch.cat(output_vae_img))
|
| 379 |
+
tgt_img = torch.cat(target_vae_img)
|
| 380 |
+
if img_loss_obj =='ar':
|
| 381 |
+
tgt_img = tgt_img.view(-1) # discrete tokens
|
| 382 |
+
loss_img = loss_fct_img(logits_img,tgt_img)
|
| 383 |
+
if img_loss_obj =='ar':
|
| 384 |
+
pass
|
| 385 |
+
else:
|
| 386 |
+
loss_img *= logits_img.shape[-1]
|
| 387 |
+
loss += loss_img
|
| 388 |
+
individual_losses['loss_img'] =loss_img.detach().item()
|
| 389 |
+
if return_generations:
|
| 390 |
+
with torch.no_grad():
|
| 391 |
+
if img_loss_obj =='ar':
|
| 392 |
+
img_encodings_pred = logits_img.argmax(-1).view(len(output_vae_img),-1)
|
| 393 |
+
else:
|
| 394 |
+
img_encodings_pred = logits_img.detach() # N, D_emb
|
| 395 |
+
img_decode = self.get_vae().image_vae.decode_seq(img_encodings_pred,info_image)
|
| 396 |
+
|
| 397 |
+
if len(output_vae_audio):
|
| 398 |
+
logits_aud = self.get_model().vae_predictor_audio(torch.cat(output_vae_audio))
|
| 399 |
+
tgt_aud = torch.cat(target_vae_audio)
|
| 400 |
+
if aud_loss_obj =='ar':
|
| 401 |
+
tgt_aud = tgt_aud.view(-1) # discrete tokens
|
| 402 |
+
loss_aud = loss_fct_aud(logits_aud,tgt_aud)
|
| 403 |
+
if aud_loss_obj =='ar':
|
| 404 |
+
pass
|
| 405 |
+
else:
|
| 406 |
+
loss_aud *= logits_aud.shape[-1]
|
| 407 |
+
loss += loss_aud
|
| 408 |
+
individual_losses['loss_aud'] =loss_aud.detach().item()
|
| 409 |
+
if return_generations:
|
| 410 |
+
with torch.no_grad():
|
| 411 |
+
if aud_loss_obj =='ar':
|
| 412 |
+
aud_encodings_pred = logits_aud.argmax(-1).view(len(output_vae_audio),-1)
|
| 413 |
+
else:
|
| 414 |
+
aud_encodings_pred = logits_aud.detach() # N, D_emb
|
| 415 |
+
aud_decode = self.get_vae().image_vae.decode_seq(aud_encodings_pred,info_audio)
|
| 416 |
+
if extra_replacement is not None:
|
| 417 |
+
extra_pred = self.get_model().vae_predictor_image(hidden_states[:,:-1][extra_replacement_mask[:,1:]])
|
| 418 |
+
extra_pred = extra_pred[extra_tgt_mask]
|
| 419 |
+
if labels is not None:
|
| 420 |
+
if loss_fn_extra is None:
|
| 421 |
+
loss_extra = extra_pred.sum() * 0.0
|
| 422 |
+
else:
|
| 423 |
+
loss_extra = loss_fn_extra(extra_pred,extra_replacement_gt)
|
| 424 |
+
if torch.isnan(loss_extra):
|
| 425 |
+
loss_extra = 0.0
|
| 426 |
+
loss += loss_extra
|
| 427 |
+
individual_losses['loss_extra'] =loss_extra.detach().item()
|
| 428 |
+
if return_generations:
|
| 429 |
+
extra_gen = extra_pred
|
| 430 |
+
extra_gen_idx = extra_replacement_mask[:,1:]
|
| 431 |
+
if not return_dict:
|
| 432 |
+
output = (logits,) + outputs[1:]
|
| 433 |
+
return (loss,) + output if loss is not None else output
|
| 434 |
+
|
| 435 |
+
return ModelOutput(
|
| 436 |
+
loss=loss,
|
| 437 |
+
logits=logits,
|
| 438 |
+
past_key_values=outputs.past_key_values,
|
| 439 |
+
hidden_states=outputs.hidden_states,
|
| 440 |
+
extra_gen=extra_gen,
|
| 441 |
+
extra_gen_idx=extra_gen_idx,
|
| 442 |
+
attentions=outputs.attentions,
|
| 443 |
+
img_decode=img_decode,
|
| 444 |
+
aud_decode=aud_decode,
|
| 445 |
+
individual_losses=individual_losses,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
def prepare_inputs_for_generation(
|
| 449 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 450 |
+
):
|
| 451 |
+
if past_key_values:
|
| 452 |
+
input_ids = input_ids[:, -1:]
|
| 453 |
+
|
| 454 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 455 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 456 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 457 |
+
else:
|
| 458 |
+
model_inputs = {"input_ids": input_ids}
|
| 459 |
+
|
| 460 |
+
model_inputs.update(
|
| 461 |
+
{
|
| 462 |
+
"past_key_values": past_key_values,
|
| 463 |
+
"use_cache": kwargs.get("use_cache"),
|
| 464 |
+
"attention_mask": attention_mask,
|
| 465 |
+
"images": kwargs.get("images", None),
|
| 466 |
+
"extra_replacement": kwargs.get("extra_replacement", None),
|
| 467 |
+
}
|
| 468 |
+
)
|
| 469 |
+
return model_inputs
|
| 470 |
+
|
| 471 |
+
AutoConfig.register("instructany2pix", InstructAny2PixLMConfig)
|
| 472 |
+
AutoModelForCausalLM.register(InstructAny2PixLMConfig, InstructAny2PixLMForCausalLM)
|
instructany2pix/llm/model/language_model/mpt/adapt_tokenizer.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Union
|
| 2 |
+
from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
|
| 3 |
+
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
| 4 |
+
NUM_SENTINEL_TOKENS: int = 100
|
| 5 |
+
|
| 6 |
+
def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
|
| 7 |
+
"""Adds sentinel tokens and padding token (if missing).
|
| 8 |
+
|
| 9 |
+
Expands the tokenizer vocabulary to include sentinel tokens
|
| 10 |
+
used in mixture-of-denoiser tasks as well as a padding token.
|
| 11 |
+
|
| 12 |
+
All added tokens are added as special tokens. No tokens are
|
| 13 |
+
added if sentinel tokens and padding token already exist.
|
| 14 |
+
"""
|
| 15 |
+
sentinels_to_add = [f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)]
|
| 16 |
+
tokenizer.add_tokens(sentinels_to_add, special_tokens=True)
|
| 17 |
+
if tokenizer.pad_token is None:
|
| 18 |
+
tokenizer.add_tokens('<pad>', special_tokens=True)
|
| 19 |
+
tokenizer.pad_token = '<pad>'
|
| 20 |
+
assert tokenizer.pad_token_id is not None
|
| 21 |
+
sentinels = ''.join([f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)])
|
| 22 |
+
_sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids
|
| 23 |
+
tokenizer.sentinel_token_ids = _sentinel_token_ids
|
| 24 |
+
|
| 25 |
+
class AutoTokenizerForMOD(AutoTokenizer):
|
| 26 |
+
"""AutoTokenizer + Adaptation for MOD.
|
| 27 |
+
|
| 28 |
+
A simple wrapper around AutoTokenizer to make instantiating
|
| 29 |
+
an MOD-adapted tokenizer a bit easier.
|
| 30 |
+
|
| 31 |
+
MOD-adapted tokenizers have sentinel tokens (e.g., <extra_id_0>),
|
| 32 |
+
a padding token, and a property to get the token ids of the
|
| 33 |
+
sentinel tokens.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
@classmethod
|
| 37 |
+
def from_pretrained(cls, *args, **kwargs):
|
| 38 |
+
"""See `AutoTokenizer.from_pretrained` docstring."""
|
| 39 |
+
tokenizer = super().from_pretrained(*args, **kwargs)
|
| 40 |
+
adapt_tokenizer_for_denoising(tokenizer)
|
| 41 |
+
return tokenizer
|
instructany2pix/llm/model/language_model/mpt/attention.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Attention layers."""
|
| 2 |
+
import math
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Optional
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from einops import rearrange
|
| 8 |
+
from packaging import version
|
| 9 |
+
from torch import nn
|
| 10 |
+
from .norm import LPLayerNorm
|
| 11 |
+
|
| 12 |
+
def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
|
| 13 |
+
if original_is_causal and num_query_tokens != num_key_tokens:
|
| 14 |
+
if num_query_tokens != 1:
|
| 15 |
+
raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
|
| 16 |
+
else:
|
| 17 |
+
return False
|
| 18 |
+
return original_is_causal
|
| 19 |
+
|
| 20 |
+
def scaled_multihead_dot_product_attention(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
| 21 |
+
q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
|
| 22 |
+
kv_n_heads = 1 if multiquery else n_heads
|
| 23 |
+
k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
|
| 24 |
+
v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
|
| 25 |
+
if past_key_value is not None:
|
| 26 |
+
if len(past_key_value) != 0:
|
| 27 |
+
k = torch.cat([past_key_value[0], k], dim=3)
|
| 28 |
+
v = torch.cat([past_key_value[1], v], dim=2)
|
| 29 |
+
past_key_value = (k, v)
|
| 30 |
+
(b, _, s_q, d) = q.shape
|
| 31 |
+
s_k = k.size(-1)
|
| 32 |
+
if softmax_scale is None:
|
| 33 |
+
softmax_scale = 1 / math.sqrt(d)
|
| 34 |
+
attn_weight = q.matmul(k) * softmax_scale
|
| 35 |
+
if attn_bias is not None:
|
| 36 |
+
_s_q = max(0, attn_bias.size(2) - s_q)
|
| 37 |
+
_s_k = max(0, attn_bias.size(3) - s_k)
|
| 38 |
+
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
| 39 |
+
if attn_bias.size(-1) != 1 and attn_bias.size(-1) != s_k or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q):
|
| 40 |
+
raise RuntimeError(f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.')
|
| 41 |
+
attn_weight = attn_weight + attn_bias
|
| 42 |
+
min_val = torch.finfo(q.dtype).min
|
| 43 |
+
if key_padding_mask is not None:
|
| 44 |
+
if attn_bias is not None:
|
| 45 |
+
warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
|
| 46 |
+
attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
|
| 47 |
+
if is_causal and (not q.size(2) == 1):
|
| 48 |
+
s = max(s_q, s_k)
|
| 49 |
+
causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
|
| 50 |
+
causal_mask = causal_mask.tril()
|
| 51 |
+
causal_mask = causal_mask.to(torch.bool)
|
| 52 |
+
causal_mask = ~causal_mask
|
| 53 |
+
causal_mask = causal_mask[-s_q:, -s_k:]
|
| 54 |
+
attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
|
| 55 |
+
attn_weight = torch.softmax(attn_weight, dim=-1)
|
| 56 |
+
if dropout_p:
|
| 57 |
+
attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
|
| 58 |
+
out = attn_weight.to(v.dtype).matmul(v)
|
| 59 |
+
out = rearrange(out, 'b h s d -> b s (h d)')
|
| 60 |
+
if needs_weights:
|
| 61 |
+
return (out, attn_weight, past_key_value)
|
| 62 |
+
return (out, None, past_key_value)
|
| 63 |
+
|
| 64 |
+
def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
|
| 65 |
+
for tensor in tensors:
|
| 66 |
+
if tensor.dtype not in valid_dtypes:
|
| 67 |
+
raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
|
| 68 |
+
if not tensor.is_cuda:
|
| 69 |
+
raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
|
| 70 |
+
|
| 71 |
+
def flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
| 72 |
+
try:
|
| 73 |
+
from flash_attn import bert_padding, flash_attn_interface
|
| 74 |
+
except:
|
| 75 |
+
raise RuntimeError('Please install flash-attn==1.0.3.post0')
|
| 76 |
+
check_valid_inputs(query, key, value)
|
| 77 |
+
if past_key_value is not None:
|
| 78 |
+
if len(past_key_value) != 0:
|
| 79 |
+
key = torch.cat([past_key_value[0], key], dim=1)
|
| 80 |
+
value = torch.cat([past_key_value[1], value], dim=1)
|
| 81 |
+
past_key_value = (key, value)
|
| 82 |
+
if attn_bias is not None:
|
| 83 |
+
_s_q = max(0, attn_bias.size(2) - query.size(1))
|
| 84 |
+
_s_k = max(0, attn_bias.size(3) - key.size(1))
|
| 85 |
+
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
| 86 |
+
if attn_bias is not None:
|
| 87 |
+
raise NotImplementedError(f'attn_bias not implemented for flash attn.')
|
| 88 |
+
(batch_size, seqlen) = query.shape[:2]
|
| 89 |
+
if key_padding_mask is None:
|
| 90 |
+
key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
|
| 91 |
+
query_padding_mask = key_padding_mask[:, -query.size(1):]
|
| 92 |
+
(query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
|
| 93 |
+
query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
|
| 94 |
+
(key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
|
| 95 |
+
key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
|
| 96 |
+
(value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
|
| 97 |
+
value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
|
| 98 |
+
if multiquery:
|
| 99 |
+
key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
|
| 100 |
+
value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
|
| 101 |
+
dropout_p = dropout_p if training else 0.0
|
| 102 |
+
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
| 103 |
+
output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
|
| 104 |
+
output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
|
| 105 |
+
return (output, None, past_key_value)
|
| 106 |
+
|
| 107 |
+
def triton_flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
|
| 108 |
+
try:
|
| 109 |
+
from .flash_attn_triton import flash_attn_func
|
| 110 |
+
except:
|
| 111 |
+
_installed = False
|
| 112 |
+
if version.parse(torch.__version__) < version.parse('2.0.0'):
|
| 113 |
+
_installed = True
|
| 114 |
+
try:
|
| 115 |
+
from flash_attn.flash_attn_triton import flash_attn_func
|
| 116 |
+
except:
|
| 117 |
+
_installed = False
|
| 118 |
+
if not _installed:
|
| 119 |
+
raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed.')
|
| 120 |
+
check_valid_inputs(query, key, value)
|
| 121 |
+
if past_key_value is not None:
|
| 122 |
+
if len(past_key_value) != 0:
|
| 123 |
+
key = torch.cat([past_key_value[0], key], dim=1)
|
| 124 |
+
value = torch.cat([past_key_value[1], value], dim=1)
|
| 125 |
+
past_key_value = (key, value)
|
| 126 |
+
if attn_bias is not None:
|
| 127 |
+
_s_q = max(0, attn_bias.size(2) - query.size(1))
|
| 128 |
+
_s_k = max(0, attn_bias.size(3) - key.size(1))
|
| 129 |
+
attn_bias = attn_bias[:, :, _s_q:, _s_k:]
|
| 130 |
+
if dropout_p:
|
| 131 |
+
raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
|
| 132 |
+
if needs_weights:
|
| 133 |
+
raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
|
| 134 |
+
if key_padding_mask is not None:
|
| 135 |
+
warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
|
| 136 |
+
(b_size, s_k) = key_padding_mask.shape[:2]
|
| 137 |
+
if attn_bias is None:
|
| 138 |
+
attn_bias = query.new_zeros(b_size, 1, 1, s_k)
|
| 139 |
+
attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
|
| 140 |
+
query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
|
| 141 |
+
key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
|
| 142 |
+
value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
|
| 143 |
+
if multiquery:
|
| 144 |
+
key = key.expand(*key.shape[:2], n_heads, key.size(-1))
|
| 145 |
+
value = value.expand(*value.shape[:2], n_heads, value.size(-1))
|
| 146 |
+
reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
|
| 147 |
+
attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
|
| 148 |
+
output = attn_output.view(*attn_output.shape[:2], -1)
|
| 149 |
+
return (output, None, past_key_value)
|
| 150 |
+
|
| 151 |
+
class MultiheadAttention(nn.Module):
|
| 152 |
+
"""Multi-head self attention.
|
| 153 |
+
|
| 154 |
+
Using torch or triton attention implementation enables user to also use
|
| 155 |
+
additive bias.
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
|
| 159 |
+
super().__init__()
|
| 160 |
+
self.attn_impl = attn_impl
|
| 161 |
+
self.clip_qkv = clip_qkv
|
| 162 |
+
self.qk_ln = qk_ln
|
| 163 |
+
self.d_model = d_model
|
| 164 |
+
self.n_heads = n_heads
|
| 165 |
+
self.softmax_scale = softmax_scale
|
| 166 |
+
if self.softmax_scale is None:
|
| 167 |
+
self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
|
| 168 |
+
self.attn_dropout_p = attn_pdrop
|
| 169 |
+
self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
|
| 170 |
+
fuse_splits = (d_model, 2 * d_model)
|
| 171 |
+
self.Wqkv._fused = (0, fuse_splits)
|
| 172 |
+
if self.qk_ln:
|
| 173 |
+
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
| 174 |
+
self.q_ln = layernorm_class(self.d_model, device=device)
|
| 175 |
+
self.k_ln = layernorm_class(self.d_model, device=device)
|
| 176 |
+
if self.attn_impl == 'flash':
|
| 177 |
+
self.attn_fn = flash_attn_fn
|
| 178 |
+
elif self.attn_impl == 'triton':
|
| 179 |
+
self.attn_fn = triton_flash_attn_fn
|
| 180 |
+
if verbose:
|
| 181 |
+
warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
|
| 182 |
+
elif self.attn_impl == 'torch':
|
| 183 |
+
self.attn_fn = scaled_multihead_dot_product_attention
|
| 184 |
+
if torch.cuda.is_available() and verbose:
|
| 185 |
+
warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
|
| 186 |
+
else:
|
| 187 |
+
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 188 |
+
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
| 189 |
+
self.out_proj._is_residual = True
|
| 190 |
+
|
| 191 |
+
def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
|
| 192 |
+
qkv = self.Wqkv(x)
|
| 193 |
+
if self.clip_qkv:
|
| 194 |
+
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
| 195 |
+
(query, key, value) = qkv.chunk(3, dim=2)
|
| 196 |
+
key_padding_mask = attention_mask
|
| 197 |
+
if self.qk_ln:
|
| 198 |
+
dtype = query.dtype
|
| 199 |
+
query = self.q_ln(query).to(dtype)
|
| 200 |
+
key = self.k_ln(key).to(dtype)
|
| 201 |
+
(context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights)
|
| 202 |
+
return (self.out_proj(context), attn_weights, past_key_value)
|
| 203 |
+
|
| 204 |
+
class MultiQueryAttention(nn.Module):
|
| 205 |
+
"""Multi-Query self attention.
|
| 206 |
+
|
| 207 |
+
Using torch or triton attention implementation enables user to also use
|
| 208 |
+
additive bias.
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.attn_impl = attn_impl
|
| 214 |
+
self.clip_qkv = clip_qkv
|
| 215 |
+
self.qk_ln = qk_ln
|
| 216 |
+
self.d_model = d_model
|
| 217 |
+
self.n_heads = n_heads
|
| 218 |
+
self.head_dim = d_model // n_heads
|
| 219 |
+
self.softmax_scale = softmax_scale
|
| 220 |
+
if self.softmax_scale is None:
|
| 221 |
+
self.softmax_scale = 1 / math.sqrt(self.head_dim)
|
| 222 |
+
self.attn_dropout_p = attn_pdrop
|
| 223 |
+
self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device)
|
| 224 |
+
fuse_splits = (d_model, d_model + self.head_dim)
|
| 225 |
+
self.Wqkv._fused = (0, fuse_splits)
|
| 226 |
+
if self.qk_ln:
|
| 227 |
+
layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
|
| 228 |
+
self.q_ln = layernorm_class(d_model, device=device)
|
| 229 |
+
self.k_ln = layernorm_class(self.head_dim, device=device)
|
| 230 |
+
if self.attn_impl == 'flash':
|
| 231 |
+
self.attn_fn = flash_attn_fn
|
| 232 |
+
elif self.attn_impl == 'triton':
|
| 233 |
+
self.attn_fn = triton_flash_attn_fn
|
| 234 |
+
if verbose:
|
| 235 |
+
warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
|
| 236 |
+
elif self.attn_impl == 'torch':
|
| 237 |
+
self.attn_fn = scaled_multihead_dot_product_attention
|
| 238 |
+
if torch.cuda.is_available() and verbose:
|
| 239 |
+
warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
|
| 240 |
+
else:
|
| 241 |
+
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 242 |
+
self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
|
| 243 |
+
self.out_proj._is_residual = True
|
| 244 |
+
|
| 245 |
+
def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
|
| 246 |
+
qkv = self.Wqkv(x)
|
| 247 |
+
if self.clip_qkv:
|
| 248 |
+
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
|
| 249 |
+
(query, key, value) = qkv.split([self.d_model, self.head_dim, self.head_dim], dim=2)
|
| 250 |
+
key_padding_mask = attention_mask
|
| 251 |
+
if self.qk_ln:
|
| 252 |
+
dtype = query.dtype
|
| 253 |
+
query = self.q_ln(query).to(dtype)
|
| 254 |
+
key = self.k_ln(key).to(dtype)
|
| 255 |
+
(context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, multiquery=True)
|
| 256 |
+
return (self.out_proj(context), attn_weights, past_key_value)
|
| 257 |
+
|
| 258 |
+
def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):
|
| 259 |
+
if attn_impl == 'flash':
|
| 260 |
+
return None
|
| 261 |
+
elif attn_impl in ['torch', 'triton']:
|
| 262 |
+
if alibi:
|
| 263 |
+
if (prefix_lm or not causal) or use_sequence_id:
|
| 264 |
+
return (1, n_heads, seq_len, seq_len)
|
| 265 |
+
return (1, n_heads, 1, seq_len)
|
| 266 |
+
elif prefix_lm or use_sequence_id:
|
| 267 |
+
return (1, 1, seq_len, seq_len)
|
| 268 |
+
return None
|
| 269 |
+
else:
|
| 270 |
+
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 271 |
+
|
| 272 |
+
def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8):
|
| 273 |
+
if attn_impl == 'flash':
|
| 274 |
+
return None
|
| 275 |
+
elif attn_impl in ['torch', 'triton']:
|
| 276 |
+
if alibi:
|
| 277 |
+
(device, dtype) = (attn_bias.device, attn_bias.dtype)
|
| 278 |
+
attn_bias = attn_bias.add(build_alibi_bias(n_heads, seq_len, full=not causal, alibi_bias_max=alibi_bias_max, device=device, dtype=dtype))
|
| 279 |
+
return attn_bias
|
| 280 |
+
else:
|
| 281 |
+
raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
|
| 282 |
+
|
| 283 |
+
def gen_slopes(n_heads, alibi_bias_max=8, device=None):
|
| 284 |
+
_n_heads = 2 ** math.ceil(math.log2(n_heads))
|
| 285 |
+
m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
|
| 286 |
+
m = m.mul(alibi_bias_max / _n_heads)
|
| 287 |
+
slopes = 1.0 / torch.pow(2, m)
|
| 288 |
+
if _n_heads != n_heads:
|
| 289 |
+
slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
|
| 290 |
+
return slopes.view(1, n_heads, 1, 1)
|
| 291 |
+
|
| 292 |
+
def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None):
|
| 293 |
+
alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len)
|
| 294 |
+
if full:
|
| 295 |
+
alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1)
|
| 296 |
+
alibi_bias = alibi_bias.abs().mul(-1)
|
| 297 |
+
slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
|
| 298 |
+
alibi_bias = alibi_bias * slopes
|
| 299 |
+
return alibi_bias.to(dtype=dtype)
|
| 300 |
+
ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention}
|
instructany2pix/llm/model/language_model/mpt/blocks.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GPT Blocks used for the GPT Model."""
|
| 2 |
+
from typing import Dict, Optional, Tuple
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from .attention import ATTN_CLASS_REGISTRY
|
| 6 |
+
from .norm import NORM_CLASS_REGISTRY
|
| 7 |
+
|
| 8 |
+
class MPTMLP(nn.Module):
|
| 9 |
+
|
| 10 |
+
def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None):
|
| 11 |
+
super().__init__()
|
| 12 |
+
self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device)
|
| 13 |
+
self.act = nn.GELU(approximate='none')
|
| 14 |
+
self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device)
|
| 15 |
+
self.down_proj._is_residual = True
|
| 16 |
+
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
return self.down_proj(self.act(self.up_proj(x)))
|
| 19 |
+
|
| 20 |
+
class MPTBlock(nn.Module):
|
| 21 |
+
|
| 22 |
+
def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', verbose: int=0, device: Optional[str]=None, **kwargs):
|
| 23 |
+
del kwargs
|
| 24 |
+
super().__init__()
|
| 25 |
+
norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
|
| 26 |
+
attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
|
| 27 |
+
self.norm_1 = norm_class(d_model, device=device)
|
| 28 |
+
self.attn = attn_class(attn_impl=attn_config['attn_impl'], clip_qkv=attn_config['clip_qkv'], qk_ln=attn_config['qk_ln'], softmax_scale=attn_config['softmax_scale'], attn_pdrop=attn_config['attn_pdrop'], d_model=d_model, n_heads=n_heads, verbose=verbose, device=device)
|
| 29 |
+
self.norm_2 = norm_class(d_model, device=device)
|
| 30 |
+
self.ffn = MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, device=device)
|
| 31 |
+
self.resid_attn_dropout = nn.Dropout(resid_pdrop)
|
| 32 |
+
self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
|
| 33 |
+
|
| 34 |
+
def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]:
|
| 35 |
+
a = self.norm_1(x)
|
| 36 |
+
(b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal)
|
| 37 |
+
x = x + self.resid_attn_dropout(b)
|
| 38 |
+
m = self.norm_2(x)
|
| 39 |
+
n = self.ffn(m)
|
| 40 |
+
x = x + self.resid_ffn_dropout(n)
|
| 41 |
+
return (x, attn_weights, past_key_value)
|
instructany2pix/llm/model/language_model/mpt/configuration_mpt.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A HuggingFace-style model configuration."""
|
| 2 |
+
from typing import Dict, Optional, Union
|
| 3 |
+
from transformers import PretrainedConfig
|
| 4 |
+
attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
|
| 5 |
+
init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
|
| 6 |
+
|
| 7 |
+
class MPTConfig(PretrainedConfig):
|
| 8 |
+
model_type = 'mpt'
|
| 9 |
+
|
| 10 |
+
def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, verbose: int=0, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, **kwargs):
|
| 11 |
+
"""The MPT configuration class.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
d_model (int): The size of the embedding dimension of the model.
|
| 15 |
+
n_heads (int): The number of attention heads.
|
| 16 |
+
n_layers (int): The number of layers in the model.
|
| 17 |
+
expansion_ratio (int): The ratio of the up/down scale in the MLP.
|
| 18 |
+
max_seq_len (int): The maximum sequence length of the model.
|
| 19 |
+
vocab_size (int): The size of the vocabulary.
|
| 20 |
+
resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
|
| 21 |
+
emb_pdrop (float): The dropout probability for the embedding layer.
|
| 22 |
+
learned_pos_emb (bool): Whether to use learned positional embeddings
|
| 23 |
+
attn_config (Dict): A dictionary used to configure the model's attention module:
|
| 24 |
+
attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
|
| 25 |
+
attn_pdrop (float): The dropout probability for the attention layers.
|
| 26 |
+
attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
|
| 27 |
+
qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
|
| 28 |
+
clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
|
| 29 |
+
this value.
|
| 30 |
+
softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
|
| 31 |
+
use the default scale of ``1/sqrt(d_keys)``.
|
| 32 |
+
prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an
|
| 33 |
+
extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix
|
| 34 |
+
can attend to one another bi-directionally. Tokens outside the prefix use causal attention.
|
| 35 |
+
attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id.
|
| 36 |
+
When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
|
| 37 |
+
which sub-sequence each token belongs to.
|
| 38 |
+
Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
|
| 39 |
+
alibi (bool): Whether to use the alibi bias instead of position embeddings.
|
| 40 |
+
alibi_bias_max (int): The maximum value of the alibi bias.
|
| 41 |
+
init_device (str): The device to use for parameter initialization.
|
| 42 |
+
logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
|
| 43 |
+
no_bias (bool): Whether to use bias in all layers.
|
| 44 |
+
verbose (int): The verbosity level. 0 is silent.
|
| 45 |
+
embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
|
| 46 |
+
norm_type (str): choose type of norm to use
|
| 47 |
+
multiquery_attention (bool): Whether to use multiquery attention implementation.
|
| 48 |
+
use_cache (bool): Whether or not the model should return the last key/values attentions
|
| 49 |
+
init_config (Dict): A dictionary used to configure the model initialization:
|
| 50 |
+
init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
|
| 51 |
+
'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or
|
| 52 |
+
'xavier_normal_'. These mimic the parameter initialization methods in PyTorch.
|
| 53 |
+
init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True.
|
| 54 |
+
emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer.
|
| 55 |
+
emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution
|
| 56 |
+
used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``.
|
| 57 |
+
init_std (float): The standard deviation of the normal distribution used to initialize the model,
|
| 58 |
+
if using the baseline_ parameter initialization scheme.
|
| 59 |
+
init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes.
|
| 60 |
+
fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes.
|
| 61 |
+
init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
|
| 62 |
+
---
|
| 63 |
+
See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
|
| 64 |
+
"""
|
| 65 |
+
self.d_model = d_model
|
| 66 |
+
self.n_heads = n_heads
|
| 67 |
+
self.n_layers = n_layers
|
| 68 |
+
self.expansion_ratio = expansion_ratio
|
| 69 |
+
self.max_seq_len = max_seq_len
|
| 70 |
+
self.vocab_size = vocab_size
|
| 71 |
+
self.resid_pdrop = resid_pdrop
|
| 72 |
+
self.emb_pdrop = emb_pdrop
|
| 73 |
+
self.learned_pos_emb = learned_pos_emb
|
| 74 |
+
self.attn_config = attn_config
|
| 75 |
+
self.init_device = init_device
|
| 76 |
+
self.logit_scale = logit_scale
|
| 77 |
+
self.no_bias = no_bias
|
| 78 |
+
self.verbose = verbose
|
| 79 |
+
self.embedding_fraction = embedding_fraction
|
| 80 |
+
self.norm_type = norm_type
|
| 81 |
+
self.use_cache = use_cache
|
| 82 |
+
self.init_config = init_config
|
| 83 |
+
if 'name' in kwargs:
|
| 84 |
+
del kwargs['name']
|
| 85 |
+
if 'loss_fn' in kwargs:
|
| 86 |
+
del kwargs['loss_fn']
|
| 87 |
+
super().__init__(**kwargs)
|
| 88 |
+
self._validate_config()
|
| 89 |
+
|
| 90 |
+
def _set_config_defaults(self, config, config_defaults):
|
| 91 |
+
for (k, v) in config_defaults.items():
|
| 92 |
+
if k not in config:
|
| 93 |
+
config[k] = v
|
| 94 |
+
return config
|
| 95 |
+
|
| 96 |
+
def _validate_config(self):
|
| 97 |
+
self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
|
| 98 |
+
self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
|
| 99 |
+
if self.d_model % self.n_heads != 0:
|
| 100 |
+
raise ValueError('d_model must be divisible by n_heads')
|
| 101 |
+
if any((prob < 0 or prob > 1 for prob in [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop])):
|
| 102 |
+
raise ValueError("self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1")
|
| 103 |
+
if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
|
| 104 |
+
raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
|
| 105 |
+
if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
| 106 |
+
raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
|
| 107 |
+
if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
| 108 |
+
raise NotImplementedError('alibi only implemented with torch and triton attention.')
|
| 109 |
+
if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
|
| 110 |
+
raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.')
|
| 111 |
+
if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
|
| 112 |
+
raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
|
| 113 |
+
if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
|
| 114 |
+
raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
| 115 |
+
if self.init_config.get('name', None) is None:
|
| 116 |
+
raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
|
| 117 |
+
if not self.learned_pos_emb and (not self.attn_config['alibi']):
|
| 118 |
+
raise ValueError(f'Positional information must be provided to the model using either learned_pos_emb or alibi.')
|
instructany2pix/llm/model/language_model/mpt/custom_embedding.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch import Tensor
|
| 5 |
+
|
| 6 |
+
class SharedEmbedding(nn.Embedding):
|
| 7 |
+
|
| 8 |
+
def forward(self, input: Tensor, unembed: bool=False) -> Tensor:
|
| 9 |
+
if unembed:
|
| 10 |
+
return F.linear(input, self.weight)
|
| 11 |
+
return super().forward(input)
|
instructany2pix/llm/model/language_model/mpt/flash_attn_triton.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
|
| 3 |
+
update imports to use 'triton_pre_mlir'
|
| 4 |
+
|
| 5 |
+
*Experimental* implementation of FlashAttention in Triton.
|
| 6 |
+
Tested with triton==2.0.0.dev20221202.
|
| 7 |
+
Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
|
| 8 |
+
other than 64:
|
| 9 |
+
https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
|
| 10 |
+
We'll update this implementation with the new Triton backend once this is fixed.
|
| 11 |
+
|
| 12 |
+
We use the FlashAttention implementation from Phil Tillet a starting point.
|
| 13 |
+
https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
|
| 14 |
+
|
| 15 |
+
Changes:
|
| 16 |
+
- Implement both causal and non-causal attention.
|
| 17 |
+
- Implement both self-attention and cross-attention.
|
| 18 |
+
- Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
|
| 19 |
+
- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
|
| 20 |
+
- Support attention bias.
|
| 21 |
+
- Speed up the forward pass a bit, and only store the LSE instead of m and l.
|
| 22 |
+
- Make the backward for d=128 much faster by reducing register spilling.
|
| 23 |
+
- Optionally parallelize the backward pass across seqlen_k, to deal with the case of
|
| 24 |
+
small batch size * nheads.
|
| 25 |
+
|
| 26 |
+
Caution:
|
| 27 |
+
- This is an *experimental* implementation. The forward pass should be quite robust but
|
| 28 |
+
I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
|
| 29 |
+
- This implementation has only been tested on A100.
|
| 30 |
+
- If you plan to use headdim other than 64 and 128, you should test for race conditions
|
| 31 |
+
(due to the Triton compiler), as done in tests/test_flash_attn.py
|
| 32 |
+
"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
|
| 33 |
+
for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
|
| 34 |
+
that there are none left for other head dimensions.
|
| 35 |
+
|
| 36 |
+
Differences between this Triton version and the CUDA version:
|
| 37 |
+
- Triton version doesn't support dropout.
|
| 38 |
+
- Triton forward is generally faster than CUDA forward, while Triton backward is
|
| 39 |
+
generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
|
| 40 |
+
than CUDA forward + backward.
|
| 41 |
+
- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
|
| 42 |
+
- Triton version supports attention bias, while CUDA version doesn't.
|
| 43 |
+
"""
|
| 44 |
+
import math
|
| 45 |
+
import torch
|
| 46 |
+
import triton_pre_mlir as triton
|
| 47 |
+
import triton_pre_mlir.language as tl
|
| 48 |
+
|
| 49 |
+
@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
|
| 50 |
+
@triton.jit
|
| 51 |
+
def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 52 |
+
start_m = tl.program_id(0)
|
| 53 |
+
off_hb = tl.program_id(1)
|
| 54 |
+
off_b = off_hb // nheads
|
| 55 |
+
off_h = off_hb % nheads
|
| 56 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 57 |
+
offs_n = tl.arange(0, BLOCK_N)
|
| 58 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 59 |
+
q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
|
| 60 |
+
k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
| 61 |
+
v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
| 62 |
+
if BIAS_TYPE == 'vector':
|
| 63 |
+
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
|
| 64 |
+
elif BIAS_TYPE == 'matrix':
|
| 65 |
+
b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
|
| 66 |
+
t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
|
| 67 |
+
lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
| 68 |
+
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
|
| 69 |
+
acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
|
| 70 |
+
if EVEN_M & EVEN_N:
|
| 71 |
+
if EVEN_HEADDIM:
|
| 72 |
+
q = tl.load(q_ptrs)
|
| 73 |
+
else:
|
| 74 |
+
q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 75 |
+
elif EVEN_HEADDIM:
|
| 76 |
+
q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
|
| 77 |
+
else:
|
| 78 |
+
q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 79 |
+
end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
|
| 80 |
+
for start_n in range(0, end_n, BLOCK_N):
|
| 81 |
+
start_n = tl.multiple_of(start_n, BLOCK_N)
|
| 82 |
+
if EVEN_N & EVEN_M:
|
| 83 |
+
if EVEN_HEADDIM:
|
| 84 |
+
k = tl.load(k_ptrs + start_n * stride_kn)
|
| 85 |
+
else:
|
| 86 |
+
k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
|
| 87 |
+
elif EVEN_HEADDIM:
|
| 88 |
+
k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
|
| 89 |
+
else:
|
| 90 |
+
k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 91 |
+
qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
|
| 92 |
+
qk += tl.dot(q, k, trans_b=True)
|
| 93 |
+
if not EVEN_N:
|
| 94 |
+
qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf'))
|
| 95 |
+
if IS_CAUSAL:
|
| 96 |
+
qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf'))
|
| 97 |
+
if BIAS_TYPE != 'none':
|
| 98 |
+
if BIAS_TYPE == 'vector':
|
| 99 |
+
if EVEN_N:
|
| 100 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
| 101 |
+
else:
|
| 102 |
+
bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32)
|
| 103 |
+
bias = bias[None, :]
|
| 104 |
+
elif BIAS_TYPE == 'matrix':
|
| 105 |
+
if EVEN_M & EVEN_N:
|
| 106 |
+
bias = tl.load(b_ptrs + start_n).to(tl.float32)
|
| 107 |
+
else:
|
| 108 |
+
bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32)
|
| 109 |
+
qk = qk * softmax_scale + bias
|
| 110 |
+
m_ij = tl.maximum(tl.max(qk, 1), lse_i)
|
| 111 |
+
p = tl.exp(qk - m_ij[:, None])
|
| 112 |
+
else:
|
| 113 |
+
m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
|
| 114 |
+
p = tl.exp(qk * softmax_scale - m_ij[:, None])
|
| 115 |
+
l_ij = tl.sum(p, 1)
|
| 116 |
+
acc_o_scale = tl.exp(m_i - m_ij)
|
| 117 |
+
tl.store(t_ptrs, acc_o_scale)
|
| 118 |
+
acc_o_scale = tl.load(t_ptrs)
|
| 119 |
+
acc_o = acc_o * acc_o_scale[:, None]
|
| 120 |
+
if EVEN_N & EVEN_M:
|
| 121 |
+
if EVEN_HEADDIM:
|
| 122 |
+
v = tl.load(v_ptrs + start_n * stride_vn)
|
| 123 |
+
else:
|
| 124 |
+
v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
|
| 125 |
+
elif EVEN_HEADDIM:
|
| 126 |
+
v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
|
| 127 |
+
else:
|
| 128 |
+
v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 129 |
+
p = p.to(v.dtype)
|
| 130 |
+
acc_o += tl.dot(p, v)
|
| 131 |
+
m_i = m_ij
|
| 132 |
+
l_i_new = tl.exp(lse_i - m_ij) + l_ij
|
| 133 |
+
lse_i = m_ij + tl.log(l_i_new)
|
| 134 |
+
o_scale = tl.exp(m_i - lse_i)
|
| 135 |
+
tl.store(t_ptrs, o_scale)
|
| 136 |
+
o_scale = tl.load(t_ptrs)
|
| 137 |
+
acc_o = acc_o * o_scale[:, None]
|
| 138 |
+
start_m = tl.program_id(0)
|
| 139 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 140 |
+
lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
|
| 141 |
+
tl.store(lse_ptrs, lse_i)
|
| 142 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 143 |
+
out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
|
| 144 |
+
if EVEN_M:
|
| 145 |
+
if EVEN_HEADDIM:
|
| 146 |
+
tl.store(out_ptrs, acc_o)
|
| 147 |
+
else:
|
| 148 |
+
tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
|
| 149 |
+
elif EVEN_HEADDIM:
|
| 150 |
+
tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
|
| 151 |
+
else:
|
| 152 |
+
tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
|
| 153 |
+
|
| 154 |
+
@triton.jit
|
| 155 |
+
def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr):
|
| 156 |
+
start_m = tl.program_id(0)
|
| 157 |
+
off_hb = tl.program_id(1)
|
| 158 |
+
off_b = off_hb // nheads
|
| 159 |
+
off_h = off_hb % nheads
|
| 160 |
+
offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 161 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 162 |
+
o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
|
| 163 |
+
do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
|
| 164 |
+
delta = tl.sum(o * do, axis=1)
|
| 165 |
+
tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
|
| 166 |
+
|
| 167 |
+
@triton.jit
|
| 168 |
+
def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr):
|
| 169 |
+
if EVEN_N & EVEN_M:
|
| 170 |
+
if EVEN_HEADDIM:
|
| 171 |
+
tl.store(dv_ptrs, dv)
|
| 172 |
+
tl.store(dk_ptrs, dk)
|
| 173 |
+
else:
|
| 174 |
+
tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
|
| 175 |
+
tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
|
| 176 |
+
elif EVEN_HEADDIM:
|
| 177 |
+
tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
|
| 178 |
+
tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
|
| 179 |
+
else:
|
| 180 |
+
tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
|
| 181 |
+
tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
|
| 182 |
+
|
| 183 |
+
@triton.jit
|
| 184 |
+
def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 185 |
+
begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M
|
| 186 |
+
offs_qm = begin_m + tl.arange(0, BLOCK_M)
|
| 187 |
+
offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
| 188 |
+
offs_m = tl.arange(0, BLOCK_M)
|
| 189 |
+
offs_d = tl.arange(0, BLOCK_HEADDIM)
|
| 190 |
+
q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
|
| 191 |
+
k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
|
| 192 |
+
v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
|
| 193 |
+
do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
|
| 194 |
+
dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
|
| 195 |
+
if BIAS_TYPE == 'vector':
|
| 196 |
+
b_ptrs = Bias + offs_n
|
| 197 |
+
elif BIAS_TYPE == 'matrix':
|
| 198 |
+
b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
|
| 199 |
+
dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
| 200 |
+
dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
|
| 201 |
+
if begin_m >= seqlen_q:
|
| 202 |
+
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
| 203 |
+
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
| 204 |
+
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
|
| 205 |
+
return
|
| 206 |
+
if EVEN_N & EVEN_M:
|
| 207 |
+
if EVEN_HEADDIM:
|
| 208 |
+
k = tl.load(k_ptrs)
|
| 209 |
+
v = tl.load(v_ptrs)
|
| 210 |
+
else:
|
| 211 |
+
k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 212 |
+
v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
|
| 213 |
+
elif EVEN_HEADDIM:
|
| 214 |
+
k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
| 215 |
+
v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
|
| 216 |
+
else:
|
| 217 |
+
k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 218 |
+
v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
|
| 219 |
+
num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
|
| 220 |
+
for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
|
| 221 |
+
start_m = tl.multiple_of(start_m, BLOCK_M)
|
| 222 |
+
offs_m_curr = start_m + offs_m
|
| 223 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 224 |
+
q = tl.load(q_ptrs)
|
| 225 |
+
elif EVEN_HEADDIM:
|
| 226 |
+
q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
|
| 227 |
+
else:
|
| 228 |
+
q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 229 |
+
qk = tl.dot(q, k, trans_b=True)
|
| 230 |
+
if not EVEN_N:
|
| 231 |
+
qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
|
| 232 |
+
if IS_CAUSAL:
|
| 233 |
+
qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf'))
|
| 234 |
+
if BIAS_TYPE != 'none':
|
| 235 |
+
tl.debug_barrier()
|
| 236 |
+
if BIAS_TYPE == 'vector':
|
| 237 |
+
if EVEN_N:
|
| 238 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
| 239 |
+
else:
|
| 240 |
+
bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
|
| 241 |
+
bias = bias[None, :]
|
| 242 |
+
elif BIAS_TYPE == 'matrix':
|
| 243 |
+
if EVEN_M & EVEN_N:
|
| 244 |
+
bias = tl.load(b_ptrs).to(tl.float32)
|
| 245 |
+
else:
|
| 246 |
+
bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32)
|
| 247 |
+
qk = qk * softmax_scale + bias
|
| 248 |
+
if not EVEN_M & EVEN_HEADDIM:
|
| 249 |
+
tl.debug_barrier()
|
| 250 |
+
lse_i = tl.load(LSE + offs_m_curr)
|
| 251 |
+
if BIAS_TYPE == 'none':
|
| 252 |
+
p = tl.exp(qk * softmax_scale - lse_i[:, None])
|
| 253 |
+
else:
|
| 254 |
+
p = tl.exp(qk - lse_i[:, None])
|
| 255 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 256 |
+
do = tl.load(do_ptrs)
|
| 257 |
+
else:
|
| 258 |
+
do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
|
| 259 |
+
dv += tl.dot(p.to(do.dtype), do, trans_a=True)
|
| 260 |
+
if not EVEN_M & EVEN_HEADDIM:
|
| 261 |
+
tl.debug_barrier()
|
| 262 |
+
dp = tl.dot(do, v, trans_b=True)
|
| 263 |
+
if not EVEN_HEADDIM:
|
| 264 |
+
tl.debug_barrier()
|
| 265 |
+
Di = tl.load(D + offs_m_curr)
|
| 266 |
+
ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
|
| 267 |
+
dk += tl.dot(ds, q, trans_a=True)
|
| 268 |
+
if not EVEN_M & EVEN_HEADDIM:
|
| 269 |
+
tl.debug_barrier()
|
| 270 |
+
if not ATOMIC_ADD:
|
| 271 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 272 |
+
dq = tl.load(dq_ptrs, eviction_policy='evict_last')
|
| 273 |
+
dq += tl.dot(ds, k)
|
| 274 |
+
tl.store(dq_ptrs, dq, eviction_policy='evict_last')
|
| 275 |
+
elif EVEN_HEADDIM:
|
| 276 |
+
dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last')
|
| 277 |
+
dq += tl.dot(ds, k)
|
| 278 |
+
tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last')
|
| 279 |
+
else:
|
| 280 |
+
dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last')
|
| 281 |
+
dq += tl.dot(ds, k)
|
| 282 |
+
tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last')
|
| 283 |
+
else:
|
| 284 |
+
dq = tl.dot(ds, k)
|
| 285 |
+
if EVEN_M & EVEN_HEADDIM:
|
| 286 |
+
tl.atomic_add(dq_ptrs, dq)
|
| 287 |
+
elif EVEN_HEADDIM:
|
| 288 |
+
tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
|
| 289 |
+
else:
|
| 290 |
+
tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
|
| 291 |
+
dq_ptrs += BLOCK_M * stride_dqm
|
| 292 |
+
q_ptrs += BLOCK_M * stride_qm
|
| 293 |
+
do_ptrs += BLOCK_M * stride_dom
|
| 294 |
+
if BIAS_TYPE == 'matrix':
|
| 295 |
+
b_ptrs += BLOCK_M * stride_bm
|
| 296 |
+
dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
|
| 297 |
+
dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
|
| 298 |
+
_bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
|
| 299 |
+
|
| 300 |
+
def init_to_zero(name):
|
| 301 |
+
return lambda nargs: nargs[name].zero_()
|
| 302 |
+
|
| 303 |
+
@triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'])
|
| 304 |
+
@triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
|
| 305 |
+
@triton.jit
|
| 306 |
+
def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
|
| 307 |
+
off_hb = tl.program_id(1)
|
| 308 |
+
off_b = off_hb // nheads
|
| 309 |
+
off_h = off_hb % nheads
|
| 310 |
+
Q += off_b * stride_qb + off_h * stride_qh
|
| 311 |
+
K += off_b * stride_kb + off_h * stride_kh
|
| 312 |
+
V += off_b * stride_vb + off_h * stride_vh
|
| 313 |
+
DO += off_b * stride_dob + off_h * stride_doh
|
| 314 |
+
DQ += off_b * stride_dqb + off_h * stride_dqh
|
| 315 |
+
DK += off_b * stride_dkb + off_h * stride_dkh
|
| 316 |
+
DV += off_b * stride_dvb + off_h * stride_dvh
|
| 317 |
+
if BIAS_TYPE != 'none':
|
| 318 |
+
Bias += off_b * stride_bb + off_h * stride_bh
|
| 319 |
+
D += off_hb * seqlen_q_rounded
|
| 320 |
+
LSE += off_hb * seqlen_q_rounded
|
| 321 |
+
if not SEQUENCE_PARALLEL:
|
| 322 |
+
num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
|
| 323 |
+
for start_n in range(0, num_block_n):
|
| 324 |
+
_bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
|
| 325 |
+
else:
|
| 326 |
+
start_n = tl.program_id(0)
|
| 327 |
+
_bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
|
| 328 |
+
|
| 329 |
+
def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
|
| 330 |
+
(batch, seqlen_q, nheads, d) = q.shape
|
| 331 |
+
(_, seqlen_k, _, _) = k.shape
|
| 332 |
+
assert k.shape == (batch, seqlen_k, nheads, d)
|
| 333 |
+
assert v.shape == (batch, seqlen_k, nheads, d)
|
| 334 |
+
assert d <= 128, 'FlashAttention only support head dimensions up to 128'
|
| 335 |
+
assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
|
| 336 |
+
assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
|
| 337 |
+
assert q.is_cuda and k.is_cuda and v.is_cuda
|
| 338 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
| 339 |
+
has_bias = bias is not None
|
| 340 |
+
bias_type = 'none'
|
| 341 |
+
if has_bias:
|
| 342 |
+
assert bias.dtype in [q.dtype, torch.float]
|
| 343 |
+
assert bias.is_cuda
|
| 344 |
+
assert bias.dim() == 4
|
| 345 |
+
if bias.stride(-1) != 1:
|
| 346 |
+
bias = bias.contiguous()
|
| 347 |
+
if bias.shape[2:] == (1, seqlen_k):
|
| 348 |
+
bias_type = 'vector'
|
| 349 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
| 350 |
+
bias_type = 'matrix'
|
| 351 |
+
else:
|
| 352 |
+
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
|
| 353 |
+
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
| 354 |
+
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
| 355 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
| 356 |
+
lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
|
| 357 |
+
tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
|
| 358 |
+
o = torch.empty_like(q)
|
| 359 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
| 360 |
+
BLOCK = 128
|
| 361 |
+
num_warps = 4 if d <= 64 else 8
|
| 362 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
| 363 |
+
_fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1)
|
| 364 |
+
return (o, lse, softmax_scale)
|
| 365 |
+
|
| 366 |
+
def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
|
| 367 |
+
if do.stride(-1) != 1:
|
| 368 |
+
do = do.contiguous()
|
| 369 |
+
(batch, seqlen_q, nheads, d) = q.shape
|
| 370 |
+
(_, seqlen_k, _, _) = k.shape
|
| 371 |
+
assert d <= 128
|
| 372 |
+
seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
|
| 373 |
+
assert lse.shape == (batch, nheads, seqlen_q_rounded)
|
| 374 |
+
assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
|
| 375 |
+
assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
|
| 376 |
+
softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
|
| 377 |
+
dq_accum = torch.empty_like(q, dtype=torch.float32)
|
| 378 |
+
delta = torch.empty_like(lse)
|
| 379 |
+
BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
|
| 380 |
+
grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
|
| 381 |
+
_bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM)
|
| 382 |
+
has_bias = bias is not None
|
| 383 |
+
bias_type = 'none'
|
| 384 |
+
if has_bias:
|
| 385 |
+
assert bias.dtype in [q.dtype, torch.float]
|
| 386 |
+
assert bias.is_cuda
|
| 387 |
+
assert bias.dim() == 4
|
| 388 |
+
assert bias.stride(-1) == 1
|
| 389 |
+
if bias.shape[2:] == (1, seqlen_k):
|
| 390 |
+
bias_type = 'vector'
|
| 391 |
+
elif bias.shape[2:] == (seqlen_q, seqlen_k):
|
| 392 |
+
bias_type = 'matrix'
|
| 393 |
+
else:
|
| 394 |
+
raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
|
| 395 |
+
bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
|
| 396 |
+
bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
|
| 397 |
+
grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
|
| 398 |
+
_bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM)
|
| 399 |
+
dq.copy_(dq_accum)
|
| 400 |
+
|
| 401 |
+
class FlashAttnQKVPackedFunc(torch.autograd.Function):
|
| 402 |
+
|
| 403 |
+
@staticmethod
|
| 404 |
+
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
|
| 405 |
+
"""
|
| 406 |
+
qkv: (batch, seqlen, 3, nheads, headdim)
|
| 407 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
|
| 408 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
|
| 409 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
|
| 410 |
+
"""
|
| 411 |
+
if qkv.stride(-1) != 1:
|
| 412 |
+
qkv = qkv.contiguous()
|
| 413 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 414 |
+
ctx.save_for_backward(qkv, o, lse, bias)
|
| 415 |
+
ctx.causal = causal
|
| 416 |
+
return o
|
| 417 |
+
|
| 418 |
+
@staticmethod
|
| 419 |
+
def backward(ctx, do):
|
| 420 |
+
(qkv, o, lse, bias) = ctx.saved_tensors
|
| 421 |
+
assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
|
| 422 |
+
with torch.inference_mode():
|
| 423 |
+
dqkv = torch.empty_like(qkv)
|
| 424 |
+
_flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 425 |
+
return (dqkv, None, None, None)
|
| 426 |
+
flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
|
| 427 |
+
|
| 428 |
+
class FlashAttnKVPackedFunc(torch.autograd.Function):
|
| 429 |
+
|
| 430 |
+
@staticmethod
|
| 431 |
+
def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
|
| 432 |
+
"""
|
| 433 |
+
q: (batch, seqlen_q, nheads, headdim)
|
| 434 |
+
kv: (batch, seqlen_k, 2, nheads, headdim)
|
| 435 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
| 436 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
| 437 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
| 438 |
+
"""
|
| 439 |
+
(q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
|
| 440 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 441 |
+
ctx.save_for_backward(q, kv, o, lse, bias)
|
| 442 |
+
ctx.causal = causal
|
| 443 |
+
return o
|
| 444 |
+
|
| 445 |
+
@staticmethod
|
| 446 |
+
def backward(ctx, do):
|
| 447 |
+
(q, kv, o, lse, bias) = ctx.saved_tensors
|
| 448 |
+
if len(ctx.needs_input_grad) >= 3:
|
| 449 |
+
assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
|
| 450 |
+
with torch.inference_mode():
|
| 451 |
+
dq = torch.empty_like(q)
|
| 452 |
+
dkv = torch.empty_like(kv)
|
| 453 |
+
_flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 454 |
+
return (dq, dkv, None, None, None)
|
| 455 |
+
flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
|
| 456 |
+
|
| 457 |
+
class FlashAttnFunc(torch.autograd.Function):
|
| 458 |
+
|
| 459 |
+
@staticmethod
|
| 460 |
+
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
|
| 461 |
+
"""
|
| 462 |
+
q: (batch_size, seqlen_q, nheads, headdim)
|
| 463 |
+
k, v: (batch_size, seqlen_k, nheads, headdim)
|
| 464 |
+
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
|
| 465 |
+
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
|
| 466 |
+
ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
|
| 467 |
+
"""
|
| 468 |
+
(q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
|
| 469 |
+
(o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
|
| 470 |
+
ctx.save_for_backward(q, k, v, o, lse, bias)
|
| 471 |
+
ctx.causal = causal
|
| 472 |
+
return o
|
| 473 |
+
|
| 474 |
+
@staticmethod
|
| 475 |
+
def backward(ctx, do):
|
| 476 |
+
(q, k, v, o, lse, bias) = ctx.saved_tensors
|
| 477 |
+
assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
|
| 478 |
+
with torch.inference_mode():
|
| 479 |
+
dq = torch.empty_like(q)
|
| 480 |
+
dk = torch.empty_like(k)
|
| 481 |
+
dv = torch.empty_like(v)
|
| 482 |
+
_flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
|
| 483 |
+
return (dq, dk, dv, None, None, None)
|
| 484 |
+
flash_attn_func = FlashAttnFunc.apply
|
instructany2pix/llm/model/language_model/mpt/hf_prefixlm_converter.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Converts Huggingface Causal LM to Prefix LM.
|
| 2 |
+
|
| 3 |
+
Conversion does lightweight surgery on a HuggingFace
|
| 4 |
+
Causal LM to convert it to a Prefix LM.
|
| 5 |
+
|
| 6 |
+
Prefix LMs accepts a `bidirectional_mask` input in `forward`
|
| 7 |
+
and treat the input prompt as the prefix in `generate`.
|
| 8 |
+
"""
|
| 9 |
+
import math
|
| 10 |
+
import warnings
|
| 11 |
+
from types import MethodType
|
| 12 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 13 |
+
import torch
|
| 14 |
+
from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
|
| 15 |
+
from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
|
| 16 |
+
from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
|
| 17 |
+
from transformers.models.bloom.modeling_bloom import logging
|
| 18 |
+
from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
|
| 19 |
+
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
|
| 20 |
+
from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
|
| 21 |
+
from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
|
| 22 |
+
from transformers.models.opt.modeling_opt import OPTForCausalLM
|
| 23 |
+
from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
|
| 24 |
+
from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
_SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
|
| 27 |
+
CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
|
| 28 |
+
|
| 29 |
+
def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
|
| 30 |
+
"""Converts a GPT-style Causal LM to a Prefix LM.
|
| 31 |
+
|
| 32 |
+
Supported HuggingFace model classes:
|
| 33 |
+
- `GPT2LMHeadModel`
|
| 34 |
+
- `GPTNeoForCausalLM`
|
| 35 |
+
- `GPTNeoXForCausalLM`
|
| 36 |
+
- `GPTJForCausalLM`
|
| 37 |
+
|
| 38 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
| 39 |
+
"""
|
| 40 |
+
if hasattr(model, '_prefix_lm_converted'):
|
| 41 |
+
return model
|
| 42 |
+
assert isinstance(model, _SUPPORTED_GPT_MODELS)
|
| 43 |
+
assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models'
|
| 44 |
+
|
| 45 |
+
def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
|
| 46 |
+
"""Helper that gets a list of the model's attention modules.
|
| 47 |
+
|
| 48 |
+
Each module has a `bias` buffer used for causal masking. The Prefix LM
|
| 49 |
+
conversion adds logic to dynamically manipulate these biases to support
|
| 50 |
+
Prefix LM attention masking.
|
| 51 |
+
"""
|
| 52 |
+
attn_modules = []
|
| 53 |
+
if isinstance(model, GPTNeoXForCausalLM):
|
| 54 |
+
blocks = model.gpt_neox.layers
|
| 55 |
+
else:
|
| 56 |
+
blocks = model.transformer.h
|
| 57 |
+
for block in blocks:
|
| 58 |
+
if isinstance(model, GPTNeoForCausalLM):
|
| 59 |
+
if block.attn.attention_type != 'global':
|
| 60 |
+
continue
|
| 61 |
+
attn_module = block.attn.attention
|
| 62 |
+
elif isinstance(model, GPTNeoXForCausalLM):
|
| 63 |
+
attn_module = block.attention
|
| 64 |
+
else:
|
| 65 |
+
attn_module = block.attn
|
| 66 |
+
attn_modules.append(attn_module)
|
| 67 |
+
return attn_modules
|
| 68 |
+
setattr(model, '_original_forward', getattr(model, 'forward'))
|
| 69 |
+
setattr(model, '_original_generate', getattr(model, 'generate'))
|
| 70 |
+
|
| 71 |
+
def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
|
| 72 |
+
"""Wraps original forward to enable PrefixLM attention."""
|
| 73 |
+
|
| 74 |
+
def call_og_forward():
|
| 75 |
+
if isinstance(self, GPTNeoXForCausalLM):
|
| 76 |
+
return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 77 |
+
else:
|
| 78 |
+
return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 79 |
+
if bidirectional_mask is None:
|
| 80 |
+
return call_og_forward()
|
| 81 |
+
assert isinstance(bidirectional_mask, torch.Tensor)
|
| 82 |
+
attn_modules = _get_attn_modules(model)
|
| 83 |
+
(b, s) = bidirectional_mask.shape
|
| 84 |
+
max_length = attn_modules[0].bias.shape[-1]
|
| 85 |
+
if s > max_length:
|
| 86 |
+
raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).')
|
| 87 |
+
assert s <= max_length
|
| 88 |
+
if s < max_length:
|
| 89 |
+
pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device)
|
| 90 |
+
bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
|
| 91 |
+
bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
|
| 92 |
+
for attn_module in attn_modules:
|
| 93 |
+
attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
|
| 94 |
+
output = call_og_forward()
|
| 95 |
+
for attn_module in attn_modules:
|
| 96 |
+
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
| 97 |
+
return output
|
| 98 |
+
|
| 99 |
+
def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
|
| 100 |
+
"""Wraps original generate to enable PrefixLM attention."""
|
| 101 |
+
attn_modules = _get_attn_modules(model)
|
| 102 |
+
for attn_module in attn_modules:
|
| 103 |
+
attn_module.bias.data[:] = 1
|
| 104 |
+
output = self._original_generate(*args, **kwargs)
|
| 105 |
+
for attn_module in attn_modules:
|
| 106 |
+
attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
|
| 107 |
+
return output
|
| 108 |
+
setattr(model, 'forward', MethodType(forward, model))
|
| 109 |
+
setattr(model, 'generate', MethodType(generate, model))
|
| 110 |
+
setattr(model, '_prefix_lm_converted', True)
|
| 111 |
+
return model
|
| 112 |
+
|
| 113 |
+
def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
|
| 114 |
+
"""Converts a BLOOM Causal LM to a Prefix LM.
|
| 115 |
+
|
| 116 |
+
Supported HuggingFace model classes:
|
| 117 |
+
- `BloomForCausalLM`
|
| 118 |
+
|
| 119 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
| 120 |
+
"""
|
| 121 |
+
if hasattr(model, '_prefix_lm_converted'):
|
| 122 |
+
return model
|
| 123 |
+
assert isinstance(model, BloomForCausalLM)
|
| 124 |
+
assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
|
| 125 |
+
|
| 126 |
+
def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
|
| 127 |
+
combined_attention_mask = None
|
| 128 |
+
device = attention_mask.device
|
| 129 |
+
(_, src_length) = input_shape
|
| 130 |
+
if src_length > 1:
|
| 131 |
+
combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
|
| 132 |
+
if bidirectional_mask is not None:
|
| 133 |
+
assert attention_mask.shape == bidirectional_mask.shape
|
| 134 |
+
expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
|
| 135 |
+
combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
|
| 136 |
+
expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
|
| 137 |
+
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
|
| 138 |
+
return combined_attention_mask
|
| 139 |
+
|
| 140 |
+
def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
|
| 141 |
+
num_heads = self.config.n_head
|
| 142 |
+
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
|
| 143 |
+
base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
|
| 144 |
+
powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
|
| 145 |
+
slopes = torch.pow(base, powers)
|
| 146 |
+
if closest_power_of_2 != num_heads:
|
| 147 |
+
extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
|
| 148 |
+
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
|
| 149 |
+
extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
|
| 150 |
+
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
|
| 151 |
+
qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
|
| 152 |
+
ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
|
| 153 |
+
diffs = qa - ka + key_length - query_length
|
| 154 |
+
diffs = -diffs.abs()
|
| 155 |
+
alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
|
| 156 |
+
alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
|
| 157 |
+
return alibi.to(dtype)
|
| 158 |
+
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
| 159 |
+
|
| 160 |
+
def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
|
| 161 |
+
if deprecated_arguments.pop('position_ids', False) is not False:
|
| 162 |
+
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
|
| 163 |
+
if len(deprecated_arguments) > 0:
|
| 164 |
+
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
|
| 165 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 166 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 167 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 168 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 169 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 170 |
+
raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
|
| 171 |
+
elif input_ids is not None:
|
| 172 |
+
(batch_size, seq_length) = input_ids.shape
|
| 173 |
+
elif inputs_embeds is not None:
|
| 174 |
+
(batch_size, seq_length, _) = inputs_embeds.shape
|
| 175 |
+
else:
|
| 176 |
+
raise ValueError('You have to specify either input_ids or inputs_embeds')
|
| 177 |
+
if past_key_values is None:
|
| 178 |
+
past_key_values = tuple([None] * len(self.h))
|
| 179 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
| 180 |
+
if inputs_embeds is None:
|
| 181 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 182 |
+
hidden_states = self.word_embeddings_layernorm(inputs_embeds)
|
| 183 |
+
presents = () if use_cache else None
|
| 184 |
+
all_self_attentions = () if output_attentions else None
|
| 185 |
+
all_hidden_states = () if output_hidden_states else None
|
| 186 |
+
seq_length_with_past = seq_length
|
| 187 |
+
past_key_values_length = 0
|
| 188 |
+
if past_key_values[0] is not None:
|
| 189 |
+
tmp = past_key_values[0][0]
|
| 190 |
+
past_key_values_length = tmp.shape[2]
|
| 191 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 192 |
+
if attention_mask is None:
|
| 193 |
+
attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
|
| 194 |
+
else:
|
| 195 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
| 196 |
+
alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
|
| 197 |
+
causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
|
| 198 |
+
for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
|
| 199 |
+
if output_hidden_states:
|
| 200 |
+
hst = (hidden_states,)
|
| 201 |
+
all_hidden_states = all_hidden_states + hst
|
| 202 |
+
if self.gradient_checkpointing and self.training:
|
| 203 |
+
if use_cache:
|
| 204 |
+
logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
|
| 205 |
+
use_cache = False
|
| 206 |
+
|
| 207 |
+
def create_custom_forward(module):
|
| 208 |
+
|
| 209 |
+
def custom_forward(*inputs):
|
| 210 |
+
return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
|
| 211 |
+
return custom_forward
|
| 212 |
+
outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
|
| 213 |
+
else:
|
| 214 |
+
outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
|
| 215 |
+
hidden_states = outputs[0]
|
| 216 |
+
if use_cache is True:
|
| 217 |
+
presents = presents + (outputs[1],)
|
| 218 |
+
if output_attentions:
|
| 219 |
+
oa = (outputs[2 if use_cache else 1],)
|
| 220 |
+
all_self_attentions = all_self_attentions + oa
|
| 221 |
+
hidden_states = self.ln_f(hidden_states)
|
| 222 |
+
if output_hidden_states:
|
| 223 |
+
hst = (hidden_states,)
|
| 224 |
+
all_hidden_states = all_hidden_states + hst
|
| 225 |
+
if not return_dict:
|
| 226 |
+
return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
|
| 227 |
+
return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
|
| 228 |
+
setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
|
| 229 |
+
setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
|
| 230 |
+
setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
|
| 231 |
+
KeyValueT = Tuple[torch.Tensor, torch.Tensor]
|
| 232 |
+
|
| 233 |
+
def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
| 234 |
+
"""Replacement forward method for BloomCausalLM."""
|
| 235 |
+
if deprecated_arguments.pop('position_ids', False) is not False:
|
| 236 |
+
warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
|
| 237 |
+
if len(deprecated_arguments) > 0:
|
| 238 |
+
raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
|
| 239 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 240 |
+
transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 241 |
+
hidden_states = transformer_outputs[0]
|
| 242 |
+
lm_logits = self.lm_head(hidden_states)
|
| 243 |
+
loss = None
|
| 244 |
+
if labels is not None:
|
| 245 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
| 246 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 247 |
+
(batch_size, seq_length, vocab_size) = shift_logits.shape
|
| 248 |
+
loss_fct = CrossEntropyLoss()
|
| 249 |
+
loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
|
| 250 |
+
if not return_dict:
|
| 251 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
| 252 |
+
return (loss,) + output if loss is not None else output
|
| 253 |
+
return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
|
| 254 |
+
|
| 255 |
+
def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
|
| 256 |
+
if past:
|
| 257 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
| 258 |
+
bidirectional_mask = None
|
| 259 |
+
if past[0][0].shape[0] == input_ids.shape[0]:
|
| 260 |
+
past = self._convert_to_bloom_cache(past)
|
| 261 |
+
else:
|
| 262 |
+
bidirectional_mask = torch.ones_like(input_ids)
|
| 263 |
+
return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
|
| 264 |
+
setattr(model, 'forward', MethodType(forward, model))
|
| 265 |
+
setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
|
| 266 |
+
setattr(model, '_prefix_lm_converted', True)
|
| 267 |
+
return model
|
| 268 |
+
|
| 269 |
+
def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
|
| 270 |
+
"""Converts an OPT Causal LM to a Prefix LM.
|
| 271 |
+
|
| 272 |
+
Supported HuggingFace model classes:
|
| 273 |
+
- `OPTForCausalLM`
|
| 274 |
+
|
| 275 |
+
See `convert_hf_causal_lm_to_prefix_lm` for more details.
|
| 276 |
+
"""
|
| 277 |
+
if hasattr(model, '_prefix_lm_converted'):
|
| 278 |
+
return model
|
| 279 |
+
assert isinstance(model, OPTForCausalLM)
|
| 280 |
+
assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
|
| 281 |
+
setattr(model, '_original_forward', getattr(model, 'forward'))
|
| 282 |
+
setattr(model, '_original_generate', getattr(model, 'generate'))
|
| 283 |
+
model.model.decoder.bidirectional_mask = None
|
| 284 |
+
|
| 285 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
| 286 |
+
combined_attention_mask = None
|
| 287 |
+
if input_shape[-1] > 1:
|
| 288 |
+
if self.bidirectional_mask == 'g':
|
| 289 |
+
(bsz, src_length) = input_shape
|
| 290 |
+
combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
|
| 291 |
+
else:
|
| 292 |
+
combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
|
| 293 |
+
if self.bidirectional_mask is not None:
|
| 294 |
+
assert attention_mask.shape == self.bidirectional_mask.shape
|
| 295 |
+
expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
|
| 296 |
+
combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
|
| 297 |
+
if attention_mask is not None:
|
| 298 |
+
expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
|
| 299 |
+
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
| 300 |
+
return combined_attention_mask
|
| 301 |
+
setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
|
| 302 |
+
|
| 303 |
+
def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
|
| 304 |
+
|
| 305 |
+
def call_og_forward():
|
| 306 |
+
return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
|
| 307 |
+
if bidirectional_mask is None:
|
| 308 |
+
return call_og_forward()
|
| 309 |
+
self.model.decoder.bidirectional_mask = bidirectional_mask
|
| 310 |
+
try:
|
| 311 |
+
outputs = call_og_forward()
|
| 312 |
+
except:
|
| 313 |
+
self.model.decoder.bidirectional_mask = None
|
| 314 |
+
raise
|
| 315 |
+
self.model.decoder.bidirectional_mask = None
|
| 316 |
+
return outputs
|
| 317 |
+
|
| 318 |
+
def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
|
| 319 |
+
"""Wraps original generate to enable PrefixLM-style attention."""
|
| 320 |
+
self.model.decoder.bidirectional_mask = 'g'
|
| 321 |
+
try:
|
| 322 |
+
output = self._original_generate(*args, **kwargs)
|
| 323 |
+
except:
|
| 324 |
+
self.model.decoder.bidirectional_mask = None
|
| 325 |
+
raise
|
| 326 |
+
self.model.decoder.bidirectional_mask = None
|
| 327 |
+
return output
|
| 328 |
+
setattr(model, 'forward', MethodType(forward, model))
|
| 329 |
+
setattr(model, 'generate', MethodType(generate, model))
|
| 330 |
+
setattr(model, '_prefix_lm_converted', True)
|
| 331 |
+
return model
|
| 332 |
+
_SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
|
| 333 |
+
CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
|
| 334 |
+
|
| 335 |
+
def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
|
| 336 |
+
"""Converts a HuggingFace Causal LM to a Prefix LM.
|
| 337 |
+
|
| 338 |
+
Supported HuggingFace model classes:
|
| 339 |
+
- `GPT2LMHeadModel`
|
| 340 |
+
- `GPTNeoForCausalLM`
|
| 341 |
+
- `GPTNeoXForCausalLM`
|
| 342 |
+
- `GPTJForCausalLM`
|
| 343 |
+
- `BloomForCausalLM`
|
| 344 |
+
- `OPTForCausalLM`
|
| 345 |
+
|
| 346 |
+
Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
|
| 347 |
+
`generate` method and/or select underlying methods depending on the model class.
|
| 348 |
+
|
| 349 |
+
These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
|
| 350 |
+
|
| 351 |
+
Notes on training:
|
| 352 |
+
To actually train the converted model as a Prefix LM, training batches will need to indicate
|
| 353 |
+
the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
|
| 354 |
+
|
| 355 |
+
**This is not a standard input and requires custom layers either within or after your dataloader.**
|
| 356 |
+
|
| 357 |
+
In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
|
| 358 |
+
such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
|
| 359 |
+
That is, the prefix portion of the sequence should not generate any loss. Loss should only be
|
| 360 |
+
generated by the target portion of the sequence.
|
| 361 |
+
|
| 362 |
+
Notes on `GPTNeoForCausalLM`:
|
| 363 |
+
To simplify the implementation, "global" and "local" attention layers are handled differently.
|
| 364 |
+
For "global" layers, we handle conversion as described above. For "local" layers, which use a
|
| 365 |
+
causal attention mask within a restricted local window, we do not alter the masking.
|
| 366 |
+
|
| 367 |
+
Notes on `forward` method conversion:
|
| 368 |
+
After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
|
| 369 |
+
which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
|
| 370 |
+
belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
|
| 371 |
+
0 indicates token positions belonging to the target.
|
| 372 |
+
|
| 373 |
+
The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
|
| 374 |
+
causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
|
| 375 |
+
the causal masks before returning the result.
|
| 376 |
+
|
| 377 |
+
Notes on `generate` method conversion:
|
| 378 |
+
After conversion, the `generate` method will have the same signature but will internally
|
| 379 |
+
convert all causal masks to be purely bidirectional, call the original `generate` method, and
|
| 380 |
+
(where appropriate) reset the causal masks before returning the result.
|
| 381 |
+
|
| 382 |
+
This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
|
| 383 |
+
"prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
|
| 384 |
+
each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
|
| 385 |
+
another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
|
| 386 |
+
previously-generated tokens (also as expected in a Prefix LM).
|
| 387 |
+
|
| 388 |
+
To preserve the API, the original methods are renamed to `_original_forward` and
|
| 389 |
+
`_original_generate`, and replaced with new `forward` and `generate` methods that wrap
|
| 390 |
+
them, respectively. Although implementation details vary by model class.
|
| 391 |
+
"""
|
| 392 |
+
if isinstance(model, _SUPPORTED_GPT_MODELS):
|
| 393 |
+
return _convert_gpt_causal_lm_to_prefix_lm(model)
|
| 394 |
+
elif isinstance(model, BloomForCausalLM):
|
| 395 |
+
return _convert_bloom_causal_lm_to_prefix_lm(model)
|
| 396 |
+
elif isinstance(model, OPTForCausalLM):
|
| 397 |
+
return _convert_opt_causal_lm_to_prefix_lm(model)
|
| 398 |
+
else:
|
| 399 |
+
raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
|
| 400 |
+
|
| 401 |
+
def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
|
| 402 |
+
"""Attempts to add bidirectional_mask to batch if missing.
|
| 403 |
+
|
| 404 |
+
Raises:
|
| 405 |
+
KeyError if bidirectional_mask is missing and can't be inferred
|
| 406 |
+
"""
|
| 407 |
+
if 'bidirectional_mask' not in batch:
|
| 408 |
+
if batch.get('mode', None) == 'icl_task':
|
| 409 |
+
batch['bidirectional_mask'] = batch['attention_mask'].clone()
|
| 410 |
+
for (i, continuation_indices) in enumerate(batch['continuation_indices']):
|
| 411 |
+
batch['bidirectional_mask'][i, continuation_indices] = 0
|
| 412 |
+
elif 'labels' in batch and 'attention_mask' in batch:
|
| 413 |
+
batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])
|
| 414 |
+
else:
|
| 415 |
+
raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')
|
instructany2pix/llm/model/language_model/mpt/meta_init_context.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import contextmanager
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
@contextmanager
|
| 6 |
+
def init_empty_weights(include_buffers: bool=False):
|
| 7 |
+
"""Meta initialization context manager.
|
| 8 |
+
|
| 9 |
+
A context manager under which models are initialized with all parameters
|
| 10 |
+
on the meta device, therefore creating an empty model. Useful when just
|
| 11 |
+
initializing the model would blow the available RAM.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
|
| 15 |
+
not to also put all buffers on the meta device while initializing.
|
| 16 |
+
|
| 17 |
+
Example:
|
| 18 |
+
```python
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
|
| 21 |
+
# Initialize a model with 100 billions parameters in no time and without using any RAM.
|
| 22 |
+
with init_empty_weights():
|
| 23 |
+
tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
<Tip warning={true}>
|
| 27 |
+
|
| 28 |
+
Any model created under this context manager has no weights. As such you can't do something like
|
| 29 |
+
`model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
|
| 30 |
+
|
| 31 |
+
</Tip>
|
| 32 |
+
"""
|
| 33 |
+
with init_on_device(torch.device('meta'), include_buffers=include_buffers) as f:
|
| 34 |
+
yield f
|
| 35 |
+
|
| 36 |
+
@contextmanager
|
| 37 |
+
def init_on_device(device: torch.device, include_buffers: bool=False):
|
| 38 |
+
"""Device initialization context manager.
|
| 39 |
+
|
| 40 |
+
A context manager under which models are initialized with all parameters
|
| 41 |
+
on the specified device.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
device (`torch.device`): Device to initialize all parameters on.
|
| 45 |
+
include_buffers (`bool`, *optional*, defaults to `False`): Whether or
|
| 46 |
+
not to also put all buffers on the meta device while initializing.
|
| 47 |
+
|
| 48 |
+
Example:
|
| 49 |
+
```python
|
| 50 |
+
import torch.nn as nn
|
| 51 |
+
|
| 52 |
+
with init_on_device(device=torch.device("cuda")):
|
| 53 |
+
tst = nn.Liner(100, 100) # on `cuda` device
|
| 54 |
+
```
|
| 55 |
+
"""
|
| 56 |
+
old_register_parameter = nn.Module.register_parameter
|
| 57 |
+
if include_buffers:
|
| 58 |
+
old_register_buffer = nn.Module.register_buffer
|
| 59 |
+
|
| 60 |
+
def register_empty_parameter(module, name, param):
|
| 61 |
+
old_register_parameter(module, name, param)
|
| 62 |
+
if param is not None:
|
| 63 |
+
param_cls = type(module._parameters[name])
|
| 64 |
+
kwargs = module._parameters[name].__dict__
|
| 65 |
+
module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
|
| 66 |
+
|
| 67 |
+
def register_empty_buffer(module, name, buffer):
|
| 68 |
+
old_register_buffer(module, name, buffer)
|
| 69 |
+
if buffer is not None:
|
| 70 |
+
module._buffers[name] = module._buffers[name].to(device)
|
| 71 |
+
if include_buffers:
|
| 72 |
+
tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
|
| 73 |
+
else:
|
| 74 |
+
tensor_constructors_to_patch = {}
|
| 75 |
+
|
| 76 |
+
def patch_tensor_constructor(fn):
|
| 77 |
+
|
| 78 |
+
def wrapper(*args, **kwargs):
|
| 79 |
+
kwargs['device'] = device
|
| 80 |
+
return fn(*args, **kwargs)
|
| 81 |
+
return wrapper
|
| 82 |
+
try:
|
| 83 |
+
nn.Module.register_parameter = register_empty_parameter
|
| 84 |
+
if include_buffers:
|
| 85 |
+
nn.Module.register_buffer = register_empty_buffer
|
| 86 |
+
for torch_function_name in tensor_constructors_to_patch.keys():
|
| 87 |
+
setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
|
| 88 |
+
yield
|
| 89 |
+
finally:
|
| 90 |
+
nn.Module.register_parameter = old_register_parameter
|
| 91 |
+
if include_buffers:
|
| 92 |
+
nn.Module.register_buffer = old_register_buffer
|
| 93 |
+
for (torch_function_name, old_torch_function) in tensor_constructors_to_patch.items():
|
| 94 |
+
setattr(torch, torch_function_name, old_torch_function)
|
instructany2pix/llm/model/language_model/mpt/modeling_mpt.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A simple, flexible implementation of a GPT model.
|
| 2 |
+
|
| 3 |
+
Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
|
| 4 |
+
"""
|
| 5 |
+
import math
|
| 6 |
+
import warnings
|
| 7 |
+
from typing import List, Optional, Tuple, Union
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
|
| 12 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 13 |
+
from .attention import attn_bias_shape, build_attn_bias
|
| 14 |
+
from .blocks import MPTBlock
|
| 15 |
+
from .custom_embedding import SharedEmbedding
|
| 16 |
+
from .norm import NORM_CLASS_REGISTRY
|
| 17 |
+
from .configuration_mpt import MPTConfig
|
| 18 |
+
from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
|
| 19 |
+
from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
|
| 20 |
+
from .meta_init_context import init_empty_weights
|
| 21 |
+
from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
|
| 22 |
+
try:
|
| 23 |
+
from .flash_attn_triton import flash_attn_func
|
| 24 |
+
except:
|
| 25 |
+
pass
|
| 26 |
+
Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
|
| 27 |
+
|
| 28 |
+
class MPTPreTrainedModel(PreTrainedModel):
|
| 29 |
+
config_class = MPTConfig
|
| 30 |
+
base_model_prefix = 'model'
|
| 31 |
+
_no_split_modules = ['MPTBlock']
|
| 32 |
+
|
| 33 |
+
class MPTModel(MPTPreTrainedModel):
|
| 34 |
+
|
| 35 |
+
def __init__(self, config: MPTConfig):
|
| 36 |
+
config._validate_config()
|
| 37 |
+
super().__init__(config)
|
| 38 |
+
self.attn_impl = config.attn_config['attn_impl']
|
| 39 |
+
self.prefix_lm = config.attn_config['prefix_lm']
|
| 40 |
+
self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
|
| 41 |
+
self.alibi = config.attn_config['alibi']
|
| 42 |
+
self.alibi_bias_max = config.attn_config['alibi_bias_max']
|
| 43 |
+
if config.init_device == 'mixed':
|
| 44 |
+
if dist.get_local_rank() == 0:
|
| 45 |
+
config.init_device = 'cpu'
|
| 46 |
+
else:
|
| 47 |
+
config.init_device = 'meta'
|
| 48 |
+
if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
|
| 49 |
+
norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
|
| 50 |
+
raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
|
| 51 |
+
norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
|
| 52 |
+
self.embedding_fraction = config.embedding_fraction
|
| 53 |
+
self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
|
| 54 |
+
if not self.alibi:
|
| 55 |
+
self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
|
| 56 |
+
self.emb_drop = nn.Dropout(config.emb_pdrop)
|
| 57 |
+
self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
|
| 58 |
+
self.norm_f = norm_class(config.d_model, device=config.init_device)
|
| 59 |
+
if config.init_device != 'meta':
|
| 60 |
+
print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.')
|
| 61 |
+
self.apply(self.param_init_fn)
|
| 62 |
+
self.is_causal = not self.prefix_lm
|
| 63 |
+
self._attn_bias_initialized = False
|
| 64 |
+
self.attn_bias = None
|
| 65 |
+
self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id)
|
| 66 |
+
if config.no_bias:
|
| 67 |
+
for module in self.modules():
|
| 68 |
+
if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
|
| 69 |
+
if config.verbose:
|
| 70 |
+
warnings.warn(f'Removing bias ({module.bias}) from {module}.')
|
| 71 |
+
module.register_parameter('bias', None)
|
| 72 |
+
if config.verbose and config.verbose > 2:
|
| 73 |
+
print(self)
|
| 74 |
+
if 'verbose' not in self.config.init_config:
|
| 75 |
+
self.config.init_config['verbose'] = self.config.verbose
|
| 76 |
+
if self.config.init_config['verbose'] > 1:
|
| 77 |
+
init_fn_name = self.config.init_config['name']
|
| 78 |
+
warnings.warn(f'Using {init_fn_name} initialization.')
|
| 79 |
+
self.gradient_checkpointing = False
|
| 80 |
+
|
| 81 |
+
def get_input_embeddings(self):
|
| 82 |
+
return self.wte
|
| 83 |
+
|
| 84 |
+
def set_input_embeddings(self, value):
|
| 85 |
+
self.wte = value
|
| 86 |
+
|
| 87 |
+
@torch.no_grad()
|
| 88 |
+
def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None):
|
| 89 |
+
if not self._attn_bias_initialized:
|
| 90 |
+
if self.attn_bias_shape:
|
| 91 |
+
self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
|
| 92 |
+
self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
|
| 93 |
+
self._attn_bias_initialized = True
|
| 94 |
+
if self.attn_impl == 'flash':
|
| 95 |
+
return (self.attn_bias, attention_mask)
|
| 96 |
+
if self.attn_bias is not None:
|
| 97 |
+
self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)
|
| 98 |
+
attn_bias = self.attn_bias
|
| 99 |
+
if self.prefix_lm:
|
| 100 |
+
assert isinstance(attn_bias, torch.Tensor)
|
| 101 |
+
assert isinstance(prefix_mask, torch.Tensor)
|
| 102 |
+
attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
|
| 103 |
+
if self.attn_uses_sequence_id and sequence_id is not None:
|
| 104 |
+
assert isinstance(attn_bias, torch.Tensor)
|
| 105 |
+
attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
|
| 106 |
+
if attention_mask is not None:
|
| 107 |
+
s_k = attention_mask.shape[-1]
|
| 108 |
+
if attn_bias is None:
|
| 109 |
+
attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)
|
| 110 |
+
else:
|
| 111 |
+
_s_k = max(0, attn_bias.size(-1) - s_k)
|
| 112 |
+
attn_bias = attn_bias[:, :, :, _s_k:]
|
| 113 |
+
if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:
|
| 114 |
+
raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
|
| 115 |
+
min_val = torch.finfo(attn_bias.dtype).min
|
| 116 |
+
attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
|
| 117 |
+
return (attn_bias, None)
|
| 118 |
+
|
| 119 |
+
def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):
|
| 120 |
+
(s_k, s_q) = attn_bias.shape[-2:]
|
| 121 |
+
if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
|
| 122 |
+
raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
|
| 123 |
+
seq_len = prefix_mask.shape[-1]
|
| 124 |
+
if seq_len > self.config.max_seq_len:
|
| 125 |
+
raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
|
| 126 |
+
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
| 127 |
+
causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len)
|
| 128 |
+
prefix = prefix_mask.view(-1, 1, 1, seq_len)
|
| 129 |
+
cannot_attend = ~torch.logical_or(causal, prefix.bool())
|
| 130 |
+
min_val = torch.finfo(attn_bias.dtype).min
|
| 131 |
+
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
| 132 |
+
return attn_bias
|
| 133 |
+
|
| 134 |
+
def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor):
|
| 135 |
+
seq_len = sequence_id.shape[-1]
|
| 136 |
+
if seq_len > self.config.max_seq_len:
|
| 137 |
+
raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
|
| 138 |
+
attn_bias = attn_bias[..., :seq_len, :seq_len]
|
| 139 |
+
cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
|
| 140 |
+
min_val = torch.finfo(attn_bias.dtype).min
|
| 141 |
+
attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
|
| 142 |
+
return attn_bias
|
| 143 |
+
|
| 144 |
+
def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None):
|
| 145 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 146 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 147 |
+
if attention_mask is not None:
|
| 148 |
+
attention_mask = attention_mask.bool()
|
| 149 |
+
if prefix_mask is not None:
|
| 150 |
+
prefix_mask = prefix_mask.bool()
|
| 151 |
+
if not return_dict:
|
| 152 |
+
raise NotImplementedError('return_dict False is not implemented yet for MPT')
|
| 153 |
+
if output_attentions:
|
| 154 |
+
if self.attn_impl != 'torch':
|
| 155 |
+
raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
|
| 156 |
+
if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training:
|
| 157 |
+
raise NotImplementedError('MPT does not support training with left padding.')
|
| 158 |
+
if self.prefix_lm and prefix_mask is None:
|
| 159 |
+
raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
|
| 160 |
+
if self.training:
|
| 161 |
+
if self.attn_uses_sequence_id and sequence_id is None:
|
| 162 |
+
raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
|
| 163 |
+
elif self.attn_uses_sequence_id is False and sequence_id is not None:
|
| 164 |
+
warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
|
| 165 |
+
if input_ids is not None:
|
| 166 |
+
S = input_ids.size(1)
|
| 167 |
+
assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
|
| 168 |
+
tok_emb = self.wte(input_ids)
|
| 169 |
+
else:
|
| 170 |
+
assert inputs_embeds is not None
|
| 171 |
+
assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.'
|
| 172 |
+
S = inputs_embeds.size(1)
|
| 173 |
+
tok_emb = inputs_embeds
|
| 174 |
+
if self.alibi:
|
| 175 |
+
x = tok_emb
|
| 176 |
+
else:
|
| 177 |
+
past_position = 0
|
| 178 |
+
if past_key_values is not None:
|
| 179 |
+
if len(past_key_values) != self.config.n_layers:
|
| 180 |
+
raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).')
|
| 181 |
+
past_position = past_key_values[0][0].size(1)
|
| 182 |
+
if self.attn_impl == 'torch':
|
| 183 |
+
past_position = past_key_values[0][0].size(3)
|
| 184 |
+
if S + past_position > self.config.max_seq_len:
|
| 185 |
+
raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
|
| 186 |
+
pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)
|
| 187 |
+
if attention_mask is not None:
|
| 188 |
+
pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
|
| 189 |
+
pos_emb = self.wpe(pos)
|
| 190 |
+
x = tok_emb + pos_emb
|
| 191 |
+
if self.embedding_fraction == 1:
|
| 192 |
+
x = self.emb_drop(x)
|
| 193 |
+
else:
|
| 194 |
+
x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)
|
| 195 |
+
assert isinstance(self.emb_drop, nn.Module)
|
| 196 |
+
x = self.emb_drop(x_shrunk)
|
| 197 |
+
(attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
|
| 198 |
+
if use_cache and past_key_values is None:
|
| 199 |
+
past_key_values = [() for _ in range(self.config.n_layers)]
|
| 200 |
+
all_hidden_states = () if output_hidden_states else None
|
| 201 |
+
all_self_attns = () if output_attentions else None
|
| 202 |
+
for (b_idx, block) in enumerate(self.blocks):
|
| 203 |
+
if output_hidden_states:
|
| 204 |
+
assert all_hidden_states is not None
|
| 205 |
+
all_hidden_states = all_hidden_states + (x,)
|
| 206 |
+
past_key_value = past_key_values[b_idx] if past_key_values is not None else None
|
| 207 |
+
if self.gradient_checkpointing and self.training:
|
| 208 |
+
(x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal)
|
| 209 |
+
else:
|
| 210 |
+
(x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)
|
| 211 |
+
if past_key_values is not None:
|
| 212 |
+
past_key_values[b_idx] = past_key_value
|
| 213 |
+
if output_attentions:
|
| 214 |
+
assert all_self_attns is not None
|
| 215 |
+
all_self_attns = all_self_attns + (attn_weights,)
|
| 216 |
+
x = self.norm_f(x)
|
| 217 |
+
if output_hidden_states:
|
| 218 |
+
assert all_hidden_states is not None
|
| 219 |
+
all_hidden_states = all_hidden_states + (x,)
|
| 220 |
+
return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns)
|
| 221 |
+
|
| 222 |
+
def param_init_fn(self, module):
|
| 223 |
+
init_fn_name = self.config.init_config['name']
|
| 224 |
+
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
| 225 |
+
|
| 226 |
+
def fsdp_wrap_fn(self, module):
|
| 227 |
+
return isinstance(module, MPTBlock)
|
| 228 |
+
|
| 229 |
+
def activation_checkpointing_fn(self, module):
|
| 230 |
+
return isinstance(module, MPTBlock)
|
| 231 |
+
|
| 232 |
+
class MPTForCausalLM(MPTPreTrainedModel):
|
| 233 |
+
|
| 234 |
+
def __init__(self, config: MPTConfig):
|
| 235 |
+
super().__init__(config)
|
| 236 |
+
if not config.tie_word_embeddings:
|
| 237 |
+
raise ValueError('MPTForCausalLM only supports tied word embeddings')
|
| 238 |
+
print(f'Instantiating an MPTForCausalLM model from {__file__}')
|
| 239 |
+
self.transformer = MPTModel(config)
|
| 240 |
+
for child in self.transformer.children():
|
| 241 |
+
if isinstance(child, torch.nn.ModuleList):
|
| 242 |
+
continue
|
| 243 |
+
if isinstance(child, torch.nn.Module):
|
| 244 |
+
child._fsdp_wrap = True
|
| 245 |
+
self.logit_scale = None
|
| 246 |
+
if config.logit_scale is not None:
|
| 247 |
+
logit_scale = config.logit_scale
|
| 248 |
+
if isinstance(logit_scale, str):
|
| 249 |
+
if logit_scale == 'inv_sqrt_d_model':
|
| 250 |
+
logit_scale = 1 / math.sqrt(config.d_model)
|
| 251 |
+
else:
|
| 252 |
+
raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
|
| 253 |
+
self.logit_scale = logit_scale
|
| 254 |
+
|
| 255 |
+
def get_input_embeddings(self):
|
| 256 |
+
return self.transformer.wte
|
| 257 |
+
|
| 258 |
+
def set_input_embeddings(self, value):
|
| 259 |
+
self.transformer.wte = value
|
| 260 |
+
|
| 261 |
+
def get_output_embeddings(self):
|
| 262 |
+
return self.transformer.wte
|
| 263 |
+
|
| 264 |
+
def set_output_embeddings(self, new_embeddings):
|
| 265 |
+
self.transformer.wte = new_embeddings
|
| 266 |
+
|
| 267 |
+
def set_decoder(self, decoder):
|
| 268 |
+
self.transformer = decoder
|
| 269 |
+
|
| 270 |
+
def get_decoder(self):
|
| 271 |
+
return self.transformer
|
| 272 |
+
|
| 273 |
+
def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None):
|
| 274 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 275 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 276 |
+
if inputs_embeds is not None:
|
| 277 |
+
raise NotImplementedError('inputs_embeds has to be None (for hf/peft support).')
|
| 278 |
+
outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
|
| 279 |
+
logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True)
|
| 280 |
+
if self.logit_scale is not None:
|
| 281 |
+
if self.logit_scale == 0:
|
| 282 |
+
warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
|
| 283 |
+
logits *= self.logit_scale
|
| 284 |
+
loss = None
|
| 285 |
+
if labels is not None:
|
| 286 |
+
labels = torch.roll(labels, shifts=-1)
|
| 287 |
+
labels[:, -1] = -100
|
| 288 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
|
| 289 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
| 290 |
+
|
| 291 |
+
def param_init_fn(self, module):
|
| 292 |
+
init_fn_name = self.config.init_config['name']
|
| 293 |
+
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
|
| 294 |
+
|
| 295 |
+
def fsdp_wrap_fn(self, module):
|
| 296 |
+
return isinstance(module, MPTBlock)
|
| 297 |
+
|
| 298 |
+
def activation_checkpointing_fn(self, module):
|
| 299 |
+
return isinstance(module, MPTBlock)
|
| 300 |
+
|
| 301 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
|
| 302 |
+
if inputs_embeds is not None:
|
| 303 |
+
raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
|
| 304 |
+
attention_mask = kwargs['attention_mask'].bool()
|
| 305 |
+
if attention_mask[:, -1].sum() != attention_mask.shape[0]:
|
| 306 |
+
raise NotImplementedError('MPT does not support generation with right padding.')
|
| 307 |
+
if self.transformer.attn_uses_sequence_id and self.training:
|
| 308 |
+
sequence_id = torch.zeros_like(input_ids[:1])
|
| 309 |
+
else:
|
| 310 |
+
sequence_id = None
|
| 311 |
+
if past_key_values is not None:
|
| 312 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
| 313 |
+
if self.transformer.prefix_lm:
|
| 314 |
+
prefix_mask = torch.ones_like(attention_mask)
|
| 315 |
+
if kwargs.get('use_cache') == False:
|
| 316 |
+
raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
|
| 317 |
+
else:
|
| 318 |
+
prefix_mask = None
|
| 319 |
+
return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)}
|
| 320 |
+
|
| 321 |
+
@staticmethod
|
| 322 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 323 |
+
"""Used by HuggingFace generate when using beam search with kv-caching.
|
| 324 |
+
|
| 325 |
+
See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
|
| 326 |
+
for an example in transformers.
|
| 327 |
+
"""
|
| 328 |
+
reordered_past = []
|
| 329 |
+
for layer_past in past_key_values:
|
| 330 |
+
reordered_past += [tuple((past_state.index_select(0, beam_idx) for past_state in layer_past))]
|
| 331 |
+
return reordered_past
|
instructany2pix/llm/model/language_model/mpt/norm.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
def _cast_if_autocast_enabled(tensor):
|
| 4 |
+
if torch.is_autocast_enabled():
|
| 5 |
+
if tensor.device.type == 'cuda':
|
| 6 |
+
dtype = torch.get_autocast_gpu_dtype()
|
| 7 |
+
elif tensor.device.type == 'cpu':
|
| 8 |
+
dtype = torch.get_autocast_cpu_dtype()
|
| 9 |
+
else:
|
| 10 |
+
raise NotImplementedError()
|
| 11 |
+
return tensor.to(dtype=dtype)
|
| 12 |
+
return tensor
|
| 13 |
+
|
| 14 |
+
class LPLayerNorm(torch.nn.LayerNorm):
|
| 15 |
+
|
| 16 |
+
def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None):
|
| 17 |
+
super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype)
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
module_device = x.device
|
| 21 |
+
downcast_x = _cast_if_autocast_enabled(x)
|
| 22 |
+
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
| 23 |
+
downcast_bias = _cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
|
| 24 |
+
with torch.autocast(enabled=False, device_type=module_device.type):
|
| 25 |
+
return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps)
|
| 26 |
+
|
| 27 |
+
def rms_norm(x, weight=None, eps=1e-05):
|
| 28 |
+
output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
|
| 29 |
+
if weight is not None:
|
| 30 |
+
return output * weight
|
| 31 |
+
return output
|
| 32 |
+
|
| 33 |
+
class RMSNorm(torch.nn.Module):
|
| 34 |
+
|
| 35 |
+
def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.eps = eps
|
| 38 |
+
if weight:
|
| 39 |
+
self.weight = torch.nn.Parameter(torch.ones(normalized_shape, dtype=dtype, device=device))
|
| 40 |
+
else:
|
| 41 |
+
self.register_parameter('weight', None)
|
| 42 |
+
|
| 43 |
+
def forward(self, x):
|
| 44 |
+
return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
|
| 45 |
+
|
| 46 |
+
class LPRMSNorm(RMSNorm):
|
| 47 |
+
|
| 48 |
+
def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
|
| 49 |
+
super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device)
|
| 50 |
+
|
| 51 |
+
def forward(self, x):
|
| 52 |
+
downcast_x = _cast_if_autocast_enabled(x)
|
| 53 |
+
downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
|
| 54 |
+
with torch.autocast(enabled=False, device_type=x.device.type):
|
| 55 |
+
return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
|
| 56 |
+
NORM_CLASS_REGISTRY = {'layernorm': torch.nn.LayerNorm, 'low_precision_layernorm': LPLayerNorm, 'rmsnorm': RMSNorm, 'low_precision_rmsnorm': LPRMSNorm}
|
instructany2pix/llm/model/language_model/mpt/param_init_fns.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import warnings
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
from functools import partial
|
| 5 |
+
from typing import Optional, Tuple, Union
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from .norm import NORM_CLASS_REGISTRY
|
| 9 |
+
|
| 10 |
+
def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
|
| 11 |
+
del kwargs
|
| 12 |
+
if verbose > 1:
|
| 13 |
+
warnings.warn(f"Initializing network using module's reset_parameters attribute")
|
| 14 |
+
if hasattr(module, 'reset_parameters'):
|
| 15 |
+
module.reset_parameters()
|
| 16 |
+
|
| 17 |
+
def fused_init_helper_(module: nn.Module, init_fn_):
|
| 18 |
+
_fused = getattr(module, '_fused', None)
|
| 19 |
+
if _fused is None:
|
| 20 |
+
raise RuntimeError(f'Internal logic error')
|
| 21 |
+
(dim, splits) = _fused
|
| 22 |
+
splits = (0, *splits, module.weight.size(dim))
|
| 23 |
+
for (s, e) in zip(splits[:-1], splits[1:]):
|
| 24 |
+
slice_indices = [slice(None)] * module.weight.ndim
|
| 25 |
+
slice_indices[dim] = slice(s, e)
|
| 26 |
+
init_fn_(module.weight[slice_indices])
|
| 27 |
+
|
| 28 |
+
def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 29 |
+
del kwargs
|
| 30 |
+
if verbose > 1:
|
| 31 |
+
warnings.warn(f'If model has bias parameters they are initialized to 0.')
|
| 32 |
+
init_div_is_residual = init_div_is_residual
|
| 33 |
+
if init_div_is_residual is False:
|
| 34 |
+
div_is_residual = 1.0
|
| 35 |
+
elif init_div_is_residual is True:
|
| 36 |
+
div_is_residual = math.sqrt(2 * n_layers)
|
| 37 |
+
elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
|
| 38 |
+
div_is_residual = init_div_is_residual
|
| 39 |
+
elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
|
| 40 |
+
div_is_residual = float(init_div_is_residual)
|
| 41 |
+
else:
|
| 42 |
+
div_is_residual = 1.0
|
| 43 |
+
raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
|
| 44 |
+
if init_div_is_residual is not False:
|
| 45 |
+
if verbose > 1:
|
| 46 |
+
warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
|
| 47 |
+
if isinstance(module, nn.Linear):
|
| 48 |
+
if hasattr(module, '_fused'):
|
| 49 |
+
fused_init_helper_(module, init_fn_)
|
| 50 |
+
else:
|
| 51 |
+
init_fn_(module.weight)
|
| 52 |
+
if module.bias is not None:
|
| 53 |
+
torch.nn.init.zeros_(module.bias)
|
| 54 |
+
if init_div_is_residual is not False and getattr(module, '_is_residual', False):
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
module.weight.div_(div_is_residual)
|
| 57 |
+
elif isinstance(module, nn.Embedding):
|
| 58 |
+
if emb_init_std is not None:
|
| 59 |
+
std = emb_init_std
|
| 60 |
+
if std == 0:
|
| 61 |
+
warnings.warn(f'Embedding layer initialized to 0.')
|
| 62 |
+
emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
|
| 63 |
+
if verbose > 1:
|
| 64 |
+
warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
|
| 65 |
+
elif emb_init_uniform_lim is not None:
|
| 66 |
+
lim = emb_init_uniform_lim
|
| 67 |
+
if isinstance(lim, Sequence):
|
| 68 |
+
if len(lim) > 2:
|
| 69 |
+
raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.')
|
| 70 |
+
if lim[0] == lim[1]:
|
| 71 |
+
warnings.warn(f'Embedding layer initialized to {lim[0]}.')
|
| 72 |
+
else:
|
| 73 |
+
if lim == 0:
|
| 74 |
+
warnings.warn(f'Embedding layer initialized to 0.')
|
| 75 |
+
lim = [-lim, lim]
|
| 76 |
+
(a, b) = lim
|
| 77 |
+
emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
|
| 78 |
+
if verbose > 1:
|
| 79 |
+
warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
|
| 80 |
+
else:
|
| 81 |
+
emb_init_fn_ = init_fn_
|
| 82 |
+
emb_init_fn_(module.weight)
|
| 83 |
+
elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
|
| 84 |
+
if verbose > 1:
|
| 85 |
+
warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
|
| 86 |
+
if hasattr(module, 'weight') and module.weight is not None:
|
| 87 |
+
torch.nn.init.ones_(module.weight)
|
| 88 |
+
if hasattr(module, 'bias') and module.bias is not None:
|
| 89 |
+
torch.nn.init.zeros_(module.bias)
|
| 90 |
+
elif isinstance(module, nn.MultiheadAttention):
|
| 91 |
+
if module._qkv_same_embed_dim:
|
| 92 |
+
assert module.in_proj_weight is not None
|
| 93 |
+
assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None)
|
| 94 |
+
assert d_model is not None
|
| 95 |
+
_d = d_model
|
| 96 |
+
splits = (0, _d, 2 * _d, 3 * _d)
|
| 97 |
+
for (s, e) in zip(splits[:-1], splits[1:]):
|
| 98 |
+
init_fn_(module.in_proj_weight[s:e])
|
| 99 |
+
else:
|
| 100 |
+
assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None)
|
| 101 |
+
assert module.in_proj_weight is None
|
| 102 |
+
init_fn_(module.q_proj_weight)
|
| 103 |
+
init_fn_(module.k_proj_weight)
|
| 104 |
+
init_fn_(module.v_proj_weight)
|
| 105 |
+
if module.in_proj_bias is not None:
|
| 106 |
+
torch.nn.init.zeros_(module.in_proj_bias)
|
| 107 |
+
if module.bias_k is not None:
|
| 108 |
+
torch.nn.init.zeros_(module.bias_k)
|
| 109 |
+
if module.bias_v is not None:
|
| 110 |
+
torch.nn.init.zeros_(module.bias_v)
|
| 111 |
+
init_fn_(module.out_proj.weight)
|
| 112 |
+
if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False):
|
| 113 |
+
with torch.no_grad():
|
| 114 |
+
module.out_proj.weight.div_(div_is_residual)
|
| 115 |
+
if module.out_proj.bias is not None:
|
| 116 |
+
torch.nn.init.zeros_(module.out_proj.bias)
|
| 117 |
+
else:
|
| 118 |
+
for _ in module.parameters(recurse=False):
|
| 119 |
+
raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
|
| 120 |
+
|
| 121 |
+
def _normal_init_(std, mean=0.0):
|
| 122 |
+
return partial(torch.nn.init.normal_, mean=mean, std=std)
|
| 123 |
+
|
| 124 |
+
def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 125 |
+
del kwargs
|
| 126 |
+
init_fn_ = _normal_init_(std=std)
|
| 127 |
+
if verbose > 1:
|
| 128 |
+
warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}')
|
| 129 |
+
generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 130 |
+
|
| 131 |
+
def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 132 |
+
del kwargs
|
| 133 |
+
if init_std is None:
|
| 134 |
+
raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
|
| 135 |
+
_normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 136 |
+
|
| 137 |
+
def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 138 |
+
del kwargs
|
| 139 |
+
std = math.sqrt(2 / (5 * d_model))
|
| 140 |
+
_normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 141 |
+
|
| 142 |
+
def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
|
| 143 |
+
"""From section 2.3.1 of GPT-NeoX-20B:
|
| 144 |
+
|
| 145 |
+
An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
|
| 146 |
+
see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151
|
| 147 |
+
and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
|
| 148 |
+
"""
|
| 149 |
+
del kwargs
|
| 150 |
+
residual_div = n_layers / math.sqrt(10)
|
| 151 |
+
if verbose > 1:
|
| 152 |
+
warnings.warn(f'setting init_div_is_residual to {residual_div}')
|
| 153 |
+
small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 154 |
+
|
| 155 |
+
def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
|
| 156 |
+
del kwargs
|
| 157 |
+
if verbose > 1:
|
| 158 |
+
warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
|
| 159 |
+
kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
| 160 |
+
generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 161 |
+
|
| 162 |
+
def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
|
| 163 |
+
del kwargs
|
| 164 |
+
if verbose > 1:
|
| 165 |
+
warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
|
| 166 |
+
kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
|
| 167 |
+
generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 168 |
+
|
| 169 |
+
def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
|
| 170 |
+
del kwargs
|
| 171 |
+
xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
|
| 172 |
+
if verbose > 1:
|
| 173 |
+
warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}')
|
| 174 |
+
generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 175 |
+
|
| 176 |
+
def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
|
| 177 |
+
xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
|
| 178 |
+
if verbose > 1:
|
| 179 |
+
warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}')
|
| 180 |
+
generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
|
| 181 |
+
MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_}
|
instructany2pix/llm/model/make_delta.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 6 |
+
from .utils import auto_upgrade
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def make_delta(base_model_path, target_model_path, delta_path, hub_repo_id):
|
| 10 |
+
print("Loading base model")
|
| 11 |
+
base = AutoModelForCausalLM.from_pretrained(
|
| 12 |
+
base_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 13 |
+
|
| 14 |
+
print("Loading target model")
|
| 15 |
+
auto_upgrade(target_model_path)
|
| 16 |
+
target = AutoModelForCausalLM.from_pretrained(target_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 17 |
+
|
| 18 |
+
print("Calculating delta")
|
| 19 |
+
for name, param in tqdm(target.state_dict().items(), desc="Calculating delta"):
|
| 20 |
+
if name not in base.state_dict():
|
| 21 |
+
assert name in ['model.mm_projector.weight', 'model.mm_projector.bias'], f'{name} not in base model'
|
| 22 |
+
continue
|
| 23 |
+
if param.data.shape == base.state_dict()[name].shape:
|
| 24 |
+
param.data -= base.state_dict()[name]
|
| 25 |
+
else:
|
| 26 |
+
assert name in ['model.embed_tokens.weight', 'lm_head.weight'], f'{name} dimension mismatch: {param.data.shape} vs {base.state_dict()[name].shape}'
|
| 27 |
+
bparam = base.state_dict()[name]
|
| 28 |
+
param.data[:bparam.shape[0], :bparam.shape[1]] -= bparam
|
| 29 |
+
|
| 30 |
+
print("Saving delta")
|
| 31 |
+
if hub_repo_id:
|
| 32 |
+
kwargs = {"push_to_hub": True, "repo_id": hub_repo_id}
|
| 33 |
+
else:
|
| 34 |
+
kwargs = {}
|
| 35 |
+
target.save_pretrained(delta_path, **kwargs)
|
| 36 |
+
target_tokenizer = AutoTokenizer.from_pretrained(target_model_path)
|
| 37 |
+
target_tokenizer.save_pretrained(delta_path, **kwargs)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
parser = argparse.ArgumentParser()
|
| 42 |
+
parser.add_argument("--base-model-path", type=str, required=True)
|
| 43 |
+
parser.add_argument("--target-model-path", type=str, required=True)
|
| 44 |
+
parser.add_argument("--delta-path", type=str, required=True)
|
| 45 |
+
parser.add_argument("--hub-repo-id", type=str, default=None)
|
| 46 |
+
args = parser.parse_args()
|
| 47 |
+
|
| 48 |
+
make_delta(args.base_model_path, args.target_model_path, args.delta_path, args.hub_repo_id)
|
instructany2pix/llm/model/multimodal_encoder/builder.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from .clip_encoder import CLIPVisionTower
|
| 3 |
+
from .image_bind_encoder import LanguageBindVisionTower
|
| 4 |
+
|
| 5 |
+
def build_vision_tower(vision_tower_cfg, **kwargs):
|
| 6 |
+
vision_tower = getattr(vision_tower_cfg, 'mm_vision_tower', getattr(vision_tower_cfg, 'vision_tower', None))
|
| 7 |
+
is_absolute_path_exists = os.path.exists(vision_tower)
|
| 8 |
+
if is_absolute_path_exists or vision_tower.startswith("openai") or vision_tower.startswith("laion"):
|
| 9 |
+
return CLIPVisionTower(vision_tower, args=vision_tower_cfg, **kwargs)
|
| 10 |
+
elif vision_tower == 'languagebind':
|
| 11 |
+
return LanguageBindVisionTower(vision_tower,args=vision_tower_cfg, **kwargs)
|
| 12 |
+
raise ValueError(f'Unknown vision tower: {vision_tower}')
|
instructany2pix/llm/model/multimodal_encoder/clip_encoder.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from transformers import CLIPVisionModelWithProjection, CLIPImageProcessor, CLIPVisionConfig
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CLIPVisionTower(nn.Module):
|
| 8 |
+
def __init__(self, vision_tower, args, delay_load=False):
|
| 9 |
+
super().__init__()
|
| 10 |
+
|
| 11 |
+
self.is_loaded = False
|
| 12 |
+
|
| 13 |
+
self.vision_tower_name = vision_tower
|
| 14 |
+
self.select_layer = args.mm_vision_select_layer
|
| 15 |
+
self.select_feature = getattr(args, 'mm_vision_select_feature', 'projection')
|
| 16 |
+
|
| 17 |
+
if not delay_load:
|
| 18 |
+
self.load_model()
|
| 19 |
+
else:
|
| 20 |
+
self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
| 21 |
+
|
| 22 |
+
def load_model(self):
|
| 23 |
+
self.image_processor = CLIPImageProcessor.from_pretrained(self.vision_tower_name)
|
| 24 |
+
self.vision_tower = CLIPVisionModelWithProjection.from_pretrained(self.vision_tower_name)
|
| 25 |
+
self.vision_tower.requires_grad_(False)
|
| 26 |
+
|
| 27 |
+
self.is_loaded = True
|
| 28 |
+
|
| 29 |
+
def feature_select(self, image_forward_outs):
|
| 30 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 31 |
+
if self.select_feature == 'patch':
|
| 32 |
+
image_features = image_features[:, 1:]
|
| 33 |
+
elif self.select_feature == 'cls_patch':
|
| 34 |
+
image_features = image_features
|
| 35 |
+
elif self.select_feature == 'projection':
|
| 36 |
+
image_features = image_forward_outs.image_embeds.unsqueeze(1)
|
| 37 |
+
else:
|
| 38 |
+
raise ValueError(f'Unexpected select feature: {self.select_feature}')
|
| 39 |
+
return image_features
|
| 40 |
+
|
| 41 |
+
@torch.no_grad()
|
| 42 |
+
def forward(self, images):
|
| 43 |
+
if type(images) is list:
|
| 44 |
+
image_features = []
|
| 45 |
+
for image in images:
|
| 46 |
+
image_forward_out = self.vision_tower(image.to(device=self.device, dtype=self.dtype).unsqueeze(0), output_hidden_states=True)
|
| 47 |
+
image_feature = self.feature_select(image_forward_out).to(image.dtype)
|
| 48 |
+
image_features.append(image_feature)
|
| 49 |
+
else:
|
| 50 |
+
return torch.zeros(images['image']['pixel_values'].shape[0],1,1024).to(images['image']['pixel_values'].dtype).to(device=self.device)
|
| 51 |
+
image_forward_outs = self.vision_tower(images['image']['pixel_values'].to(device=self.device), output_hidden_states=True)
|
| 52 |
+
image_features = self.feature_select(image_forward_outs).to(images['image']['pixel_values'].dtype)
|
| 53 |
+
|
| 54 |
+
return image_features
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def dummy_feature(self):
|
| 58 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def dtype(self):
|
| 62 |
+
return self.vision_tower.dtype
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def device(self):
|
| 66 |
+
return self.vision_tower.device
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def config(self):
|
| 70 |
+
if self.is_loaded:
|
| 71 |
+
return self.vision_tower.config
|
| 72 |
+
else:
|
| 73 |
+
return self.cfg_only
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def hidden_size(self):
|
| 77 |
+
return self.config.projection_dim if self.select_feature == 'projection' else self.config.hidden_size
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def num_patches(self):
|
| 81 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
instructany2pix/llm/model/multimodal_encoder/image_bind_encoder.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
from transformers import CLIPVisionModel, CLIPImageProcessor, CLIPVisionConfig
|
| 6 |
+
# from imagebind.models import imagebind_model
|
| 7 |
+
try:
|
| 8 |
+
from languagebind import LanguageBind, to_device, transform_dict, LanguageBindImageTokenizer
|
| 9 |
+
except:
|
| 10 |
+
pass
|
| 11 |
+
|
| 12 |
+
class LanguageBindProcesser:
|
| 13 |
+
|
| 14 |
+
def __init__(self,modality_transform) -> None:
|
| 15 |
+
self.modality_transform = modality_transform
|
| 16 |
+
self.crop_size = dict(height=224,width=224)
|
| 17 |
+
|
| 18 |
+
def __call__(self, inputs) -> Any:
|
| 19 |
+
outputs = {}
|
| 20 |
+
for modality,data in inputs.items():
|
| 21 |
+
outputs[modality] = self.modality_transform[modality](data)
|
| 22 |
+
return outputs
|
| 23 |
+
|
| 24 |
+
class LanguageBindVisionTower(nn.Module):
|
| 25 |
+
def __init__(self, vision_tower, args,clip_type=('image',),delay_load=False):
|
| 26 |
+
super().__init__()
|
| 27 |
+
# 'audio'
|
| 28 |
+
self.is_loaded = False
|
| 29 |
+
|
| 30 |
+
self.vision_tower_name = vision_tower
|
| 31 |
+
self.select_layer = args.mm_vision_select_layer
|
| 32 |
+
self.select_feature = getattr(args, 'mm_vision_select_feature', 'patch')
|
| 33 |
+
self.clip_type = clip_type
|
| 34 |
+
self.hidden_size = 768
|
| 35 |
+
if not delay_load:
|
| 36 |
+
self.load_model()
|
| 37 |
+
else:
|
| 38 |
+
pass
|
| 39 |
+
#self.cfg_only = CLIPVisionConfig.from_pretrained(self.vision_tower_name)
|
| 40 |
+
|
| 41 |
+
def load_model(self):
|
| 42 |
+
model = LanguageBind(clip_type=self.clip_type, cache_dir='src/LanguageBind/cache_dir')
|
| 43 |
+
self.modality_transform = {c: transform_dict[c](model.modality_config[c]) for c in self.clip_type}
|
| 44 |
+
self.image_processor = LanguageBindProcesser(self.modality_transform)
|
| 45 |
+
self.vision_tower = model
|
| 46 |
+
self.vision_tower.requires_grad_(False)
|
| 47 |
+
#self.hidden_size = 768
|
| 48 |
+
self.is_loaded = True
|
| 49 |
+
|
| 50 |
+
def feature_select(self, image_forward_outs):
|
| 51 |
+
image_features = image_forward_outs.hidden_states[self.select_layer]
|
| 52 |
+
if self.select_feature == 'patch':
|
| 53 |
+
image_features = image_features[:, 1:]
|
| 54 |
+
elif self.select_feature == 'cls_patch':
|
| 55 |
+
image_features = image_features
|
| 56 |
+
else:
|
| 57 |
+
raise ValueError(f'Unexpected select feature: {self.select_feature}')
|
| 58 |
+
return image_features
|
| 59 |
+
|
| 60 |
+
@torch.no_grad()
|
| 61 |
+
def forward(self, inputs):
|
| 62 |
+
embeddings = self.vision_tower({k:v for k,v in inputs.items() if k != 'info'})
|
| 63 |
+
embeddings = torch.stack(
|
| 64 |
+
[embeddings[info['modality']][info['idx']] for info in inputs['info']]
|
| 65 |
+
)
|
| 66 |
+
return embeddings
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def dummy_feature(self):
|
| 70 |
+
return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def dtype(self):
|
| 74 |
+
return self.vision_tower.dtype
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def device(self):
|
| 78 |
+
return self.vision_tower.device
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def config(self):
|
| 82 |
+
if self.is_loaded:
|
| 83 |
+
return self.vision_tower.config
|
| 84 |
+
else:
|
| 85 |
+
return self.cfg_only
|
| 86 |
+
|
| 87 |
+
# @property
|
| 88 |
+
# def hidden_size(self):
|
| 89 |
+
# return self.config.hidden_size
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def num_patches(self):
|
| 93 |
+
return (self.config.image_size // self.config.patch_size) ** 2
|
instructany2pix/llm/model/multimodal_projector/builder.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class IdentityMap(nn.Module):
|
| 7 |
+
def __init__(self):
|
| 8 |
+
super().__init__()
|
| 9 |
+
|
| 10 |
+
def forward(self, x, *args, **kwargs):
|
| 11 |
+
return x
|
| 12 |
+
|
| 13 |
+
@property
|
| 14 |
+
def config(self):
|
| 15 |
+
return {"mm_projector_type": 'identity'}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SimpleResBlock(nn.Module):
|
| 19 |
+
def __init__(self, channels):
|
| 20 |
+
super().__init__()
|
| 21 |
+
self.pre_norm = nn.LayerNorm(channels)
|
| 22 |
+
|
| 23 |
+
self.proj = nn.Sequential(
|
| 24 |
+
nn.Linear(channels, channels),
|
| 25 |
+
nn.GELU(),
|
| 26 |
+
nn.Linear(channels, channels)
|
| 27 |
+
)
|
| 28 |
+
def forward(self, x):
|
| 29 |
+
x = self.pre_norm(x)
|
| 30 |
+
return x + self.proj(x)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def build_vision_projector(config, delay_load=False,input_size=None, **kwargs):
|
| 34 |
+
projector_type = getattr(config, 'mm_projector_type', 'linear')
|
| 35 |
+
if not input_size:
|
| 36 |
+
input_size = config.mm_hidden_size
|
| 37 |
+
if projector_type == 'linear':
|
| 38 |
+
return nn.Linear(input_size, config.hidden_size)
|
| 39 |
+
|
| 40 |
+
mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
|
| 41 |
+
if mlp_gelu_match:
|
| 42 |
+
mlp_depth = int(mlp_gelu_match.group(1))
|
| 43 |
+
modules = [nn.Linear(input_size, config.hidden_size)]
|
| 44 |
+
for _ in range(1, mlp_depth):
|
| 45 |
+
modules.append(nn.GELU())
|
| 46 |
+
modules.append(nn.Linear(config.hidden_size, config.hidden_size))
|
| 47 |
+
return nn.Sequential(*modules)
|
| 48 |
+
|
| 49 |
+
if projector_type == 'identity':
|
| 50 |
+
return IdentityMap()
|
| 51 |
+
|
| 52 |
+
raise ValueError(f'Unknown projector type: {projector_type}')
|
| 53 |
+
|
| 54 |
+
def build_vision_predictor(config, output_size=None, **kwargs):
|
| 55 |
+
projector_type = getattr(config, 'mm_projector_type', 'linear')
|
| 56 |
+
if not output_size:
|
| 57 |
+
output_size = config.mm_hidden_size
|
| 58 |
+
if projector_type == 'linear':
|
| 59 |
+
return nn.Linear(config.hidden_size,output_size)
|
| 60 |
+
|
| 61 |
+
mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', projector_type)
|
| 62 |
+
if mlp_gelu_match:
|
| 63 |
+
mlp_depth = int(mlp_gelu_match.group(1))
|
| 64 |
+
modules = []
|
| 65 |
+
for _ in range(1, mlp_depth):
|
| 66 |
+
modules.append(nn.Linear(config.hidden_size, config.hidden_size))
|
| 67 |
+
modules.append(nn.GELU())
|
| 68 |
+
modules.append(nn.Linear(config.hidden_size,output_size))
|
| 69 |
+
return nn.Sequential(*modules)
|
| 70 |
+
|
| 71 |
+
if projector_type == 'identity':
|
| 72 |
+
return IdentityMap()
|
| 73 |
+
|
| 74 |
+
raise ValueError(f'Unknown projector type: {projector_type}')
|
| 75 |
+
|
instructany2pix/llm/model/utils.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def auto_upgrade(config):
|
| 5 |
+
pass
|
instructany2pix/llm/model/vae/audio_vqvae.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import pytorch_lightning as pl
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
sys.path.insert(0, '.') # nopep8
|
| 8 |
+
#from train import instantiate_from_config
|
| 9 |
+
|
| 10 |
+
from .modules.blocks_spec import Encoder, Decoder, Encoder1d, Decoder1d
|
| 11 |
+
from .modules.quantize_spec import VectorQuantizer, VectorQuantizer1d
|
| 12 |
+
# from .modules.quantize_spec import VectorQuantizer2 as VectorQuantizer
|
| 13 |
+
from .modules.util import instantiate_from_config
|
| 14 |
+
|
| 15 |
+
class VQModel(pl.LightningModule):
|
| 16 |
+
def __init__(self,
|
| 17 |
+
ddconfig,
|
| 18 |
+
lossconfig,
|
| 19 |
+
n_embed,
|
| 20 |
+
embed_dim,
|
| 21 |
+
ckpt_path=None,
|
| 22 |
+
ignore_keys=[],
|
| 23 |
+
image_key="image",
|
| 24 |
+
colorize_nlabels=None,
|
| 25 |
+
monitor=None
|
| 26 |
+
):
|
| 27 |
+
super().__init__()
|
| 28 |
+
self.image_key = image_key
|
| 29 |
+
# we need this one for compatibility in train.ImageLogger.log_img if statement
|
| 30 |
+
self.first_stage_key = image_key
|
| 31 |
+
self.encoder = Encoder(**ddconfig)
|
| 32 |
+
self.decoder = Decoder(**ddconfig)
|
| 33 |
+
self.loss = instantiate_from_config(lossconfig)
|
| 34 |
+
self.n_embed = n_embed
|
| 35 |
+
self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25)
|
| 36 |
+
self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
|
| 37 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
| 38 |
+
if ckpt_path is not None:
|
| 39 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
| 40 |
+
if colorize_nlabels is not None:
|
| 41 |
+
assert type(colorize_nlabels)==int
|
| 42 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
| 43 |
+
if monitor is not None:
|
| 44 |
+
self.monitor = monitor
|
| 45 |
+
self.used_codes = []
|
| 46 |
+
self.counts = [0 for _ in range(self.quantize.n_e)]
|
| 47 |
+
|
| 48 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
| 49 |
+
sd = torch.load(path, map_location="cpu")["state_dict"]
|
| 50 |
+
keys = list(sd.keys())
|
| 51 |
+
for k in keys:
|
| 52 |
+
for ik in ignore_keys:
|
| 53 |
+
if k.startswith(ik):
|
| 54 |
+
print("Deleting key {} from state_dict.".format(k))
|
| 55 |
+
del sd[k]
|
| 56 |
+
self.load_state_dict(sd, strict=False)
|
| 57 |
+
print(f"Restored from {path}")
|
| 58 |
+
|
| 59 |
+
def encode(self, x):
|
| 60 |
+
h = self.encoder(x) # 2d: (B, 256, 16, 16) <- (B, 3, 256, 256)
|
| 61 |
+
h = self.quant_conv(h) # 2d: (B, 256, 16, 16)
|
| 62 |
+
quant, emb_loss, info = self.quantize(h) # (B, 256, 16, 16), (), ((), (768, 1024), (768, 1))
|
| 63 |
+
if not self.training:
|
| 64 |
+
self.counts = [info[2].squeeze().tolist().count(i) + self.counts[i] for i in range(self.quantize.n_e)]
|
| 65 |
+
return quant, emb_loss, info
|
| 66 |
+
|
| 67 |
+
def decode(self, quant):
|
| 68 |
+
quant = self.post_quant_conv(quant)
|
| 69 |
+
dec = self.decoder(quant)
|
| 70 |
+
return dec
|
| 71 |
+
|
| 72 |
+
def decode_code(self, code_b):
|
| 73 |
+
quant_b = self.quantize.embed_code(code_b)
|
| 74 |
+
dec = self.decode(quant_b)
|
| 75 |
+
return dec
|
| 76 |
+
|
| 77 |
+
def forward(self, input):
|
| 78 |
+
quant, diff, _ = self.encode(input)
|
| 79 |
+
dec = self.decode(quant)
|
| 80 |
+
return dec, diff
|
| 81 |
+
|
| 82 |
+
def get_input(self, batch, k):
|
| 83 |
+
x = batch[k]
|
| 84 |
+
if len(x.shape) == 3:
|
| 85 |
+
x = x[..., None]
|
| 86 |
+
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
|
| 87 |
+
return x.float()
|
| 88 |
+
|
| 89 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
| 90 |
+
x = self.get_input(batch, self.image_key)
|
| 91 |
+
xrec, qloss = self(x)
|
| 92 |
+
|
| 93 |
+
if optimizer_idx == 0:
|
| 94 |
+
# autoencode
|
| 95 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
| 96 |
+
last_layer=self.get_last_layer(), split="train")
|
| 97 |
+
|
| 98 |
+
self.log("train/aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
| 99 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
| 100 |
+
return aeloss
|
| 101 |
+
|
| 102 |
+
if optimizer_idx == 1:
|
| 103 |
+
# discriminator
|
| 104 |
+
discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
| 105 |
+
last_layer=self.get_last_layer(), split="train")
|
| 106 |
+
self.log("train/disc_loss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
| 107 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
| 108 |
+
return discloss
|
| 109 |
+
|
| 110 |
+
def validation_step(self, batch, batch_idx):
|
| 111 |
+
if batch_idx == 0 and self.global_step != 0 and sum(self.counts) > 0:
|
| 112 |
+
print(f'Previous Epoch counts: {self.counts}')
|
| 113 |
+
zero_hit_codes = len([1 for count in self.counts if count == 0])
|
| 114 |
+
used_codes = []
|
| 115 |
+
for c, count in enumerate(self.counts):
|
| 116 |
+
used_codes.extend([c] * count)
|
| 117 |
+
self.logger.experiment.add_histogram('val/code_hits', torch.tensor(used_codes), self.global_step)
|
| 118 |
+
self.logger.experiment.add_scalar('val/zero_hit_codes', zero_hit_codes, self.global_step)
|
| 119 |
+
self.counts = [0 for _ in range(self.quantize.n_e)]
|
| 120 |
+
x = self.get_input(batch, self.image_key)
|
| 121 |
+
xrec, qloss = self(x)
|
| 122 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0, self.global_step,
|
| 123 |
+
last_layer=self.get_last_layer(), split="val")
|
| 124 |
+
|
| 125 |
+
discloss, log_dict_disc = self.loss(qloss, x, xrec, 1, self.global_step,
|
| 126 |
+
last_layer=self.get_last_layer(), split="val")
|
| 127 |
+
rec_loss = log_dict_ae['val/rec_loss']
|
| 128 |
+
self.log('val/rec_loss', rec_loss, prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
|
| 129 |
+
self.log('val/aeloss', aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
|
| 130 |
+
self.log_dict(log_dict_ae)
|
| 131 |
+
self.log_dict(log_dict_disc)
|
| 132 |
+
return self.log_dict
|
| 133 |
+
|
| 134 |
+
def configure_optimizers(self):
|
| 135 |
+
lr = self.learning_rate
|
| 136 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters()) +
|
| 137 |
+
list(self.decoder.parameters()) +
|
| 138 |
+
list(self.quantize.parameters()) +
|
| 139 |
+
list(self.quant_conv.parameters()) +
|
| 140 |
+
list(self.post_quant_conv.parameters()),
|
| 141 |
+
lr=lr, betas=(0.5, 0.9))
|
| 142 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
| 143 |
+
lr=lr, betas=(0.5, 0.9))
|
| 144 |
+
return [opt_ae, opt_disc], []
|
| 145 |
+
|
| 146 |
+
def get_last_layer(self):
|
| 147 |
+
return self.decoder.conv_out.weight
|
| 148 |
+
|
| 149 |
+
def log_images(self, batch, **kwargs):
|
| 150 |
+
log = dict()
|
| 151 |
+
x = self.get_input(batch, self.image_key)
|
| 152 |
+
x = x.to(self.device)
|
| 153 |
+
xrec, _ = self(x)
|
| 154 |
+
if x.shape[1] > 3:
|
| 155 |
+
# colorize with random projection
|
| 156 |
+
assert xrec.shape[1] > 3
|
| 157 |
+
x = self.to_rgb(x)
|
| 158 |
+
xrec = self.to_rgb(xrec)
|
| 159 |
+
log["inputs"] = x
|
| 160 |
+
log["reconstructions"] = xrec
|
| 161 |
+
return log
|
| 162 |
+
|
| 163 |
+
def to_rgb(self, x):
|
| 164 |
+
assert self.image_key == "segmentation"
|
| 165 |
+
if not hasattr(self, "colorize"):
|
| 166 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
| 167 |
+
x = F.conv2d(x, weight=self.colorize)
|
| 168 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
| 169 |
+
return x
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class VQModel1d(VQModel):
|
| 173 |
+
def __init__(self, ddconfig, lossconfig, n_embed, embed_dim, ckpt_path=None, ignore_keys=[],
|
| 174 |
+
image_key='feature', colorize_nlabels=None, monitor=None):
|
| 175 |
+
# ckpt_path is none to super because otherwise will try to load 1D checkpoint into 2D model
|
| 176 |
+
super().__init__(ddconfig, lossconfig, n_embed, embed_dim)
|
| 177 |
+
self.image_key = image_key
|
| 178 |
+
# we need this one for compatibility in train.ImageLogger.log_img if statement
|
| 179 |
+
self.first_stage_key = image_key
|
| 180 |
+
self.encoder = Encoder1d(**ddconfig)
|
| 181 |
+
self.decoder = Decoder1d(**ddconfig)
|
| 182 |
+
self.loss = instantiate_from_config(lossconfig)
|
| 183 |
+
self.quantize = VectorQuantizer1d(n_embed, embed_dim, beta=0.25)
|
| 184 |
+
self.quant_conv = torch.nn.Conv1d(ddconfig['z_channels'], embed_dim, 1)
|
| 185 |
+
self.post_quant_conv = torch.nn.Conv1d(embed_dim, ddconfig['z_channels'], 1)
|
| 186 |
+
if ckpt_path is not None:
|
| 187 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
| 188 |
+
if colorize_nlabels is not None:
|
| 189 |
+
assert type(colorize_nlabels)==int
|
| 190 |
+
self.register_buffer('colorize', torch.randn(3, colorize_nlabels, 1, 1))
|
| 191 |
+
if monitor is not None:
|
| 192 |
+
self.monitor = monitor
|
| 193 |
+
|
| 194 |
+
def get_input(self, batch, k):
|
| 195 |
+
x = batch[k]
|
| 196 |
+
if self.image_key == 'feature':
|
| 197 |
+
x = x.permute(0, 2, 1)
|
| 198 |
+
elif self.image_key == 'image':
|
| 199 |
+
x = x.unsqueeze(1)
|
| 200 |
+
x = x.to(memory_format=torch.contiguous_format)
|
| 201 |
+
return x.float()
|
| 202 |
+
|
| 203 |
+
def forward(self, input):
|
| 204 |
+
if self.image_key == 'image':
|
| 205 |
+
input = input.squeeze(1)
|
| 206 |
+
quant, diff, _ = self.encode(input)
|
| 207 |
+
dec = self.decode(quant)
|
| 208 |
+
if self.image_key == 'image':
|
| 209 |
+
dec = dec.unsqueeze(1)
|
| 210 |
+
return dec, diff
|
| 211 |
+
|
| 212 |
+
def log_images(self, batch, **kwargs):
|
| 213 |
+
if self.image_key == 'image':
|
| 214 |
+
log = dict()
|
| 215 |
+
x = self.get_input(batch, self.image_key)
|
| 216 |
+
x = x.to(self.device)
|
| 217 |
+
xrec, _ = self(x)
|
| 218 |
+
if x.shape[1] > 3:
|
| 219 |
+
# colorize with random projection
|
| 220 |
+
assert xrec.shape[1] > 3
|
| 221 |
+
x = self.to_rgb(x)
|
| 222 |
+
xrec = self.to_rgb(xrec)
|
| 223 |
+
log['inputs'] = x
|
| 224 |
+
log['reconstructions'] = xrec
|
| 225 |
+
return log
|
| 226 |
+
else:
|
| 227 |
+
raise NotImplementedError('1d input should be treated differently')
|
| 228 |
+
|
| 229 |
+
def to_rgb(self, batch, **kwargs):
|
| 230 |
+
raise NotImplementedError('1d input should be treated differently')
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class VQSegmentationModel(VQModel):
|
| 234 |
+
def __init__(self, n_labels, *args, **kwargs):
|
| 235 |
+
super().__init__(*args, **kwargs)
|
| 236 |
+
self.register_buffer("colorize", torch.randn(3, n_labels, 1, 1))
|
| 237 |
+
|
| 238 |
+
def configure_optimizers(self):
|
| 239 |
+
lr = self.learning_rate
|
| 240 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
| 241 |
+
list(self.decoder.parameters())+
|
| 242 |
+
list(self.quantize.parameters())+
|
| 243 |
+
list(self.quant_conv.parameters())+
|
| 244 |
+
list(self.post_quant_conv.parameters()),
|
| 245 |
+
lr=lr, betas=(0.5, 0.9))
|
| 246 |
+
return opt_ae
|
| 247 |
+
|
| 248 |
+
def training_step(self, batch, batch_idx):
|
| 249 |
+
x = self.get_input(batch, self.image_key)
|
| 250 |
+
xrec, qloss = self(x)
|
| 251 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, split="train")
|
| 252 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
| 253 |
+
return aeloss
|
| 254 |
+
|
| 255 |
+
def validation_step(self, batch, batch_idx):
|
| 256 |
+
x = self.get_input(batch, self.image_key)
|
| 257 |
+
xrec, qloss = self(x)
|
| 258 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, split="val")
|
| 259 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
| 260 |
+
total_loss = log_dict_ae["val/total_loss"]
|
| 261 |
+
self.log("val/total_loss", total_loss,
|
| 262 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=True, sync_dist=True)
|
| 263 |
+
return aeloss
|
| 264 |
+
|
| 265 |
+
@torch.no_grad()
|
| 266 |
+
def log_images(self, batch, **kwargs):
|
| 267 |
+
log = dict()
|
| 268 |
+
x = self.get_input(batch, self.image_key)
|
| 269 |
+
x = x.to(self.device)
|
| 270 |
+
xrec, _ = self(x)
|
| 271 |
+
if x.shape[1] > 3:
|
| 272 |
+
# colorize with random projection
|
| 273 |
+
assert xrec.shape[1] > 3
|
| 274 |
+
# convert logits to indices
|
| 275 |
+
xrec = torch.argmax(xrec, dim=1, keepdim=True)
|
| 276 |
+
xrec = F.one_hot(xrec, num_classes=x.shape[1])
|
| 277 |
+
xrec = xrec.squeeze(1).permute(0, 3, 1, 2).float()
|
| 278 |
+
x = self.to_rgb(x)
|
| 279 |
+
xrec = self.to_rgb(xrec)
|
| 280 |
+
log["inputs"] = x
|
| 281 |
+
log["reconstructions"] = xrec
|
| 282 |
+
return log
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class VQNoDiscModel(VQModel):
|
| 286 |
+
def __init__(self,
|
| 287 |
+
ddconfig,
|
| 288 |
+
lossconfig,
|
| 289 |
+
n_embed,
|
| 290 |
+
embed_dim,
|
| 291 |
+
ckpt_path=None,
|
| 292 |
+
ignore_keys=[],
|
| 293 |
+
image_key="image",
|
| 294 |
+
colorize_nlabels=None
|
| 295 |
+
):
|
| 296 |
+
super().__init__(ddconfig=ddconfig, lossconfig=lossconfig, n_embed=n_embed, embed_dim=embed_dim,
|
| 297 |
+
ckpt_path=ckpt_path, ignore_keys=ignore_keys, image_key=image_key,
|
| 298 |
+
colorize_nlabels=colorize_nlabels)
|
| 299 |
+
|
| 300 |
+
def training_step(self, batch, batch_idx):
|
| 301 |
+
x = self.get_input(batch, self.image_key)
|
| 302 |
+
xrec, qloss = self(x)
|
| 303 |
+
# autoencode
|
| 304 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, self.global_step, split="train")
|
| 305 |
+
output = pl.TrainResult(minimize=aeloss)
|
| 306 |
+
output.log("train/aeloss", aeloss,
|
| 307 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
| 308 |
+
output.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
| 309 |
+
return output
|
| 310 |
+
|
| 311 |
+
def validation_step(self, batch, batch_idx):
|
| 312 |
+
x = self.get_input(batch, self.image_key)
|
| 313 |
+
xrec, qloss = self(x)
|
| 314 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, self.global_step, split="val")
|
| 315 |
+
rec_loss = log_dict_ae["val/rec_loss"]
|
| 316 |
+
output = pl.EvalResult(checkpoint_on=rec_loss)
|
| 317 |
+
output.log("val/rec_loss", rec_loss,
|
| 318 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
| 319 |
+
output.log("val/aeloss", aeloss,
|
| 320 |
+
prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
| 321 |
+
output.log_dict(log_dict_ae)
|
| 322 |
+
|
| 323 |
+
return output
|
| 324 |
+
|
| 325 |
+
def configure_optimizers(self):
|
| 326 |
+
optimizer = torch.optim.Adam(list(self.encoder.parameters()) +
|
| 327 |
+
list(self.decoder.parameters()) +
|
| 328 |
+
list(self.quantize.parameters()) +
|
| 329 |
+
list(self.quant_conv.parameters()) +
|
| 330 |
+
list(self.post_quant_conv.parameters()),
|
| 331 |
+
lr=self.learning_rate, betas=(0.5, 0.9))
|
| 332 |
+
return optimizer
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class VQAudioModelInterfaceForLLM(VQModel):
|
| 336 |
+
def __init__(self, embed_dim, *args, **kwargs):
|
| 337 |
+
super().__init__(embed_dim=embed_dim, *args, **kwargs)
|
| 338 |
+
self.embed_dim = embed_dim
|
| 339 |
+
|
| 340 |
+
def encode_seq(self,x):
|
| 341 |
+
quant, diff, (_,_,ind) = self.encode(x)
|
| 342 |
+
n,c,h,w = quant.shape
|
| 343 |
+
return quant,ind,(n,c,h,w)
|
| 344 |
+
|
| 345 |
+
def decode_seq(self,ind,target_shape):
|
| 346 |
+
n,c,h,w = target_shape
|
| 347 |
+
min_encodings = torch.zeros(ind.shape[0], self.quantize.n_e)
|
| 348 |
+
min_encodings.scatter_(1, ind, 1)
|
| 349 |
+
|
| 350 |
+
# dtype min encodings: torch.float32
|
| 351 |
+
# min_encodings shape: torch.Size([2048, 512])
|
| 352 |
+
# min_encoding_indices.shape: torch.Size([2048, 1])
|
| 353 |
+
|
| 354 |
+
# get quantized latent vectors
|
| 355 |
+
z_q = torch.matmul(min_encodings, self.quantize.embedding.weight).view(n,h,w,c).permute(0,3,1,2)
|
| 356 |
+
y = self.decode(z_q)
|
| 357 |
+
return y
|
| 358 |
+
|
| 359 |
+
from .modules.util import get_duration,calculate_codebook_bitrate,get_audio_file_bitrate
|
| 360 |
+
from .modules.extract_spec import extract_melspectrogram
|
| 361 |
+
from .modules.vocoder import load_vocoder
|
| 362 |
+
class AudioVAEProcesser:
|
| 363 |
+
|
| 364 |
+
def __init__(self,sample_rate=22050) -> None:
|
| 365 |
+
|
| 366 |
+
self.model_sr = sample_rate
|
| 367 |
+
|
| 368 |
+
def __call__(self, audio) -> Any:
|
| 369 |
+
input_wav = audio # '../neural_audio_codec/music2/original.wav'
|
| 370 |
+
duration = get_duration(input_wav)
|
| 371 |
+
spec = extract_melspectrogram(input_wav, sr=self.model_sr, duration=duration)
|
| 372 |
+
x = torch.tensor(spec)[None,..., None].permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format)
|
| 373 |
+
return x
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
if __name__ == '__main__':
|
| 378 |
+
from omegaconf import OmegaConf
|
| 379 |
+
from train import instantiate_from_config
|
| 380 |
+
|
| 381 |
+
image_key = 'image'
|
| 382 |
+
cfg_audio = OmegaConf.load('./configs/vggsound_codebook.yaml')
|
| 383 |
+
model = VQModel(cfg_audio.model.params.ddconfig,
|
| 384 |
+
cfg_audio.model.params.lossconfig,
|
| 385 |
+
cfg_audio.model.params.n_embed,
|
| 386 |
+
cfg_audio.model.params.embed_dim,
|
| 387 |
+
image_key='image')
|
| 388 |
+
batch = {
|
| 389 |
+
'image': torch.rand((4, 80, 848)),
|
| 390 |
+
'file_path_': ['data/vggsound/mel123.npy', 'data/vggsound/mel123.npy', 'data/vggsound/mel123.npy'],
|
| 391 |
+
'class': [1, 1, 1],
|
| 392 |
+
}
|
| 393 |
+
xrec, qloss = model(model.get_input(batch, image_key))
|
| 394 |
+
print(xrec.shape, qloss.shape)
|
instructany2pix/llm/model/vae/builder.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pathlib
|
| 2 |
+
import os
|
| 3 |
+
from typing import Any
|
| 4 |
+
from .image_vqvae import instantiate_from_config,ImageVAEProcesser
|
| 5 |
+
from .audio_vqvae import AudioVAEProcesser
|
| 6 |
+
from .clip import ClipVisionPreprocessorForLLM,NpzLoader
|
| 7 |
+
import yaml
|
| 8 |
+
import torch
|
| 9 |
+
from torch import nn
|
| 10 |
+
CURR_PATH = pathlib.Path(__file__).parent.resolve()
|
| 11 |
+
|
| 12 |
+
def build_vae(config,modality):
|
| 13 |
+
config_file = CURR_PATH / f'{config}.yaml'
|
| 14 |
+
with open(config_file) as f:
|
| 15 |
+
config = yaml.safe_load(f.read())
|
| 16 |
+
model_config = config['model']
|
| 17 |
+
model = instantiate_from_config(model_config)
|
| 18 |
+
ckpt = config['ckpt']
|
| 19 |
+
if ckpt:
|
| 20 |
+
sd = torch.load(ckpt,map_location='cpu')["state_dict"]
|
| 21 |
+
model.load_state_dict(sd, strict=False)
|
| 22 |
+
if modality == 'image':
|
| 23 |
+
if config.get("processor") == 'clip':
|
| 24 |
+
processor = ClipVisionPreprocessorForLLM(pretrained=config['model']['params']['pretrained'])
|
| 25 |
+
else:
|
| 26 |
+
processor = ImageVAEProcesser(config['image_size'])
|
| 27 |
+
elif modality == 'audio':
|
| 28 |
+
if config.get("processor") == 'npz':
|
| 29 |
+
processor = NpzLoader()
|
| 30 |
+
else:
|
| 31 |
+
processor = AudioVAEProcesser(config['data']['params']['sample_rate'])
|
| 32 |
+
return model,processor
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class VQVAEProcessor:
|
| 37 |
+
def __init__(self,image_vae_processor,audio_vae_processor) -> None:
|
| 38 |
+
self.image_vae_processor = image_vae_processor
|
| 39 |
+
self.audio_vae_processor = audio_vae_processor
|
| 40 |
+
|
| 41 |
+
def __call__(self, x,modality) -> Any:
|
| 42 |
+
if modality == 'image':
|
| 43 |
+
return self.image_vae_processor(x)
|
| 44 |
+
elif modality == 'audio':
|
| 45 |
+
return self.audio_vae_processor(x)
|
| 46 |
+
else:
|
| 47 |
+
raise NotImplemented
|
| 48 |
+
|
| 49 |
+
class VQVAE(nn.Module):
|
| 50 |
+
|
| 51 |
+
def __init__(self,image_vae,audio_vae) -> None:
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.image_vae_processor = None
|
| 54 |
+
self.audio_vae_processor = None
|
| 55 |
+
self.embed_dim_image = 1
|
| 56 |
+
self.embed_dim_audio = 1
|
| 57 |
+
self.vocab_size_image = 1
|
| 58 |
+
self.vocab_size_audio = 1
|
| 59 |
+
if image_vae:
|
| 60 |
+
self.image_vae,self.image_vae_processor = build_vae(image_vae,'image')
|
| 61 |
+
self.image_vae.requires_grad_(False)
|
| 62 |
+
self.embed_dim_image = self.image_vae.embed_dim
|
| 63 |
+
self.vocab_size_image = self.image_vae.n_embed
|
| 64 |
+
if audio_vae:
|
| 65 |
+
self.audio_vae,self.audio_vae_processor = build_vae(audio_vae,'audio')
|
| 66 |
+
self.audio_vae.requires_grad_(False)
|
| 67 |
+
self.embed_dim_audio = self.audio_vae.embed_dim
|
| 68 |
+
self.vocab_size_audio = self.audio_vae.n_embed
|
| 69 |
+
self.processor = VQVAEProcessor(self.image_vae_processor,self.audio_vae_processor)
|
| 70 |
+
|
| 71 |
+
@torch.no_grad()
|
| 72 |
+
def forward(self,x):
|
| 73 |
+
out = {}
|
| 74 |
+
if 'image' in x:
|
| 75 |
+
out['image'] = self.image_vae.encode_seq(x['image'])
|
| 76 |
+
if 'audio' in x:
|
| 77 |
+
out['audio'] = self.audio_vae.encode_seq(x['audio'])
|
| 78 |
+
return out
|
| 79 |
+
|
instructany2pix/llm/model/vae/clip.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import CLIPImageProcessor,CLIPVisionModelWithProjection
|
| 2 |
+
from torch import nn
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import os
|
| 5 |
+
import torch
|
| 6 |
+
import numpy as np
|
| 7 |
+
class ClipVisionModelInterfaceForLLM(nn.Module):
|
| 8 |
+
def __init__(self, embed_dim,pretrained,lazy_init=True, *args, **kwargs):
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.embed_dim = embed_dim
|
| 11 |
+
self.n_embed = 1024
|
| 12 |
+
self.clip_model = CLIPVisionModelWithProjection.from_pretrained(pretrained,low_cpu_mem_usage=os.environ.get('DEEPSPEED3',False) == False)
|
| 13 |
+
|
| 14 |
+
def encode_seq(self,x,model=None):
|
| 15 |
+
x = self.clip_model(torch.cat(x.pixel_values)).image_embeds
|
| 16 |
+
x = x[...,None,None]
|
| 17 |
+
return x,None,None
|
| 18 |
+
|
| 19 |
+
def decode_seq(self,ind,target_shape):
|
| 20 |
+
return ind
|
| 21 |
+
|
| 22 |
+
class ClipVisionPreprocessorForLLM:
|
| 23 |
+
def __init__(self,pretrained, *args, **kwargs):
|
| 24 |
+
self.processor = CLIPImageProcessor.from_pretrained(pretrained)
|
| 25 |
+
|
| 26 |
+
def __call__(self,image):
|
| 27 |
+
image = Image.open(image).convert("RGB")
|
| 28 |
+
return self.processor(images=image)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class TensorLoader(nn.Module):
|
| 32 |
+
def __init__(self, embed_dim,n_embed,lazy_init=True, *args, **kwargs):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.embed_dim = embed_dim
|
| 35 |
+
self.n_embed = n_embed
|
| 36 |
+
|
| 37 |
+
def encode_seq(self,x,model=None):
|
| 38 |
+
# x = self.clip_model(torch.cat(x.pixel_values)).image_embeds
|
| 39 |
+
# x = x[...,None,None]
|
| 40 |
+
return x,None,None
|
| 41 |
+
|
| 42 |
+
def decode_seq(self,ind,target_shape):
|
| 43 |
+
return ind
|
| 44 |
+
|
| 45 |
+
class NpzLoader:
|
| 46 |
+
def __init__(self, *args, **kwargs):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
def __call__(self,image):
|
| 50 |
+
x = np.load(image)['state']
|
| 51 |
+
x = torch.tensor(x)
|
| 52 |
+
return x
|
instructany2pix/llm/model/vae/image_vqvae.py
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
import torch
|
| 3 |
+
import pytorch_lightning as pl
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
|
| 7 |
+
from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
|
| 8 |
+
|
| 9 |
+
from .modules.blocks import Encoder, Decoder
|
| 10 |
+
from .modules.distributions import DiagonalGaussianDistribution
|
| 11 |
+
|
| 12 |
+
from .modules.util import instantiate_from_config
|
| 13 |
+
import numpy as np
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from torchvision import transforms as T
|
| 16 |
+
class VQModel(pl.LightningModule):
|
| 17 |
+
def __init__(self,
|
| 18 |
+
ddconfig,
|
| 19 |
+
lossconfig,
|
| 20 |
+
n_embed,
|
| 21 |
+
embed_dim,
|
| 22 |
+
ckpt_path=None,
|
| 23 |
+
ignore_keys=[],
|
| 24 |
+
image_key="image",
|
| 25 |
+
colorize_nlabels=None,
|
| 26 |
+
monitor=None,
|
| 27 |
+
batch_resize_range=None,
|
| 28 |
+
scheduler_config=None,
|
| 29 |
+
lr_g_factor=1.0,
|
| 30 |
+
remap=None,
|
| 31 |
+
sane_index_shape=False, # tell vector quantizer to return indices as bhw
|
| 32 |
+
use_ema=False
|
| 33 |
+
):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.embed_dim = embed_dim
|
| 36 |
+
self.n_embed = n_embed
|
| 37 |
+
self.image_key = image_key
|
| 38 |
+
self.encoder = Encoder(**ddconfig)
|
| 39 |
+
self.decoder = Decoder(**ddconfig)
|
| 40 |
+
self.loss = instantiate_from_config(lossconfig)
|
| 41 |
+
self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25,
|
| 42 |
+
remap=remap,
|
| 43 |
+
sane_index_shape=sane_index_shape)
|
| 44 |
+
self.quant_conv = torch.nn.Conv2d(ddconfig["z_channels"], embed_dim, 1)
|
| 45 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
| 46 |
+
if colorize_nlabels is not None:
|
| 47 |
+
assert type(colorize_nlabels)==int
|
| 48 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
| 49 |
+
if monitor is not None:
|
| 50 |
+
self.monitor = monitor
|
| 51 |
+
self.batch_resize_range = batch_resize_range
|
| 52 |
+
if self.batch_resize_range is not None:
|
| 53 |
+
print(f"{self.__class__.__name__}: Using per-batch resizing in range {batch_resize_range}.")
|
| 54 |
+
|
| 55 |
+
self.use_ema = use_ema
|
| 56 |
+
if self.use_ema:
|
| 57 |
+
raise NotImplemented
|
| 58 |
+
#self.model_ema = LitEma(self)
|
| 59 |
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
| 60 |
+
|
| 61 |
+
if ckpt_path is not None:
|
| 62 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
| 63 |
+
self.scheduler_config = scheduler_config
|
| 64 |
+
self.lr_g_factor = lr_g_factor
|
| 65 |
+
|
| 66 |
+
@contextmanager
|
| 67 |
+
def ema_scope(self, context=None):
|
| 68 |
+
if self.use_ema:
|
| 69 |
+
self.model_ema.store(self.parameters())
|
| 70 |
+
self.model_ema.copy_to(self)
|
| 71 |
+
if context is not None:
|
| 72 |
+
print(f"{context}: Switched to EMA weights")
|
| 73 |
+
try:
|
| 74 |
+
yield None
|
| 75 |
+
finally:
|
| 76 |
+
if self.use_ema:
|
| 77 |
+
self.model_ema.restore(self.parameters())
|
| 78 |
+
if context is not None:
|
| 79 |
+
print(f"{context}: Restored training weights")
|
| 80 |
+
|
| 81 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
| 82 |
+
sd = torch.load(path, map_location="cpu")["state_dict"]
|
| 83 |
+
keys = list(sd.keys())
|
| 84 |
+
for k in keys:
|
| 85 |
+
for ik in ignore_keys:
|
| 86 |
+
if k.startswith(ik):
|
| 87 |
+
print("Deleting key {} from state_dict.".format(k))
|
| 88 |
+
del sd[k]
|
| 89 |
+
missing, unexpected = self.load_state_dict(sd, strict=False)
|
| 90 |
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
| 91 |
+
if len(missing) > 0:
|
| 92 |
+
print(f"Missing Keys: {missing}")
|
| 93 |
+
print(f"Unexpected Keys: {unexpected}")
|
| 94 |
+
|
| 95 |
+
def on_train_batch_end(self, *args, **kwargs):
|
| 96 |
+
if self.use_ema:
|
| 97 |
+
self.model_ema(self)
|
| 98 |
+
|
| 99 |
+
def encode(self, x):
|
| 100 |
+
h = self.encoder(x)
|
| 101 |
+
h = self.quant_conv(h)
|
| 102 |
+
quant, emb_loss, info = self.quantize(h)
|
| 103 |
+
return quant, emb_loss, info
|
| 104 |
+
|
| 105 |
+
def encode_to_prequant(self, x):
|
| 106 |
+
h = self.encoder(x)
|
| 107 |
+
h = self.quant_conv(h)
|
| 108 |
+
return h
|
| 109 |
+
|
| 110 |
+
def decode(self, quant):
|
| 111 |
+
quant = self.post_quant_conv(quant)
|
| 112 |
+
dec = self.decoder(quant)
|
| 113 |
+
return dec
|
| 114 |
+
|
| 115 |
+
def decode_code(self, code_b):
|
| 116 |
+
quant_b = self.quantize.embed_code(code_b)
|
| 117 |
+
dec = self.decode(quant_b)
|
| 118 |
+
return dec
|
| 119 |
+
|
| 120 |
+
def forward(self, input, return_pred_indices=False):
|
| 121 |
+
quant, diff, (_,_,ind) = self.encode(input)
|
| 122 |
+
dec = self.decode(quant)
|
| 123 |
+
if return_pred_indices:
|
| 124 |
+
return dec, diff, ind
|
| 125 |
+
return dec, diff
|
| 126 |
+
|
| 127 |
+
def get_input(self, batch, k):
|
| 128 |
+
x = batch[k]
|
| 129 |
+
if len(x.shape) == 3:
|
| 130 |
+
x = x[..., None]
|
| 131 |
+
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
|
| 132 |
+
if self.batch_resize_range is not None:
|
| 133 |
+
lower_size = self.batch_resize_range[0]
|
| 134 |
+
upper_size = self.batch_resize_range[1]
|
| 135 |
+
if self.global_step <= 4:
|
| 136 |
+
# do the first few batches with max size to avoid later oom
|
| 137 |
+
new_resize = upper_size
|
| 138 |
+
else:
|
| 139 |
+
new_resize = np.random.choice(np.arange(lower_size, upper_size+16, 16))
|
| 140 |
+
if new_resize != x.shape[2]:
|
| 141 |
+
x = F.interpolate(x, size=new_resize, mode="bicubic")
|
| 142 |
+
x = x.detach()
|
| 143 |
+
return x
|
| 144 |
+
|
| 145 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
| 146 |
+
# https://github.com/pytorch/pytorch/issues/37142
|
| 147 |
+
# try not to fool the heuristics
|
| 148 |
+
x = self.get_input(batch, self.image_key)
|
| 149 |
+
xrec, qloss, ind = self(x, return_pred_indices=True)
|
| 150 |
+
|
| 151 |
+
if optimizer_idx == 0:
|
| 152 |
+
# autoencode
|
| 153 |
+
aeloss, log_dict_ae = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
| 154 |
+
last_layer=self.get_last_layer(), split="train",
|
| 155 |
+
predicted_indices=ind)
|
| 156 |
+
|
| 157 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
| 158 |
+
return aeloss
|
| 159 |
+
|
| 160 |
+
if optimizer_idx == 1:
|
| 161 |
+
# discriminator
|
| 162 |
+
discloss, log_dict_disc = self.loss(qloss, x, xrec, optimizer_idx, self.global_step,
|
| 163 |
+
last_layer=self.get_last_layer(), split="train")
|
| 164 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=True)
|
| 165 |
+
return discloss
|
| 166 |
+
|
| 167 |
+
def validation_step(self, batch, batch_idx):
|
| 168 |
+
log_dict = self._validation_step(batch, batch_idx)
|
| 169 |
+
with self.ema_scope():
|
| 170 |
+
log_dict_ema = self._validation_step(batch, batch_idx, suffix="_ema")
|
| 171 |
+
return log_dict
|
| 172 |
+
|
| 173 |
+
def _validation_step(self, batch, batch_idx, suffix=""):
|
| 174 |
+
raise NotImplemented
|
| 175 |
+
# x = self.get_input(batch, self.image_key)
|
| 176 |
+
# xrec, qloss, ind = self(x, return_pred_indices=True)
|
| 177 |
+
# aeloss, log_dict_ae = self.loss(qloss, x, xrec, 0,
|
| 178 |
+
# self.global_step,
|
| 179 |
+
# last_layer=self.get_last_layer(),
|
| 180 |
+
# split="val"+suffix,
|
| 181 |
+
# predicted_indices=ind
|
| 182 |
+
# )
|
| 183 |
+
|
| 184 |
+
# discloss, log_dict_disc = self.loss(qloss, x, xrec, 1,
|
| 185 |
+
# self.global_step,
|
| 186 |
+
# last_layer=self.get_last_layer(),
|
| 187 |
+
# split="val"+suffix,
|
| 188 |
+
# predicted_indices=ind
|
| 189 |
+
# )
|
| 190 |
+
# rec_loss = log_dict_ae[f"val{suffix}/rec_loss"]
|
| 191 |
+
# self.log(f"val{suffix}/rec_loss", rec_loss,
|
| 192 |
+
# prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
| 193 |
+
# self.log(f"val{suffix}/aeloss", aeloss,
|
| 194 |
+
# prog_bar=True, logger=True, on_step=False, on_epoch=True, sync_dist=True)
|
| 195 |
+
# if version.parse(pl.__version__) >= version.parse('1.4.0'):
|
| 196 |
+
# del log_dict_ae[f"val{suffix}/rec_loss"]
|
| 197 |
+
# self.log_dict(log_dict_ae)
|
| 198 |
+
# self.log_dict(log_dict_disc)
|
| 199 |
+
# return self.log_dict
|
| 200 |
+
|
| 201 |
+
def configure_optimizers(self):
|
| 202 |
+
lr_d = self.learning_rate
|
| 203 |
+
lr_g = self.lr_g_factor*self.learning_rate
|
| 204 |
+
print("lr_d", lr_d)
|
| 205 |
+
print("lr_g", lr_g)
|
| 206 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
| 207 |
+
list(self.decoder.parameters())+
|
| 208 |
+
list(self.quantize.parameters())+
|
| 209 |
+
list(self.quant_conv.parameters())+
|
| 210 |
+
list(self.post_quant_conv.parameters()),
|
| 211 |
+
lr=lr_g, betas=(0.5, 0.9))
|
| 212 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
| 213 |
+
lr=lr_d, betas=(0.5, 0.9))
|
| 214 |
+
|
| 215 |
+
if self.scheduler_config is not None:
|
| 216 |
+
scheduler = instantiate_from_config(self.scheduler_config)
|
| 217 |
+
|
| 218 |
+
print("Setting up LambdaLR scheduler...")
|
| 219 |
+
raise NotImplemented
|
| 220 |
+
# scheduler = [
|
| 221 |
+
# {
|
| 222 |
+
# 'scheduler': LambdaLR(opt_ae, lr_lambda=scheduler.schedule),
|
| 223 |
+
# 'interval': 'step',
|
| 224 |
+
# 'frequency': 1
|
| 225 |
+
# },
|
| 226 |
+
# {
|
| 227 |
+
# 'scheduler': LambdaLR(opt_disc, lr_lambda=scheduler.schedule),
|
| 228 |
+
# 'interval': 'step',
|
| 229 |
+
# 'frequency': 1
|
| 230 |
+
# },
|
| 231 |
+
# ]
|
| 232 |
+
return [opt_ae, opt_disc], scheduler
|
| 233 |
+
return [opt_ae, opt_disc], []
|
| 234 |
+
|
| 235 |
+
def get_last_layer(self):
|
| 236 |
+
return self.decoder.conv_out.weight
|
| 237 |
+
|
| 238 |
+
def log_images(self, batch, only_inputs=False, plot_ema=False, **kwargs):
|
| 239 |
+
log = dict()
|
| 240 |
+
x = self.get_input(batch, self.image_key)
|
| 241 |
+
x = x.to(self.device)
|
| 242 |
+
if only_inputs:
|
| 243 |
+
log["inputs"] = x
|
| 244 |
+
return log
|
| 245 |
+
xrec, _ = self(x)
|
| 246 |
+
if x.shape[1] > 3:
|
| 247 |
+
# colorize with random projection
|
| 248 |
+
assert xrec.shape[1] > 3
|
| 249 |
+
x = self.to_rgb(x)
|
| 250 |
+
xrec = self.to_rgb(xrec)
|
| 251 |
+
log["inputs"] = x
|
| 252 |
+
log["reconstructions"] = xrec
|
| 253 |
+
if plot_ema:
|
| 254 |
+
with self.ema_scope():
|
| 255 |
+
xrec_ema, _ = self(x)
|
| 256 |
+
if x.shape[1] > 3: xrec_ema = self.to_rgb(xrec_ema)
|
| 257 |
+
log["reconstructions_ema"] = xrec_ema
|
| 258 |
+
return log
|
| 259 |
+
|
| 260 |
+
def to_rgb(self, x):
|
| 261 |
+
assert self.image_key == "segmentation"
|
| 262 |
+
if not hasattr(self, "colorize"):
|
| 263 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
| 264 |
+
x = F.conv2d(x, weight=self.colorize)
|
| 265 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
| 266 |
+
return x
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class VQModelInterface(VQModel):
|
| 270 |
+
def __init__(self, embed_dim, *args, **kwargs):
|
| 271 |
+
super().__init__(embed_dim=embed_dim, *args, **kwargs)
|
| 272 |
+
self.embed_dim = embed_dim
|
| 273 |
+
|
| 274 |
+
def encode(self, x):
|
| 275 |
+
h = self.encoder(x)
|
| 276 |
+
h = self.quant_conv(h)
|
| 277 |
+
return h
|
| 278 |
+
|
| 279 |
+
def decode(self, h, force_not_quantize=False):
|
| 280 |
+
# also go through quantization layer
|
| 281 |
+
if not force_not_quantize:
|
| 282 |
+
quant, emb_loss, info = self.quantize(h)
|
| 283 |
+
else:
|
| 284 |
+
quant = h
|
| 285 |
+
quant = self.post_quant_conv(quant)
|
| 286 |
+
dec = self.decoder(quant)
|
| 287 |
+
return dec
|
| 288 |
+
|
| 289 |
+
class VQVisionModelInterfaceForLLM(VQModel):
|
| 290 |
+
def __init__(self, embed_dim, *args, **kwargs):
|
| 291 |
+
super().__init__(embed_dim=embed_dim, *args, **kwargs)
|
| 292 |
+
self.embed_dim = embed_dim
|
| 293 |
+
|
| 294 |
+
def encode_seq(self,x):
|
| 295 |
+
quant, diff, (_,_,ind) = self.encode(x)
|
| 296 |
+
n,c,h,w = quant.shape
|
| 297 |
+
return quant,ind,(n,c,h,w)
|
| 298 |
+
|
| 299 |
+
def decode_seq(self,ind,target_shape):
|
| 300 |
+
n,c,h,w = target_shape
|
| 301 |
+
y = self.quantize.embedding(ind).view(n,h,w,c).permute(0,3,1,2)
|
| 302 |
+
y = self.decode(y)
|
| 303 |
+
return y
|
| 304 |
+
|
| 305 |
+
class AutoencoderKL(pl.LightningModule):
|
| 306 |
+
def __init__(self,
|
| 307 |
+
ddconfig,
|
| 308 |
+
lossconfig,
|
| 309 |
+
embed_dim,
|
| 310 |
+
ckpt_path=None,
|
| 311 |
+
ignore_keys=[],
|
| 312 |
+
image_key="image",
|
| 313 |
+
colorize_nlabels=None,
|
| 314 |
+
monitor=None,
|
| 315 |
+
):
|
| 316 |
+
super().__init__()
|
| 317 |
+
self.image_key = image_key
|
| 318 |
+
self.encoder = Encoder(**ddconfig)
|
| 319 |
+
self.decoder = Decoder(**ddconfig)
|
| 320 |
+
self.loss = instantiate_from_config(lossconfig)
|
| 321 |
+
assert ddconfig["double_z"]
|
| 322 |
+
self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1)
|
| 323 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1)
|
| 324 |
+
self.embed_dim = embed_dim
|
| 325 |
+
if colorize_nlabels is not None:
|
| 326 |
+
assert type(colorize_nlabels)==int
|
| 327 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
| 328 |
+
if monitor is not None:
|
| 329 |
+
self.monitor = monitor
|
| 330 |
+
if ckpt_path is not None:
|
| 331 |
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
|
| 332 |
+
|
| 333 |
+
def init_from_ckpt(self, path, ignore_keys=list()):
|
| 334 |
+
sd = torch.load(path, map_location="cpu")["state_dict"]
|
| 335 |
+
keys = list(sd.keys())
|
| 336 |
+
for k in keys:
|
| 337 |
+
for ik in ignore_keys:
|
| 338 |
+
if k.startswith(ik):
|
| 339 |
+
print("Deleting key {} from state_dict.".format(k))
|
| 340 |
+
del sd[k]
|
| 341 |
+
self.load_state_dict(sd, strict=False)
|
| 342 |
+
print(f"Restored from {path}")
|
| 343 |
+
|
| 344 |
+
def encode(self, x):
|
| 345 |
+
h = self.encoder(x)
|
| 346 |
+
moments = self.quant_conv(h)
|
| 347 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 348 |
+
return posterior
|
| 349 |
+
|
| 350 |
+
def decode(self, z):
|
| 351 |
+
z = self.post_quant_conv(z)
|
| 352 |
+
dec = self.decoder(z)
|
| 353 |
+
return dec
|
| 354 |
+
|
| 355 |
+
def forward(self, input, sample_posterior=True):
|
| 356 |
+
posterior = self.encode(input)
|
| 357 |
+
if sample_posterior:
|
| 358 |
+
z = posterior.sample()
|
| 359 |
+
else:
|
| 360 |
+
z = posterior.mode()
|
| 361 |
+
dec = self.decode(z)
|
| 362 |
+
return dec, posterior
|
| 363 |
+
|
| 364 |
+
def get_input(self, batch, k):
|
| 365 |
+
x = batch[k]
|
| 366 |
+
if len(x.shape) == 3:
|
| 367 |
+
x = x[..., None]
|
| 368 |
+
x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float()
|
| 369 |
+
return x
|
| 370 |
+
|
| 371 |
+
def training_step(self, batch, batch_idx, optimizer_idx):
|
| 372 |
+
inputs = self.get_input(batch, self.image_key)
|
| 373 |
+
reconstructions, posterior = self(inputs)
|
| 374 |
+
|
| 375 |
+
if optimizer_idx == 0:
|
| 376 |
+
# train encoder+decoder+logvar
|
| 377 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
| 378 |
+
last_layer=self.get_last_layer(), split="train")
|
| 379 |
+
self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
| 380 |
+
self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
| 381 |
+
return aeloss
|
| 382 |
+
|
| 383 |
+
if optimizer_idx == 1:
|
| 384 |
+
# train the discriminator
|
| 385 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step,
|
| 386 |
+
last_layer=self.get_last_layer(), split="train")
|
| 387 |
+
|
| 388 |
+
self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True)
|
| 389 |
+
self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False)
|
| 390 |
+
return discloss
|
| 391 |
+
|
| 392 |
+
def validation_step(self, batch, batch_idx):
|
| 393 |
+
inputs = self.get_input(batch, self.image_key)
|
| 394 |
+
reconstructions, posterior = self(inputs)
|
| 395 |
+
aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step,
|
| 396 |
+
last_layer=self.get_last_layer(), split="val")
|
| 397 |
+
|
| 398 |
+
discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step,
|
| 399 |
+
last_layer=self.get_last_layer(), split="val")
|
| 400 |
+
|
| 401 |
+
self.log("val/rec_loss", log_dict_ae["val/rec_loss"])
|
| 402 |
+
self.log_dict(log_dict_ae)
|
| 403 |
+
self.log_dict(log_dict_disc)
|
| 404 |
+
return self.log_dict
|
| 405 |
+
|
| 406 |
+
def configure_optimizers(self):
|
| 407 |
+
lr = self.learning_rate
|
| 408 |
+
opt_ae = torch.optim.Adam(list(self.encoder.parameters())+
|
| 409 |
+
list(self.decoder.parameters())+
|
| 410 |
+
list(self.quant_conv.parameters())+
|
| 411 |
+
list(self.post_quant_conv.parameters()),
|
| 412 |
+
lr=lr, betas=(0.5, 0.9))
|
| 413 |
+
opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(),
|
| 414 |
+
lr=lr, betas=(0.5, 0.9))
|
| 415 |
+
return [opt_ae, opt_disc], []
|
| 416 |
+
|
| 417 |
+
def get_last_layer(self):
|
| 418 |
+
return self.decoder.conv_out.weight
|
| 419 |
+
|
| 420 |
+
@torch.no_grad()
|
| 421 |
+
def log_images(self, batch, only_inputs=False, **kwargs):
|
| 422 |
+
log = dict()
|
| 423 |
+
x = self.get_input(batch, self.image_key)
|
| 424 |
+
x = x.to(self.device)
|
| 425 |
+
if not only_inputs:
|
| 426 |
+
xrec, posterior = self(x)
|
| 427 |
+
if x.shape[1] > 3:
|
| 428 |
+
# colorize with random projection
|
| 429 |
+
assert xrec.shape[1] > 3
|
| 430 |
+
x = self.to_rgb(x)
|
| 431 |
+
xrec = self.to_rgb(xrec)
|
| 432 |
+
log["samples"] = self.decode(torch.randn_like(posterior.sample()))
|
| 433 |
+
log["reconstructions"] = xrec
|
| 434 |
+
log["inputs"] = x
|
| 435 |
+
return log
|
| 436 |
+
|
| 437 |
+
def to_rgb(self, x):
|
| 438 |
+
assert self.image_key == "segmentation"
|
| 439 |
+
if not hasattr(self, "colorize"):
|
| 440 |
+
self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x))
|
| 441 |
+
x = F.conv2d(x, weight=self.colorize)
|
| 442 |
+
x = 2.*(x-x.min())/(x.max()-x.min()) - 1.
|
| 443 |
+
return x
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class IdentityFirstStage(torch.nn.Module):
|
| 447 |
+
def __init__(self, *args, vq_interface=False, **kwargs):
|
| 448 |
+
self.vq_interface = vq_interface # TODO: Should be true by default but check to not break older stuff
|
| 449 |
+
super().__init__()
|
| 450 |
+
|
| 451 |
+
def encode(self, x, *args, **kwargs):
|
| 452 |
+
return x
|
| 453 |
+
|
| 454 |
+
def decode(self, x, *args, **kwargs):
|
| 455 |
+
return x
|
| 456 |
+
|
| 457 |
+
def quantize(self, x, *args, **kwargs):
|
| 458 |
+
if self.vq_interface:
|
| 459 |
+
return x, None, [None, None, None]
|
| 460 |
+
return x
|
| 461 |
+
|
| 462 |
+
def forward(self, x, *args, **kwargs):
|
| 463 |
+
return x
|
| 464 |
+
|
| 465 |
+
class ImageVAEProcesser:
|
| 466 |
+
|
| 467 |
+
def __init__(self,image_size=128) -> None:
|
| 468 |
+
self.transform = T.Compose([
|
| 469 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
| 470 |
+
T.Resize(image_size),
|
| 471 |
+
T.RandomHorizontalFlip(),
|
| 472 |
+
T.CenterCrop(image_size),
|
| 473 |
+
T.ToTensor()
|
| 474 |
+
])
|
| 475 |
+
|
| 476 |
+
def __call__(self, image) -> Any:
|
| 477 |
+
image = Image.open(image).convert("RGB")
|
| 478 |
+
image = self.transform(image)
|
| 479 |
+
return image
|
| 480 |
+
|
| 481 |
+
def make_batch_image(image,size=128):
|
| 482 |
+
image = Image.open(image).convert("RGB")
|
| 483 |
+
image = image.resize((128,128))
|
| 484 |
+
image = np.array(image)
|
| 485 |
+
image = image.astype(np.float32)/255.0
|
| 486 |
+
image = image[None].transpose(0,3,1,2)
|
| 487 |
+
image = torch.from_numpy(image)
|
| 488 |
+
return image
|
instructany2pix/llm/model/vae/modules/__init__.py
ADDED
|
File without changes
|
instructany2pix/llm/model/vae/modules/attention.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from inspect import isfunction
|
| 2 |
+
import math
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import nn, einsum
|
| 6 |
+
from einops import rearrange, repeat
|
| 7 |
+
|
| 8 |
+
from .util import checkpoint
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def exists(val):
|
| 12 |
+
return val is not None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def uniq(arr):
|
| 16 |
+
return{el: True for el in arr}.keys()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def default(val, d):
|
| 20 |
+
if exists(val):
|
| 21 |
+
return val
|
| 22 |
+
return d() if isfunction(d) else d
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def max_neg_value(t):
|
| 26 |
+
return -torch.finfo(t.dtype).max
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def init_(tensor):
|
| 30 |
+
dim = tensor.shape[-1]
|
| 31 |
+
std = 1 / math.sqrt(dim)
|
| 32 |
+
tensor.uniform_(-std, std)
|
| 33 |
+
return tensor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# feedforward
|
| 37 |
+
class GEGLU(nn.Module):
|
| 38 |
+
def __init__(self, dim_in, dim_out):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.proj = nn.Linear(dim_in, dim_out * 2)
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
x, gate = self.proj(x).chunk(2, dim=-1)
|
| 44 |
+
return x * F.gelu(gate)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class FeedForward(nn.Module):
|
| 48 |
+
def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.):
|
| 49 |
+
super().__init__()
|
| 50 |
+
inner_dim = int(dim * mult)
|
| 51 |
+
dim_out = default(dim_out, dim)
|
| 52 |
+
project_in = nn.Sequential(
|
| 53 |
+
nn.Linear(dim, inner_dim),
|
| 54 |
+
nn.GELU()
|
| 55 |
+
) if not glu else GEGLU(dim, inner_dim)
|
| 56 |
+
|
| 57 |
+
self.net = nn.Sequential(
|
| 58 |
+
project_in,
|
| 59 |
+
nn.Dropout(dropout),
|
| 60 |
+
nn.Linear(inner_dim, dim_out)
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def forward(self, x):
|
| 64 |
+
return self.net(x)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def zero_module(module):
|
| 68 |
+
"""
|
| 69 |
+
Zero out the parameters of a module and return it.
|
| 70 |
+
"""
|
| 71 |
+
for p in module.parameters():
|
| 72 |
+
p.detach().zero_()
|
| 73 |
+
return module
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def Normalize(in_channels):
|
| 77 |
+
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class LinearAttention(nn.Module):
|
| 81 |
+
def __init__(self, dim, heads=4, dim_head=32):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.heads = heads
|
| 84 |
+
hidden_dim = dim_head * heads
|
| 85 |
+
self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias = False)
|
| 86 |
+
self.to_out = nn.Conv2d(hidden_dim, dim, 1)
|
| 87 |
+
|
| 88 |
+
def forward(self, x):
|
| 89 |
+
b, c, h, w = x.shape
|
| 90 |
+
qkv = self.to_qkv(x)
|
| 91 |
+
q, k, v = rearrange(qkv, 'b (qkv heads c) h w -> qkv b heads c (h w)', heads = self.heads, qkv=3)
|
| 92 |
+
k = k.softmax(dim=-1)
|
| 93 |
+
context = torch.einsum('bhdn,bhen->bhde', k, v)
|
| 94 |
+
out = torch.einsum('bhde,bhdn->bhen', context, q)
|
| 95 |
+
out = rearrange(out, 'b heads c (h w) -> b (heads c) h w', heads=self.heads, h=h, w=w)
|
| 96 |
+
return self.to_out(out)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class SpatialSelfAttention(nn.Module):
|
| 100 |
+
def __init__(self, in_channels):
|
| 101 |
+
super().__init__()
|
| 102 |
+
self.in_channels = in_channels
|
| 103 |
+
|
| 104 |
+
self.norm = Normalize(in_channels)
|
| 105 |
+
self.q = torch.nn.Conv2d(in_channels,
|
| 106 |
+
in_channels,
|
| 107 |
+
kernel_size=1,
|
| 108 |
+
stride=1,
|
| 109 |
+
padding=0)
|
| 110 |
+
self.k = torch.nn.Conv2d(in_channels,
|
| 111 |
+
in_channels,
|
| 112 |
+
kernel_size=1,
|
| 113 |
+
stride=1,
|
| 114 |
+
padding=0)
|
| 115 |
+
self.v = torch.nn.Conv2d(in_channels,
|
| 116 |
+
in_channels,
|
| 117 |
+
kernel_size=1,
|
| 118 |
+
stride=1,
|
| 119 |
+
padding=0)
|
| 120 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
| 121 |
+
in_channels,
|
| 122 |
+
kernel_size=1,
|
| 123 |
+
stride=1,
|
| 124 |
+
padding=0)
|
| 125 |
+
|
| 126 |
+
def forward(self, x):
|
| 127 |
+
h_ = x
|
| 128 |
+
h_ = self.norm(h_)
|
| 129 |
+
q = self.q(h_)
|
| 130 |
+
k = self.k(h_)
|
| 131 |
+
v = self.v(h_)
|
| 132 |
+
|
| 133 |
+
# compute attention
|
| 134 |
+
b,c,h,w = q.shape
|
| 135 |
+
q = rearrange(q, 'b c h w -> b (h w) c')
|
| 136 |
+
k = rearrange(k, 'b c h w -> b c (h w)')
|
| 137 |
+
w_ = torch.einsum('bij,bjk->bik', q, k)
|
| 138 |
+
|
| 139 |
+
w_ = w_ * (int(c)**(-0.5))
|
| 140 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
| 141 |
+
|
| 142 |
+
# attend to values
|
| 143 |
+
v = rearrange(v, 'b c h w -> b c (h w)')
|
| 144 |
+
w_ = rearrange(w_, 'b i j -> b j i')
|
| 145 |
+
h_ = torch.einsum('bij,bjk->bik', v, w_)
|
| 146 |
+
h_ = rearrange(h_, 'b c (h w) -> b c h w', h=h)
|
| 147 |
+
h_ = self.proj_out(h_)
|
| 148 |
+
|
| 149 |
+
return x+h_
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class CrossAttention(nn.Module):
|
| 153 |
+
def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
|
| 154 |
+
super().__init__()
|
| 155 |
+
inner_dim = dim_head * heads
|
| 156 |
+
context_dim = default(context_dim, query_dim)
|
| 157 |
+
|
| 158 |
+
self.scale = dim_head ** -0.5
|
| 159 |
+
self.heads = heads
|
| 160 |
+
|
| 161 |
+
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
| 162 |
+
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
|
| 163 |
+
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
|
| 164 |
+
|
| 165 |
+
self.to_out = nn.Sequential(
|
| 166 |
+
nn.Linear(inner_dim, query_dim),
|
| 167 |
+
nn.Dropout(dropout)
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def forward(self, x, context=None, mask=None):
|
| 171 |
+
h = self.heads
|
| 172 |
+
|
| 173 |
+
q = self.to_q(x)
|
| 174 |
+
context = default(context, x)
|
| 175 |
+
k = self.to_k(context)
|
| 176 |
+
v = self.to_v(context)
|
| 177 |
+
|
| 178 |
+
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
| 179 |
+
|
| 180 |
+
sim = einsum('b i d, b j d -> b i j', q, k) * self.scale
|
| 181 |
+
|
| 182 |
+
if exists(mask):
|
| 183 |
+
mask = rearrange(mask, 'b ... -> b (...)')
|
| 184 |
+
max_neg_value = -torch.finfo(sim.dtype).max
|
| 185 |
+
mask = repeat(mask, 'b j -> (b h) () j', h=h)
|
| 186 |
+
sim.masked_fill_(~mask, max_neg_value)
|
| 187 |
+
|
| 188 |
+
# attention, what we cannot get enough of
|
| 189 |
+
attn = sim.softmax(dim=-1)
|
| 190 |
+
|
| 191 |
+
out = einsum('b i j, b j d -> b i d', attn, v)
|
| 192 |
+
out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
|
| 193 |
+
return self.to_out(out)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class BasicTransformerBlock(nn.Module):
|
| 197 |
+
def __init__(self, dim, n_heads, d_head, dropout=0., context_dim=None, gated_ff=True, checkpoint=True):
|
| 198 |
+
super().__init__()
|
| 199 |
+
self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout) # is a self-attention
|
| 200 |
+
self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
|
| 201 |
+
self.attn2 = CrossAttention(query_dim=dim, context_dim=context_dim,
|
| 202 |
+
heads=n_heads, dim_head=d_head, dropout=dropout) # is self-attn if context is none
|
| 203 |
+
self.norm1 = nn.LayerNorm(dim)
|
| 204 |
+
self.norm2 = nn.LayerNorm(dim)
|
| 205 |
+
self.norm3 = nn.LayerNorm(dim)
|
| 206 |
+
self.checkpoint = checkpoint
|
| 207 |
+
|
| 208 |
+
def forward(self, x, context=None):
|
| 209 |
+
return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
|
| 210 |
+
|
| 211 |
+
def _forward(self, x, context=None):
|
| 212 |
+
x = self.attn1(self.norm1(x)) + x
|
| 213 |
+
x = self.attn2(self.norm2(x), context=context) + x
|
| 214 |
+
x = self.ff(self.norm3(x)) + x
|
| 215 |
+
return x
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class SpatialTransformer(nn.Module):
|
| 219 |
+
"""
|
| 220 |
+
Transformer block for image-like data.
|
| 221 |
+
First, project the input (aka embedding)
|
| 222 |
+
and reshape to b, t, d.
|
| 223 |
+
Then apply standard transformer action.
|
| 224 |
+
Finally, reshape to image
|
| 225 |
+
"""
|
| 226 |
+
def __init__(self, in_channels, n_heads, d_head,
|
| 227 |
+
depth=1, dropout=0., context_dim=None):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.in_channels = in_channels
|
| 230 |
+
inner_dim = n_heads * d_head
|
| 231 |
+
self.norm = Normalize(in_channels)
|
| 232 |
+
|
| 233 |
+
self.proj_in = nn.Conv2d(in_channels,
|
| 234 |
+
inner_dim,
|
| 235 |
+
kernel_size=1,
|
| 236 |
+
stride=1,
|
| 237 |
+
padding=0)
|
| 238 |
+
|
| 239 |
+
self.transformer_blocks = nn.ModuleList(
|
| 240 |
+
[BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim)
|
| 241 |
+
for d in range(depth)]
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
self.proj_out = zero_module(nn.Conv2d(inner_dim,
|
| 245 |
+
in_channels,
|
| 246 |
+
kernel_size=1,
|
| 247 |
+
stride=1,
|
| 248 |
+
padding=0))
|
| 249 |
+
|
| 250 |
+
def forward(self, x, context=None):
|
| 251 |
+
# note: if no context is given, cross-attention defaults to self-attention
|
| 252 |
+
b, c, h, w = x.shape
|
| 253 |
+
x_in = x
|
| 254 |
+
x = self.norm(x)
|
| 255 |
+
x = self.proj_in(x)
|
| 256 |
+
x = rearrange(x, 'b c h w -> b (h w) c')
|
| 257 |
+
for block in self.transformer_blocks:
|
| 258 |
+
x = block(x, context=context)
|
| 259 |
+
x = rearrange(x, 'b (h w) c -> b c h w', h=h, w=w)
|
| 260 |
+
x = self.proj_out(x)
|
| 261 |
+
return x + x_in
|
instructany2pix/llm/model/vae/modules/blocks.py
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pytorch_diffusion + derived encoder decoder
|
| 2 |
+
import math
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import numpy as np
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
|
| 8 |
+
from .util import instantiate_from_config
|
| 9 |
+
from .attention import LinearAttention
|
| 10 |
+
from .distributions import DiagonalGaussianDistribution
|
| 11 |
+
|
| 12 |
+
def get_timestep_embedding(timesteps, embedding_dim):
|
| 13 |
+
"""
|
| 14 |
+
This matches the implementation in Denoising Diffusion Probabilistic Models:
|
| 15 |
+
From Fairseq.
|
| 16 |
+
Build sinusoidal embeddings.
|
| 17 |
+
This matches the implementation in tensor2tensor, but differs slightly
|
| 18 |
+
from the description in Section 3.5 of "Attention Is All You Need".
|
| 19 |
+
"""
|
| 20 |
+
assert len(timesteps.shape) == 1
|
| 21 |
+
|
| 22 |
+
half_dim = embedding_dim // 2
|
| 23 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 24 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
|
| 25 |
+
emb = emb.to(device=timesteps.device)
|
| 26 |
+
emb = timesteps.float()[:, None] * emb[None, :]
|
| 27 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 28 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 29 |
+
emb = torch.nn.functional.pad(emb, (0,1,0,0))
|
| 30 |
+
return emb
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def nonlinearity(x):
|
| 34 |
+
# swish
|
| 35 |
+
return x*torch.sigmoid(x)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def Normalize(in_channels, num_groups=32):
|
| 39 |
+
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Upsample(nn.Module):
|
| 43 |
+
def __init__(self, in_channels, with_conv):
|
| 44 |
+
super().__init__()
|
| 45 |
+
self.with_conv = with_conv
|
| 46 |
+
if self.with_conv:
|
| 47 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 48 |
+
in_channels,
|
| 49 |
+
kernel_size=3,
|
| 50 |
+
stride=1,
|
| 51 |
+
padding=1)
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
dtype = x.dtype
|
| 55 |
+
x = torch.nn.functional.interpolate(x.float(), scale_factor=2.0, mode="nearest").to(dtype)
|
| 56 |
+
if self.with_conv:
|
| 57 |
+
x = self.conv(x)
|
| 58 |
+
return x
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class Downsample(nn.Module):
|
| 62 |
+
def __init__(self, in_channels, with_conv):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.with_conv = with_conv
|
| 65 |
+
if self.with_conv:
|
| 66 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 67 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 68 |
+
in_channels,
|
| 69 |
+
kernel_size=3,
|
| 70 |
+
stride=2,
|
| 71 |
+
padding=0)
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
if self.with_conv:
|
| 75 |
+
pad = (0,1,0,1)
|
| 76 |
+
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
| 77 |
+
x = self.conv(x)
|
| 78 |
+
else:
|
| 79 |
+
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
| 80 |
+
return x
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class ResnetBlock(nn.Module):
|
| 84 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
| 85 |
+
dropout, temb_channels=512):
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.in_channels = in_channels
|
| 88 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 89 |
+
self.out_channels = out_channels
|
| 90 |
+
self.use_conv_shortcut = conv_shortcut
|
| 91 |
+
|
| 92 |
+
self.norm1 = Normalize(in_channels)
|
| 93 |
+
self.conv1 = torch.nn.Conv2d(in_channels,
|
| 94 |
+
out_channels,
|
| 95 |
+
kernel_size=3,
|
| 96 |
+
stride=1,
|
| 97 |
+
padding=1)
|
| 98 |
+
if temb_channels > 0:
|
| 99 |
+
self.temb_proj = torch.nn.Linear(temb_channels,
|
| 100 |
+
out_channels)
|
| 101 |
+
self.norm2 = Normalize(out_channels)
|
| 102 |
+
self.dropout = torch.nn.Dropout(dropout)
|
| 103 |
+
self.conv2 = torch.nn.Conv2d(out_channels,
|
| 104 |
+
out_channels,
|
| 105 |
+
kernel_size=3,
|
| 106 |
+
stride=1,
|
| 107 |
+
padding=1)
|
| 108 |
+
if self.in_channels != self.out_channels:
|
| 109 |
+
if self.use_conv_shortcut:
|
| 110 |
+
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
| 111 |
+
out_channels,
|
| 112 |
+
kernel_size=3,
|
| 113 |
+
stride=1,
|
| 114 |
+
padding=1)
|
| 115 |
+
else:
|
| 116 |
+
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
| 117 |
+
out_channels,
|
| 118 |
+
kernel_size=1,
|
| 119 |
+
stride=1,
|
| 120 |
+
padding=0)
|
| 121 |
+
|
| 122 |
+
def forward(self, x, temb):
|
| 123 |
+
h = x
|
| 124 |
+
h = self.norm1(h)
|
| 125 |
+
h = nonlinearity(h)
|
| 126 |
+
h = self.conv1(h)
|
| 127 |
+
|
| 128 |
+
if temb is not None:
|
| 129 |
+
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
|
| 130 |
+
|
| 131 |
+
h = self.norm2(h)
|
| 132 |
+
h = nonlinearity(h)
|
| 133 |
+
h = self.dropout(h)
|
| 134 |
+
h = self.conv2(h)
|
| 135 |
+
|
| 136 |
+
if self.in_channels != self.out_channels:
|
| 137 |
+
if self.use_conv_shortcut:
|
| 138 |
+
x = self.conv_shortcut(x)
|
| 139 |
+
else:
|
| 140 |
+
x = self.nin_shortcut(x)
|
| 141 |
+
|
| 142 |
+
return x+h
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class LinAttnBlock(LinearAttention):
|
| 146 |
+
"""to match AttnBlock usage"""
|
| 147 |
+
def __init__(self, in_channels):
|
| 148 |
+
super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class AttnBlock(nn.Module):
|
| 152 |
+
def __init__(self, in_channels):
|
| 153 |
+
super().__init__()
|
| 154 |
+
self.in_channels = in_channels
|
| 155 |
+
|
| 156 |
+
self.norm = Normalize(in_channels)
|
| 157 |
+
self.q = torch.nn.Conv2d(in_channels,
|
| 158 |
+
in_channels,
|
| 159 |
+
kernel_size=1,
|
| 160 |
+
stride=1,
|
| 161 |
+
padding=0)
|
| 162 |
+
self.k = torch.nn.Conv2d(in_channels,
|
| 163 |
+
in_channels,
|
| 164 |
+
kernel_size=1,
|
| 165 |
+
stride=1,
|
| 166 |
+
padding=0)
|
| 167 |
+
self.v = torch.nn.Conv2d(in_channels,
|
| 168 |
+
in_channels,
|
| 169 |
+
kernel_size=1,
|
| 170 |
+
stride=1,
|
| 171 |
+
padding=0)
|
| 172 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
| 173 |
+
in_channels,
|
| 174 |
+
kernel_size=1,
|
| 175 |
+
stride=1,
|
| 176 |
+
padding=0)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def forward(self, x):
|
| 180 |
+
h_ = x
|
| 181 |
+
h_ = self.norm(h_)
|
| 182 |
+
q = self.q(h_)
|
| 183 |
+
k = self.k(h_)
|
| 184 |
+
v = self.v(h_)
|
| 185 |
+
|
| 186 |
+
# compute attention
|
| 187 |
+
b,c,h,w = q.shape
|
| 188 |
+
q = q.reshape(b,c,h*w)
|
| 189 |
+
q = q.permute(0,2,1) # b,hw,c
|
| 190 |
+
k = k.reshape(b,c,h*w) # b,c,hw
|
| 191 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
| 192 |
+
w_ = w_ * (int(c)**(-0.5))
|
| 193 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
| 194 |
+
|
| 195 |
+
# attend to values
|
| 196 |
+
v = v.reshape(b,c,h*w)
|
| 197 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
| 198 |
+
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
| 199 |
+
h_ = h_.reshape(b,c,h,w)
|
| 200 |
+
|
| 201 |
+
h_ = self.proj_out(h_)
|
| 202 |
+
|
| 203 |
+
return x+h_
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def make_attn(in_channels, attn_type="vanilla"):
|
| 207 |
+
assert attn_type in ["vanilla", "linear", "none"], f'attn_type {attn_type} unknown'
|
| 208 |
+
print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
|
| 209 |
+
if attn_type == "vanilla":
|
| 210 |
+
return AttnBlock(in_channels)
|
| 211 |
+
elif attn_type == "none":
|
| 212 |
+
return nn.Identity(in_channels)
|
| 213 |
+
else:
|
| 214 |
+
return LinAttnBlock(in_channels)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class Model(nn.Module):
|
| 218 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 219 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 220 |
+
resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
|
| 221 |
+
super().__init__()
|
| 222 |
+
if use_linear_attn: attn_type = "linear"
|
| 223 |
+
self.ch = ch
|
| 224 |
+
self.temb_ch = self.ch*4
|
| 225 |
+
self.num_resolutions = len(ch_mult)
|
| 226 |
+
self.num_res_blocks = num_res_blocks
|
| 227 |
+
self.resolution = resolution
|
| 228 |
+
self.in_channels = in_channels
|
| 229 |
+
|
| 230 |
+
self.use_timestep = use_timestep
|
| 231 |
+
if self.use_timestep:
|
| 232 |
+
# timestep embedding
|
| 233 |
+
self.temb = nn.Module()
|
| 234 |
+
self.temb.dense = nn.ModuleList([
|
| 235 |
+
torch.nn.Linear(self.ch,
|
| 236 |
+
self.temb_ch),
|
| 237 |
+
torch.nn.Linear(self.temb_ch,
|
| 238 |
+
self.temb_ch),
|
| 239 |
+
])
|
| 240 |
+
|
| 241 |
+
# downsampling
|
| 242 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
| 243 |
+
self.ch,
|
| 244 |
+
kernel_size=3,
|
| 245 |
+
stride=1,
|
| 246 |
+
padding=1)
|
| 247 |
+
|
| 248 |
+
curr_res = resolution
|
| 249 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 250 |
+
self.down = nn.ModuleList()
|
| 251 |
+
for i_level in range(self.num_resolutions):
|
| 252 |
+
block = nn.ModuleList()
|
| 253 |
+
attn = nn.ModuleList()
|
| 254 |
+
block_in = ch*in_ch_mult[i_level]
|
| 255 |
+
block_out = ch*ch_mult[i_level]
|
| 256 |
+
for i_block in range(self.num_res_blocks):
|
| 257 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 258 |
+
out_channels=block_out,
|
| 259 |
+
temb_channels=self.temb_ch,
|
| 260 |
+
dropout=dropout))
|
| 261 |
+
block_in = block_out
|
| 262 |
+
if curr_res in attn_resolutions:
|
| 263 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 264 |
+
down = nn.Module()
|
| 265 |
+
down.block = block
|
| 266 |
+
down.attn = attn
|
| 267 |
+
if i_level != self.num_resolutions-1:
|
| 268 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
| 269 |
+
curr_res = curr_res // 2
|
| 270 |
+
self.down.append(down)
|
| 271 |
+
|
| 272 |
+
# middle
|
| 273 |
+
self.mid = nn.Module()
|
| 274 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 275 |
+
out_channels=block_in,
|
| 276 |
+
temb_channels=self.temb_ch,
|
| 277 |
+
dropout=dropout)
|
| 278 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
| 279 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 280 |
+
out_channels=block_in,
|
| 281 |
+
temb_channels=self.temb_ch,
|
| 282 |
+
dropout=dropout)
|
| 283 |
+
|
| 284 |
+
# upsampling
|
| 285 |
+
self.up = nn.ModuleList()
|
| 286 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 287 |
+
block = nn.ModuleList()
|
| 288 |
+
attn = nn.ModuleList()
|
| 289 |
+
block_out = ch*ch_mult[i_level]
|
| 290 |
+
skip_in = ch*ch_mult[i_level]
|
| 291 |
+
for i_block in range(self.num_res_blocks+1):
|
| 292 |
+
if i_block == self.num_res_blocks:
|
| 293 |
+
skip_in = ch*in_ch_mult[i_level]
|
| 294 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
| 295 |
+
out_channels=block_out,
|
| 296 |
+
temb_channels=self.temb_ch,
|
| 297 |
+
dropout=dropout))
|
| 298 |
+
block_in = block_out
|
| 299 |
+
if curr_res in attn_resolutions:
|
| 300 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 301 |
+
up = nn.Module()
|
| 302 |
+
up.block = block
|
| 303 |
+
up.attn = attn
|
| 304 |
+
if i_level != 0:
|
| 305 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
| 306 |
+
curr_res = curr_res * 2
|
| 307 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 308 |
+
|
| 309 |
+
# end
|
| 310 |
+
self.norm_out = Normalize(block_in)
|
| 311 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 312 |
+
out_ch,
|
| 313 |
+
kernel_size=3,
|
| 314 |
+
stride=1,
|
| 315 |
+
padding=1)
|
| 316 |
+
|
| 317 |
+
def forward(self, x, t=None, context=None):
|
| 318 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
| 319 |
+
if context is not None:
|
| 320 |
+
# assume aligned context, cat along channel axis
|
| 321 |
+
x = torch.cat((x, context), dim=1)
|
| 322 |
+
if self.use_timestep:
|
| 323 |
+
# timestep embedding
|
| 324 |
+
assert t is not None
|
| 325 |
+
temb = get_timestep_embedding(t, self.ch)
|
| 326 |
+
temb = self.temb.dense[0](temb)
|
| 327 |
+
temb = nonlinearity(temb)
|
| 328 |
+
temb = self.temb.dense[1](temb)
|
| 329 |
+
else:
|
| 330 |
+
temb = None
|
| 331 |
+
|
| 332 |
+
# downsampling
|
| 333 |
+
hs = [self.conv_in(x)]
|
| 334 |
+
for i_level in range(self.num_resolutions):
|
| 335 |
+
for i_block in range(self.num_res_blocks):
|
| 336 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
| 337 |
+
if len(self.down[i_level].attn) > 0:
|
| 338 |
+
h = self.down[i_level].attn[i_block](h)
|
| 339 |
+
hs.append(h)
|
| 340 |
+
if i_level != self.num_resolutions-1:
|
| 341 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 342 |
+
|
| 343 |
+
# middle
|
| 344 |
+
h = hs[-1]
|
| 345 |
+
h = self.mid.block_1(h, temb)
|
| 346 |
+
h = self.mid.attn_1(h)
|
| 347 |
+
h = self.mid.block_2(h, temb)
|
| 348 |
+
|
| 349 |
+
# upsampling
|
| 350 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 351 |
+
for i_block in range(self.num_res_blocks+1):
|
| 352 |
+
h = self.up[i_level].block[i_block](
|
| 353 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
| 354 |
+
if len(self.up[i_level].attn) > 0:
|
| 355 |
+
h = self.up[i_level].attn[i_block](h)
|
| 356 |
+
if i_level != 0:
|
| 357 |
+
h = self.up[i_level].upsample(h)
|
| 358 |
+
|
| 359 |
+
# end
|
| 360 |
+
h = self.norm_out(h)
|
| 361 |
+
h = nonlinearity(h)
|
| 362 |
+
h = self.conv_out(h)
|
| 363 |
+
return h
|
| 364 |
+
|
| 365 |
+
def get_last_layer(self):
|
| 366 |
+
return self.conv_out.weight
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class Encoder(nn.Module):
|
| 370 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 371 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 372 |
+
resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
|
| 373 |
+
**ignore_kwargs):
|
| 374 |
+
super().__init__()
|
| 375 |
+
if use_linear_attn: attn_type = "linear"
|
| 376 |
+
self.ch = ch
|
| 377 |
+
self.temb_ch = 0
|
| 378 |
+
self.num_resolutions = len(ch_mult)
|
| 379 |
+
self.num_res_blocks = num_res_blocks
|
| 380 |
+
self.resolution = resolution
|
| 381 |
+
self.in_channels = in_channels
|
| 382 |
+
|
| 383 |
+
# downsampling
|
| 384 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
| 385 |
+
self.ch,
|
| 386 |
+
kernel_size=3,
|
| 387 |
+
stride=1,
|
| 388 |
+
padding=1)
|
| 389 |
+
|
| 390 |
+
curr_res = resolution
|
| 391 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 392 |
+
self.in_ch_mult = in_ch_mult
|
| 393 |
+
self.down = nn.ModuleList()
|
| 394 |
+
for i_level in range(self.num_resolutions):
|
| 395 |
+
block = nn.ModuleList()
|
| 396 |
+
attn = nn.ModuleList()
|
| 397 |
+
block_in = ch*in_ch_mult[i_level]
|
| 398 |
+
block_out = ch*ch_mult[i_level]
|
| 399 |
+
for i_block in range(self.num_res_blocks):
|
| 400 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 401 |
+
out_channels=block_out,
|
| 402 |
+
temb_channels=self.temb_ch,
|
| 403 |
+
dropout=dropout))
|
| 404 |
+
block_in = block_out
|
| 405 |
+
if curr_res in attn_resolutions:
|
| 406 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 407 |
+
down = nn.Module()
|
| 408 |
+
down.block = block
|
| 409 |
+
down.attn = attn
|
| 410 |
+
if i_level != self.num_resolutions-1:
|
| 411 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
| 412 |
+
curr_res = curr_res // 2
|
| 413 |
+
self.down.append(down)
|
| 414 |
+
|
| 415 |
+
# middle
|
| 416 |
+
self.mid = nn.Module()
|
| 417 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 418 |
+
out_channels=block_in,
|
| 419 |
+
temb_channels=self.temb_ch,
|
| 420 |
+
dropout=dropout)
|
| 421 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
| 422 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 423 |
+
out_channels=block_in,
|
| 424 |
+
temb_channels=self.temb_ch,
|
| 425 |
+
dropout=dropout)
|
| 426 |
+
|
| 427 |
+
# end
|
| 428 |
+
self.norm_out = Normalize(block_in)
|
| 429 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 430 |
+
2*z_channels if double_z else z_channels,
|
| 431 |
+
kernel_size=3,
|
| 432 |
+
stride=1,
|
| 433 |
+
padding=1)
|
| 434 |
+
|
| 435 |
+
def forward(self, x):
|
| 436 |
+
# timestep embedding
|
| 437 |
+
temb = None
|
| 438 |
+
|
| 439 |
+
# downsampling
|
| 440 |
+
hs = [self.conv_in(x)]
|
| 441 |
+
for i_level in range(self.num_resolutions):
|
| 442 |
+
for i_block in range(self.num_res_blocks):
|
| 443 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
| 444 |
+
if len(self.down[i_level].attn) > 0:
|
| 445 |
+
h = self.down[i_level].attn[i_block](h)
|
| 446 |
+
hs.append(h)
|
| 447 |
+
if i_level != self.num_resolutions-1:
|
| 448 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 449 |
+
|
| 450 |
+
# middle
|
| 451 |
+
h = hs[-1]
|
| 452 |
+
h = self.mid.block_1(h, temb)
|
| 453 |
+
h = self.mid.attn_1(h)
|
| 454 |
+
h = self.mid.block_2(h, temb)
|
| 455 |
+
|
| 456 |
+
# end
|
| 457 |
+
h = self.norm_out(h)
|
| 458 |
+
h = nonlinearity(h)
|
| 459 |
+
h = self.conv_out(h)
|
| 460 |
+
return h
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class Decoder(nn.Module):
|
| 464 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 465 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 466 |
+
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
|
| 467 |
+
attn_type="vanilla", **ignorekwargs):
|
| 468 |
+
super().__init__()
|
| 469 |
+
if use_linear_attn: attn_type = "linear"
|
| 470 |
+
self.ch = ch
|
| 471 |
+
self.temb_ch = 0
|
| 472 |
+
self.num_resolutions = len(ch_mult)
|
| 473 |
+
self.num_res_blocks = num_res_blocks
|
| 474 |
+
self.resolution = resolution
|
| 475 |
+
self.in_channels = in_channels
|
| 476 |
+
self.give_pre_end = give_pre_end
|
| 477 |
+
self.tanh_out = tanh_out
|
| 478 |
+
|
| 479 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
| 480 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 481 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
| 482 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
| 483 |
+
self.z_shape = (1,z_channels,curr_res,curr_res)
|
| 484 |
+
print("Working with z of shape {} = {} dimensions.".format(
|
| 485 |
+
self.z_shape, np.prod(self.z_shape)))
|
| 486 |
+
|
| 487 |
+
# z to block_in
|
| 488 |
+
self.conv_in = torch.nn.Conv2d(z_channels,
|
| 489 |
+
block_in,
|
| 490 |
+
kernel_size=3,
|
| 491 |
+
stride=1,
|
| 492 |
+
padding=1)
|
| 493 |
+
|
| 494 |
+
# middle
|
| 495 |
+
self.mid = nn.Module()
|
| 496 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 497 |
+
out_channels=block_in,
|
| 498 |
+
temb_channels=self.temb_ch,
|
| 499 |
+
dropout=dropout)
|
| 500 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
| 501 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 502 |
+
out_channels=block_in,
|
| 503 |
+
temb_channels=self.temb_ch,
|
| 504 |
+
dropout=dropout)
|
| 505 |
+
|
| 506 |
+
# upsampling
|
| 507 |
+
self.up = nn.ModuleList()
|
| 508 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 509 |
+
block = nn.ModuleList()
|
| 510 |
+
attn = nn.ModuleList()
|
| 511 |
+
block_out = ch*ch_mult[i_level]
|
| 512 |
+
for i_block in range(self.num_res_blocks+1):
|
| 513 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 514 |
+
out_channels=block_out,
|
| 515 |
+
temb_channels=self.temb_ch,
|
| 516 |
+
dropout=dropout))
|
| 517 |
+
block_in = block_out
|
| 518 |
+
if curr_res in attn_resolutions:
|
| 519 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 520 |
+
up = nn.Module()
|
| 521 |
+
up.block = block
|
| 522 |
+
up.attn = attn
|
| 523 |
+
if i_level != 0:
|
| 524 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
| 525 |
+
curr_res = curr_res * 2
|
| 526 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 527 |
+
|
| 528 |
+
# end
|
| 529 |
+
self.norm_out = Normalize(block_in)
|
| 530 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 531 |
+
out_ch,
|
| 532 |
+
kernel_size=3,
|
| 533 |
+
stride=1,
|
| 534 |
+
padding=1)
|
| 535 |
+
|
| 536 |
+
def forward(self, z):
|
| 537 |
+
#assert z.shape[1:] == self.z_shape[1:]
|
| 538 |
+
self.last_z_shape = z.shape
|
| 539 |
+
|
| 540 |
+
# timestep embedding
|
| 541 |
+
temb = None
|
| 542 |
+
|
| 543 |
+
# z to block_in
|
| 544 |
+
h = self.conv_in(z)
|
| 545 |
+
|
| 546 |
+
# middle
|
| 547 |
+
h = self.mid.block_1(h, temb)
|
| 548 |
+
h = self.mid.attn_1(h)
|
| 549 |
+
h = self.mid.block_2(h, temb)
|
| 550 |
+
|
| 551 |
+
# upsampling
|
| 552 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 553 |
+
for i_block in range(self.num_res_blocks+1):
|
| 554 |
+
h = self.up[i_level].block[i_block](h, temb)
|
| 555 |
+
if len(self.up[i_level].attn) > 0:
|
| 556 |
+
h = self.up[i_level].attn[i_block](h)
|
| 557 |
+
if i_level != 0:
|
| 558 |
+
h = self.up[i_level].upsample(h)
|
| 559 |
+
|
| 560 |
+
# end
|
| 561 |
+
if self.give_pre_end:
|
| 562 |
+
return h
|
| 563 |
+
|
| 564 |
+
h = self.norm_out(h)
|
| 565 |
+
h = nonlinearity(h)
|
| 566 |
+
h = self.conv_out(h)
|
| 567 |
+
if self.tanh_out:
|
| 568 |
+
h = torch.tanh(h)
|
| 569 |
+
return h
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
class SimpleDecoder(nn.Module):
|
| 573 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
| 574 |
+
super().__init__()
|
| 575 |
+
self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
|
| 576 |
+
ResnetBlock(in_channels=in_channels,
|
| 577 |
+
out_channels=2 * in_channels,
|
| 578 |
+
temb_channels=0, dropout=0.0),
|
| 579 |
+
ResnetBlock(in_channels=2 * in_channels,
|
| 580 |
+
out_channels=4 * in_channels,
|
| 581 |
+
temb_channels=0, dropout=0.0),
|
| 582 |
+
ResnetBlock(in_channels=4 * in_channels,
|
| 583 |
+
out_channels=2 * in_channels,
|
| 584 |
+
temb_channels=0, dropout=0.0),
|
| 585 |
+
nn.Conv2d(2*in_channels, in_channels, 1),
|
| 586 |
+
Upsample(in_channels, with_conv=True)])
|
| 587 |
+
# end
|
| 588 |
+
self.norm_out = Normalize(in_channels)
|
| 589 |
+
self.conv_out = torch.nn.Conv2d(in_channels,
|
| 590 |
+
out_channels,
|
| 591 |
+
kernel_size=3,
|
| 592 |
+
stride=1,
|
| 593 |
+
padding=1)
|
| 594 |
+
|
| 595 |
+
def forward(self, x):
|
| 596 |
+
for i, layer in enumerate(self.model):
|
| 597 |
+
if i in [1,2,3]:
|
| 598 |
+
x = layer(x, None)
|
| 599 |
+
else:
|
| 600 |
+
x = layer(x)
|
| 601 |
+
|
| 602 |
+
h = self.norm_out(x)
|
| 603 |
+
h = nonlinearity(h)
|
| 604 |
+
x = self.conv_out(h)
|
| 605 |
+
return x
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class UpsampleDecoder(nn.Module):
|
| 609 |
+
def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
|
| 610 |
+
ch_mult=(2,2), dropout=0.0):
|
| 611 |
+
super().__init__()
|
| 612 |
+
# upsampling
|
| 613 |
+
self.temb_ch = 0
|
| 614 |
+
self.num_resolutions = len(ch_mult)
|
| 615 |
+
self.num_res_blocks = num_res_blocks
|
| 616 |
+
block_in = in_channels
|
| 617 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
| 618 |
+
self.res_blocks = nn.ModuleList()
|
| 619 |
+
self.upsample_blocks = nn.ModuleList()
|
| 620 |
+
for i_level in range(self.num_resolutions):
|
| 621 |
+
res_block = []
|
| 622 |
+
block_out = ch * ch_mult[i_level]
|
| 623 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 624 |
+
res_block.append(ResnetBlock(in_channels=block_in,
|
| 625 |
+
out_channels=block_out,
|
| 626 |
+
temb_channels=self.temb_ch,
|
| 627 |
+
dropout=dropout))
|
| 628 |
+
block_in = block_out
|
| 629 |
+
self.res_blocks.append(nn.ModuleList(res_block))
|
| 630 |
+
if i_level != self.num_resolutions - 1:
|
| 631 |
+
self.upsample_blocks.append(Upsample(block_in, True))
|
| 632 |
+
curr_res = curr_res * 2
|
| 633 |
+
|
| 634 |
+
# end
|
| 635 |
+
self.norm_out = Normalize(block_in)
|
| 636 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 637 |
+
out_channels,
|
| 638 |
+
kernel_size=3,
|
| 639 |
+
stride=1,
|
| 640 |
+
padding=1)
|
| 641 |
+
|
| 642 |
+
def forward(self, x):
|
| 643 |
+
# upsampling
|
| 644 |
+
h = x
|
| 645 |
+
for k, i_level in enumerate(range(self.num_resolutions)):
|
| 646 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 647 |
+
h = self.res_blocks[i_level][i_block](h, None)
|
| 648 |
+
if i_level != self.num_resolutions - 1:
|
| 649 |
+
h = self.upsample_blocks[k](h)
|
| 650 |
+
h = self.norm_out(h)
|
| 651 |
+
h = nonlinearity(h)
|
| 652 |
+
h = self.conv_out(h)
|
| 653 |
+
return h
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
class LatentRescaler(nn.Module):
|
| 657 |
+
def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
|
| 658 |
+
super().__init__()
|
| 659 |
+
# residual block, interpolate, residual block
|
| 660 |
+
self.factor = factor
|
| 661 |
+
self.conv_in = nn.Conv2d(in_channels,
|
| 662 |
+
mid_channels,
|
| 663 |
+
kernel_size=3,
|
| 664 |
+
stride=1,
|
| 665 |
+
padding=1)
|
| 666 |
+
self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
| 667 |
+
out_channels=mid_channels,
|
| 668 |
+
temb_channels=0,
|
| 669 |
+
dropout=0.0) for _ in range(depth)])
|
| 670 |
+
self.attn = AttnBlock(mid_channels)
|
| 671 |
+
self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
| 672 |
+
out_channels=mid_channels,
|
| 673 |
+
temb_channels=0,
|
| 674 |
+
dropout=0.0) for _ in range(depth)])
|
| 675 |
+
|
| 676 |
+
self.conv_out = nn.Conv2d(mid_channels,
|
| 677 |
+
out_channels,
|
| 678 |
+
kernel_size=1,
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
def forward(self, x):
|
| 682 |
+
x = self.conv_in(x)
|
| 683 |
+
for block in self.res_block1:
|
| 684 |
+
x = block(x, None)
|
| 685 |
+
x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
|
| 686 |
+
x = self.attn(x)
|
| 687 |
+
for block in self.res_block2:
|
| 688 |
+
x = block(x, None)
|
| 689 |
+
x = self.conv_out(x)
|
| 690 |
+
return x
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
class MergedRescaleEncoder(nn.Module):
|
| 694 |
+
def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
|
| 695 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True,
|
| 696 |
+
ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
|
| 697 |
+
super().__init__()
|
| 698 |
+
intermediate_chn = ch * ch_mult[-1]
|
| 699 |
+
self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
|
| 700 |
+
z_channels=intermediate_chn, double_z=False, resolution=resolution,
|
| 701 |
+
attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
|
| 702 |
+
out_ch=None)
|
| 703 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
|
| 704 |
+
mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
|
| 705 |
+
|
| 706 |
+
def forward(self, x):
|
| 707 |
+
x = self.encoder(x)
|
| 708 |
+
x = self.rescaler(x)
|
| 709 |
+
return x
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
class MergedRescaleDecoder(nn.Module):
|
| 713 |
+
def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
|
| 714 |
+
dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
|
| 715 |
+
super().__init__()
|
| 716 |
+
tmp_chn = z_channels*ch_mult[-1]
|
| 717 |
+
self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
|
| 718 |
+
resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
|
| 719 |
+
ch_mult=ch_mult, resolution=resolution, ch=ch)
|
| 720 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
|
| 721 |
+
out_channels=tmp_chn, depth=rescale_module_depth)
|
| 722 |
+
|
| 723 |
+
def forward(self, x):
|
| 724 |
+
x = self.rescaler(x)
|
| 725 |
+
x = self.decoder(x)
|
| 726 |
+
return x
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
class Upsampler(nn.Module):
|
| 730 |
+
def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
|
| 731 |
+
super().__init__()
|
| 732 |
+
assert out_size >= in_size
|
| 733 |
+
num_blocks = int(np.log2(out_size//in_size))+1
|
| 734 |
+
factor_up = 1.+ (out_size % in_size)
|
| 735 |
+
print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
|
| 736 |
+
self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
|
| 737 |
+
out_channels=in_channels)
|
| 738 |
+
self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
|
| 739 |
+
attn_resolutions=[], in_channels=None, ch=in_channels,
|
| 740 |
+
ch_mult=[ch_mult for _ in range(num_blocks)])
|
| 741 |
+
|
| 742 |
+
def forward(self, x):
|
| 743 |
+
x = self.rescaler(x)
|
| 744 |
+
x = self.decoder(x)
|
| 745 |
+
return x
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class Resize(nn.Module):
|
| 749 |
+
def __init__(self, in_channels=None, learned=False, mode="bilinear"):
|
| 750 |
+
super().__init__()
|
| 751 |
+
self.with_conv = learned
|
| 752 |
+
self.mode = mode
|
| 753 |
+
if self.with_conv:
|
| 754 |
+
print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
|
| 755 |
+
raise NotImplementedError()
|
| 756 |
+
assert in_channels is not None
|
| 757 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 758 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 759 |
+
in_channels,
|
| 760 |
+
kernel_size=4,
|
| 761 |
+
stride=2,
|
| 762 |
+
padding=1)
|
| 763 |
+
|
| 764 |
+
def forward(self, x, scale_factor=1.0):
|
| 765 |
+
if scale_factor==1.0:
|
| 766 |
+
return x
|
| 767 |
+
else:
|
| 768 |
+
x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
|
| 769 |
+
return x
|
| 770 |
+
|
| 771 |
+
class FirstStagePostProcessor(nn.Module):
|
| 772 |
+
|
| 773 |
+
def __init__(self, ch_mult:list, in_channels,
|
| 774 |
+
pretrained_model:nn.Module=None,
|
| 775 |
+
reshape=False,
|
| 776 |
+
n_channels=None,
|
| 777 |
+
dropout=0.,
|
| 778 |
+
pretrained_config=None):
|
| 779 |
+
super().__init__()
|
| 780 |
+
if pretrained_config is None:
|
| 781 |
+
assert pretrained_model is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
| 782 |
+
self.pretrained_model = pretrained_model
|
| 783 |
+
else:
|
| 784 |
+
assert pretrained_config is not None, 'Either "pretrained_model" or "pretrained_config" must not be None'
|
| 785 |
+
self.instantiate_pretrained(pretrained_config)
|
| 786 |
+
|
| 787 |
+
self.do_reshape = reshape
|
| 788 |
+
|
| 789 |
+
if n_channels is None:
|
| 790 |
+
n_channels = self.pretrained_model.encoder.ch
|
| 791 |
+
|
| 792 |
+
self.proj_norm = Normalize(in_channels,num_groups=in_channels//2)
|
| 793 |
+
self.proj = nn.Conv2d(in_channels,n_channels,kernel_size=3,
|
| 794 |
+
stride=1,padding=1)
|
| 795 |
+
|
| 796 |
+
blocks = []
|
| 797 |
+
downs = []
|
| 798 |
+
ch_in = n_channels
|
| 799 |
+
for m in ch_mult:
|
| 800 |
+
blocks.append(ResnetBlock(in_channels=ch_in,out_channels=m*n_channels,dropout=dropout))
|
| 801 |
+
ch_in = m * n_channels
|
| 802 |
+
downs.append(Downsample(ch_in, with_conv=False))
|
| 803 |
+
|
| 804 |
+
self.model = nn.ModuleList(blocks)
|
| 805 |
+
self.downsampler = nn.ModuleList(downs)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def instantiate_pretrained(self, config):
|
| 809 |
+
model = instantiate_from_config(config)
|
| 810 |
+
self.pretrained_model = model.eval()
|
| 811 |
+
# self.pretrained_model.train = False
|
| 812 |
+
for param in self.pretrained_model.parameters():
|
| 813 |
+
param.requires_grad = False
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
@torch.no_grad()
|
| 817 |
+
def encode_with_pretrained(self,x):
|
| 818 |
+
c = self.pretrained_model.encode(x)
|
| 819 |
+
if isinstance(c, DiagonalGaussianDistribution):
|
| 820 |
+
c = c.mode()
|
| 821 |
+
return c
|
| 822 |
+
|
| 823 |
+
def forward(self,x):
|
| 824 |
+
z_fs = self.encode_with_pretrained(x)
|
| 825 |
+
z = self.proj_norm(z_fs)
|
| 826 |
+
z = self.proj(z)
|
| 827 |
+
z = nonlinearity(z)
|
| 828 |
+
|
| 829 |
+
for submodel, downmodel in zip(self.model,self.downsampler):
|
| 830 |
+
z = submodel(z,temb=None)
|
| 831 |
+
z = downmodel(z)
|
| 832 |
+
|
| 833 |
+
if self.do_reshape:
|
| 834 |
+
z = rearrange(z,'b c h w -> b (h w) c')
|
| 835 |
+
return z
|
instructany2pix/llm/model/vae/modules/blocks_spec.py
ADDED
|
@@ -0,0 +1,999 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pytorch_diffusion + derived encoder decoder
|
| 2 |
+
import math
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_timestep_embedding(timesteps, embedding_dim):
|
| 9 |
+
"""
|
| 10 |
+
This matches the implementation in Denoising Diffusion Probabilistic Models:
|
| 11 |
+
From Fairseq.
|
| 12 |
+
Build sinusoidal embeddings.
|
| 13 |
+
This matches the implementation in tensor2tensor, but differs slightly
|
| 14 |
+
from the description in Section 3.5 of "Attention Is All You Need".
|
| 15 |
+
"""
|
| 16 |
+
assert len(timesteps.shape) == 1
|
| 17 |
+
|
| 18 |
+
half_dim = embedding_dim // 2
|
| 19 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 20 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
|
| 21 |
+
emb = emb.to(device=timesteps.device)
|
| 22 |
+
emb = timesteps.float()[:, None] * emb[None, :]
|
| 23 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 24 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 25 |
+
emb = torch.nn.functional.pad(emb, (0,1,0,0))
|
| 26 |
+
return emb
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def nonlinearity(x):
|
| 30 |
+
# swish
|
| 31 |
+
return x*torch.sigmoid(x)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def Normalize(in_channels):
|
| 35 |
+
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
|
| 36 |
+
|
| 37 |
+
class Upsample(nn.Module):
|
| 38 |
+
def __init__(self, in_channels, with_conv):
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.with_conv = with_conv
|
| 41 |
+
if self.with_conv:
|
| 42 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 43 |
+
in_channels,
|
| 44 |
+
kernel_size=3,
|
| 45 |
+
stride=1,
|
| 46 |
+
padding=1)
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
| 50 |
+
if self.with_conv:
|
| 51 |
+
x = self.conv(x)
|
| 52 |
+
return x
|
| 53 |
+
|
| 54 |
+
class Upsample1d(Upsample):
|
| 55 |
+
def __init__(self, in_channels, with_conv):
|
| 56 |
+
super().__init__(in_channels, with_conv)
|
| 57 |
+
if self.with_conv:
|
| 58 |
+
self.conv = torch.nn.Conv1d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
|
| 59 |
+
|
| 60 |
+
class Downsample(nn.Module):
|
| 61 |
+
def __init__(self, in_channels, with_conv):
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.with_conv = with_conv
|
| 64 |
+
if self.with_conv:
|
| 65 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 66 |
+
self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
|
| 67 |
+
self.pad = (0, 1, 0, 1)
|
| 68 |
+
else:
|
| 69 |
+
self.avg_pool = nn.AvgPool2d(kernel_size=2, stride=2)
|
| 70 |
+
|
| 71 |
+
def forward(self, x):
|
| 72 |
+
if self.with_conv: # bp: check self.avgpool and self.pad
|
| 73 |
+
x = torch.nn.functional.pad(x, self.pad, mode="constant", value=0)
|
| 74 |
+
x = self.conv(x)
|
| 75 |
+
else:
|
| 76 |
+
x = self.avg_pool(x)
|
| 77 |
+
return x
|
| 78 |
+
|
| 79 |
+
class Downsample1d(Downsample):
|
| 80 |
+
|
| 81 |
+
def __init__(self, in_channels, with_conv):
|
| 82 |
+
super().__init__(in_channels, with_conv)
|
| 83 |
+
if self.with_conv:
|
| 84 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 85 |
+
# TODO: can we replace it just with conv2d with padding 1?
|
| 86 |
+
self.conv = torch.nn.Conv1d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
|
| 87 |
+
self.pad = (1, 1)
|
| 88 |
+
else:
|
| 89 |
+
self.avg_pool = nn.AvgPool1d(kernel_size=2, stride=2)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class ResnetBlock(nn.Module):
|
| 93 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
| 94 |
+
dropout, temb_channels=512):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.in_channels = in_channels
|
| 97 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 98 |
+
self.out_channels = out_channels
|
| 99 |
+
self.use_conv_shortcut = conv_shortcut
|
| 100 |
+
|
| 101 |
+
self.norm1 = Normalize(in_channels)
|
| 102 |
+
self.conv1 = torch.nn.Conv2d(in_channels,
|
| 103 |
+
out_channels,
|
| 104 |
+
kernel_size=3,
|
| 105 |
+
stride=1,
|
| 106 |
+
padding=1)
|
| 107 |
+
if temb_channels > 0:
|
| 108 |
+
self.temb_proj = torch.nn.Linear(temb_channels,
|
| 109 |
+
out_channels)
|
| 110 |
+
self.norm2 = Normalize(out_channels)
|
| 111 |
+
self.dropout = torch.nn.Dropout(dropout)
|
| 112 |
+
self.conv2 = torch.nn.Conv2d(out_channels,
|
| 113 |
+
out_channels,
|
| 114 |
+
kernel_size=3,
|
| 115 |
+
stride=1,
|
| 116 |
+
padding=1)
|
| 117 |
+
if self.in_channels != self.out_channels:
|
| 118 |
+
if self.use_conv_shortcut:
|
| 119 |
+
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
| 120 |
+
out_channels,
|
| 121 |
+
kernel_size=3,
|
| 122 |
+
stride=1,
|
| 123 |
+
padding=1)
|
| 124 |
+
else:
|
| 125 |
+
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
| 126 |
+
out_channels,
|
| 127 |
+
kernel_size=1,
|
| 128 |
+
stride=1,
|
| 129 |
+
padding=0)
|
| 130 |
+
|
| 131 |
+
def forward(self, x, temb):
|
| 132 |
+
h = x
|
| 133 |
+
h = self.norm1(h)
|
| 134 |
+
h = nonlinearity(h)
|
| 135 |
+
h = self.conv1(h)
|
| 136 |
+
|
| 137 |
+
if temb is not None:
|
| 138 |
+
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
|
| 139 |
+
|
| 140 |
+
h = self.norm2(h)
|
| 141 |
+
h = nonlinearity(h)
|
| 142 |
+
h = self.dropout(h)
|
| 143 |
+
h = self.conv2(h)
|
| 144 |
+
|
| 145 |
+
if self.in_channels != self.out_channels:
|
| 146 |
+
if self.use_conv_shortcut:
|
| 147 |
+
x = self.conv_shortcut(x)
|
| 148 |
+
else:
|
| 149 |
+
x = self.nin_shortcut(x)
|
| 150 |
+
|
| 151 |
+
return x+h
|
| 152 |
+
|
| 153 |
+
class ResnetBlock1d(ResnetBlock):
|
| 154 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
| 155 |
+
dropout, temb_channels=512):
|
| 156 |
+
super().__init__(in_channels=in_channels, out_channels=out_channels,
|
| 157 |
+
conv_shortcut=conv_shortcut, dropout=dropout, temb_channels=temb_channels)
|
| 158 |
+
# redefining different elements (forward is goint to be the same as in RenetBlock)
|
| 159 |
+
if temb_channels > 0:
|
| 160 |
+
raise NotImplementedError('go to ResnetBlock and figure out how to deal with it in forward')
|
| 161 |
+
self.temb_proj = torch.nn.Linear(temb_channels, out_channels)
|
| 162 |
+
|
| 163 |
+
self.conv1 = torch.nn.Conv1d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 164 |
+
self.conv2 = torch.nn.Conv1d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)
|
| 165 |
+
if self.in_channels != self.out_channels:
|
| 166 |
+
if self.use_conv_shortcut:
|
| 167 |
+
self.conv_shortcut = torch.nn.Conv1d(in_channels, out_channels, kernel_size=3,
|
| 168 |
+
stride=1, padding=1)
|
| 169 |
+
else:
|
| 170 |
+
self.nin_shortcut = torch.nn.Conv1d(in_channels, out_channels, kernel_size=1,
|
| 171 |
+
stride=1, padding=0)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class AttnBlock(nn.Module):
|
| 175 |
+
def __init__(self, in_channels):
|
| 176 |
+
super().__init__()
|
| 177 |
+
self.in_channels = in_channels
|
| 178 |
+
|
| 179 |
+
self.norm = Normalize(in_channels)
|
| 180 |
+
self.q = torch.nn.Conv2d(in_channels,
|
| 181 |
+
in_channels,
|
| 182 |
+
kernel_size=1,
|
| 183 |
+
stride=1,
|
| 184 |
+
padding=0)
|
| 185 |
+
self.k = torch.nn.Conv2d(in_channels,
|
| 186 |
+
in_channels,
|
| 187 |
+
kernel_size=1,
|
| 188 |
+
stride=1,
|
| 189 |
+
padding=0)
|
| 190 |
+
self.v = torch.nn.Conv2d(in_channels,
|
| 191 |
+
in_channels,
|
| 192 |
+
kernel_size=1,
|
| 193 |
+
stride=1,
|
| 194 |
+
padding=0)
|
| 195 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
| 196 |
+
in_channels,
|
| 197 |
+
kernel_size=1,
|
| 198 |
+
stride=1,
|
| 199 |
+
padding=0)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def forward(self, x):
|
| 203 |
+
h_ = x
|
| 204 |
+
h_ = self.norm(h_)
|
| 205 |
+
q = self.q(h_)
|
| 206 |
+
k = self.k(h_)
|
| 207 |
+
v = self.v(h_)
|
| 208 |
+
|
| 209 |
+
# compute attention
|
| 210 |
+
b,c,h,w = q.shape
|
| 211 |
+
q = q.reshape(b,c,h*w)
|
| 212 |
+
q = q.permute(0,2,1) # b,hw,c
|
| 213 |
+
k = k.reshape(b,c,h*w) # b,c,hw
|
| 214 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
| 215 |
+
w_ = w_ * (int(c)**(-0.5))
|
| 216 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
| 217 |
+
|
| 218 |
+
# attend to values
|
| 219 |
+
v = v.reshape(b,c,h*w)
|
| 220 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
| 221 |
+
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
| 222 |
+
h_ = h_.reshape(b,c,h,w)
|
| 223 |
+
|
| 224 |
+
h_ = self.proj_out(h_)
|
| 225 |
+
|
| 226 |
+
return x+h_
|
| 227 |
+
|
| 228 |
+
class AttnBlock1d(nn.Module):
|
| 229 |
+
|
| 230 |
+
def __init__(self, in_channels):
|
| 231 |
+
super().__init__()
|
| 232 |
+
self.in_channels = in_channels
|
| 233 |
+
|
| 234 |
+
self.norm = Normalize(in_channels)
|
| 235 |
+
self.q = torch.nn.Conv1d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 236 |
+
self.k = torch.nn.Conv1d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 237 |
+
self.v = torch.nn.Conv1d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 238 |
+
self.proj_out = torch.nn.Conv1d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
| 239 |
+
|
| 240 |
+
def forward(self, x):
|
| 241 |
+
h_ = x
|
| 242 |
+
h_ = self.norm(h_)
|
| 243 |
+
q = self.q(h_)
|
| 244 |
+
k = self.k(h_)
|
| 245 |
+
v = self.v(h_)
|
| 246 |
+
|
| 247 |
+
# compute attention
|
| 248 |
+
b, c, t = q.shape
|
| 249 |
+
q = q.permute(0, 2, 1) # b,t,c
|
| 250 |
+
w_ = torch.bmm(q, k) # b,t,t w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
| 251 |
+
w_ = w_ * (int(c) ** (-0.5))
|
| 252 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
| 253 |
+
|
| 254 |
+
# attend to values
|
| 255 |
+
w_ = w_.permute(0, 2, 1) # b,t,t (first t of k, second of q)
|
| 256 |
+
h_ = torch.bmm(v, w_) # b,c,t (t of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
| 257 |
+
|
| 258 |
+
h_ = self.proj_out(h_)
|
| 259 |
+
|
| 260 |
+
return x + h_
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class Model(nn.Module):
|
| 264 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 265 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 266 |
+
resolution, use_timestep=True):
|
| 267 |
+
super().__init__()
|
| 268 |
+
self.ch = ch
|
| 269 |
+
self.temb_ch = self.ch*4
|
| 270 |
+
self.num_resolutions = len(ch_mult)
|
| 271 |
+
self.num_res_blocks = num_res_blocks
|
| 272 |
+
self.resolution = resolution
|
| 273 |
+
self.in_channels = in_channels
|
| 274 |
+
|
| 275 |
+
self.use_timestep = use_timestep
|
| 276 |
+
if self.use_timestep:
|
| 277 |
+
# timestep embedding
|
| 278 |
+
self.temb = nn.Module()
|
| 279 |
+
self.temb.dense = nn.ModuleList([
|
| 280 |
+
torch.nn.Linear(self.ch,
|
| 281 |
+
self.temb_ch),
|
| 282 |
+
torch.nn.Linear(self.temb_ch,
|
| 283 |
+
self.temb_ch),
|
| 284 |
+
])
|
| 285 |
+
|
| 286 |
+
# downsampling
|
| 287 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
| 288 |
+
self.ch,
|
| 289 |
+
kernel_size=3,
|
| 290 |
+
stride=1,
|
| 291 |
+
padding=1)
|
| 292 |
+
|
| 293 |
+
curr_res = resolution
|
| 294 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 295 |
+
self.down = nn.ModuleList()
|
| 296 |
+
for i_level in range(self.num_resolutions):
|
| 297 |
+
block = nn.ModuleList()
|
| 298 |
+
attn = nn.ModuleList()
|
| 299 |
+
block_in = ch*in_ch_mult[i_level]
|
| 300 |
+
block_out = ch*ch_mult[i_level]
|
| 301 |
+
for i_block in range(self.num_res_blocks):
|
| 302 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 303 |
+
out_channels=block_out,
|
| 304 |
+
temb_channels=self.temb_ch,
|
| 305 |
+
dropout=dropout))
|
| 306 |
+
block_in = block_out
|
| 307 |
+
if curr_res in attn_resolutions:
|
| 308 |
+
attn.append(AttnBlock(block_in))
|
| 309 |
+
down = nn.Module()
|
| 310 |
+
down.block = block
|
| 311 |
+
down.attn = attn
|
| 312 |
+
if i_level != self.num_resolutions-1:
|
| 313 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
| 314 |
+
curr_res = curr_res // 2
|
| 315 |
+
self.down.append(down)
|
| 316 |
+
|
| 317 |
+
# middle
|
| 318 |
+
self.mid = nn.Module()
|
| 319 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 320 |
+
out_channels=block_in,
|
| 321 |
+
temb_channels=self.temb_ch,
|
| 322 |
+
dropout=dropout)
|
| 323 |
+
self.mid.attn_1 = AttnBlock(block_in)
|
| 324 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 325 |
+
out_channels=block_in,
|
| 326 |
+
temb_channels=self.temb_ch,
|
| 327 |
+
dropout=dropout)
|
| 328 |
+
|
| 329 |
+
# upsampling
|
| 330 |
+
self.up = nn.ModuleList()
|
| 331 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 332 |
+
block = nn.ModuleList()
|
| 333 |
+
attn = nn.ModuleList()
|
| 334 |
+
block_out = ch*ch_mult[i_level]
|
| 335 |
+
skip_in = ch*ch_mult[i_level]
|
| 336 |
+
for i_block in range(self.num_res_blocks+1):
|
| 337 |
+
if i_block == self.num_res_blocks:
|
| 338 |
+
skip_in = ch*in_ch_mult[i_level]
|
| 339 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
| 340 |
+
out_channels=block_out,
|
| 341 |
+
temb_channels=self.temb_ch,
|
| 342 |
+
dropout=dropout))
|
| 343 |
+
block_in = block_out
|
| 344 |
+
if curr_res in attn_resolutions:
|
| 345 |
+
attn.append(AttnBlock(block_in))
|
| 346 |
+
up = nn.Module()
|
| 347 |
+
up.block = block
|
| 348 |
+
up.attn = attn
|
| 349 |
+
if i_level != 0:
|
| 350 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
| 351 |
+
curr_res = curr_res * 2
|
| 352 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 353 |
+
|
| 354 |
+
# end
|
| 355 |
+
self.norm_out = Normalize(block_in)
|
| 356 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 357 |
+
out_ch,
|
| 358 |
+
kernel_size=3,
|
| 359 |
+
stride=1,
|
| 360 |
+
padding=1)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def forward(self, x, t=None):
|
| 364 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
| 365 |
+
|
| 366 |
+
if self.use_timestep:
|
| 367 |
+
# timestep embedding
|
| 368 |
+
assert t is not None
|
| 369 |
+
temb = get_timestep_embedding(t, self.ch)
|
| 370 |
+
temb = self.temb.dense[0](temb)
|
| 371 |
+
temb = nonlinearity(temb)
|
| 372 |
+
temb = self.temb.dense[1](temb)
|
| 373 |
+
else:
|
| 374 |
+
temb = None
|
| 375 |
+
|
| 376 |
+
# downsampling
|
| 377 |
+
hs = [self.conv_in(x)]
|
| 378 |
+
for i_level in range(self.num_resolutions):
|
| 379 |
+
for i_block in range(self.num_res_blocks):
|
| 380 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
| 381 |
+
if len(self.down[i_level].attn) > 0:
|
| 382 |
+
h = self.down[i_level].attn[i_block](h)
|
| 383 |
+
hs.append(h)
|
| 384 |
+
if i_level != self.num_resolutions-1:
|
| 385 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 386 |
+
|
| 387 |
+
# middle
|
| 388 |
+
h = hs[-1]
|
| 389 |
+
h = self.mid.block_1(h, temb)
|
| 390 |
+
h = self.mid.attn_1(h)
|
| 391 |
+
h = self.mid.block_2(h, temb)
|
| 392 |
+
|
| 393 |
+
# upsampling
|
| 394 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 395 |
+
for i_block in range(self.num_res_blocks+1):
|
| 396 |
+
h = self.up[i_level].block[i_block](
|
| 397 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
| 398 |
+
if len(self.up[i_level].attn) > 0:
|
| 399 |
+
h = self.up[i_level].attn[i_block](h)
|
| 400 |
+
if i_level != 0:
|
| 401 |
+
h = self.up[i_level].upsample(h)
|
| 402 |
+
|
| 403 |
+
# end
|
| 404 |
+
h = self.norm_out(h)
|
| 405 |
+
h = nonlinearity(h)
|
| 406 |
+
h = self.conv_out(h)
|
| 407 |
+
return h
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class Encoder(nn.Module):
|
| 411 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 412 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 413 |
+
resolution, z_channels, double_z=True, **ignore_kwargs):
|
| 414 |
+
super().__init__()
|
| 415 |
+
self.ch = ch
|
| 416 |
+
self.temb_ch = 0
|
| 417 |
+
self.num_resolutions = len(ch_mult)
|
| 418 |
+
self.num_res_blocks = num_res_blocks
|
| 419 |
+
self.resolution = resolution
|
| 420 |
+
self.in_channels = in_channels
|
| 421 |
+
|
| 422 |
+
# downsampling
|
| 423 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
| 424 |
+
self.ch,
|
| 425 |
+
kernel_size=3,
|
| 426 |
+
stride=1,
|
| 427 |
+
padding=1)
|
| 428 |
+
|
| 429 |
+
curr_res = resolution
|
| 430 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 431 |
+
self.down = nn.ModuleList()
|
| 432 |
+
for i_level in range(self.num_resolutions):
|
| 433 |
+
block = nn.ModuleList()
|
| 434 |
+
attn = nn.ModuleList()
|
| 435 |
+
block_in = ch*in_ch_mult[i_level]
|
| 436 |
+
block_out = ch*ch_mult[i_level]
|
| 437 |
+
for i_block in range(self.num_res_blocks):
|
| 438 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 439 |
+
out_channels=block_out,
|
| 440 |
+
temb_channels=self.temb_ch,
|
| 441 |
+
dropout=dropout))
|
| 442 |
+
block_in = block_out
|
| 443 |
+
if curr_res in attn_resolutions:
|
| 444 |
+
attn.append(AttnBlock(block_in))
|
| 445 |
+
down = nn.Module()
|
| 446 |
+
down.block = block
|
| 447 |
+
down.attn = attn
|
| 448 |
+
if i_level != self.num_resolutions-1:
|
| 449 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
| 450 |
+
curr_res = curr_res // 2
|
| 451 |
+
self.down.append(down)
|
| 452 |
+
|
| 453 |
+
# middle
|
| 454 |
+
self.mid = nn.Module()
|
| 455 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 456 |
+
out_channels=block_in,
|
| 457 |
+
temb_channels=self.temb_ch,
|
| 458 |
+
dropout=dropout)
|
| 459 |
+
self.mid.attn_1 = AttnBlock(block_in)
|
| 460 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 461 |
+
out_channels=block_in,
|
| 462 |
+
temb_channels=self.temb_ch,
|
| 463 |
+
dropout=dropout)
|
| 464 |
+
|
| 465 |
+
# end
|
| 466 |
+
self.norm_out = Normalize(block_in)
|
| 467 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 468 |
+
2*z_channels if double_z else z_channels,
|
| 469 |
+
kernel_size=3,
|
| 470 |
+
stride=1,
|
| 471 |
+
padding=1)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def forward(self, x):
|
| 475 |
+
#assert x.shape[2] == x.shape[3] == self.resolution, "{}, {}, {}".format(x.shape[2], x.shape[3], self.resolution)
|
| 476 |
+
|
| 477 |
+
# timestep embedding
|
| 478 |
+
temb = None
|
| 479 |
+
|
| 480 |
+
# downsampling
|
| 481 |
+
hs = [self.conv_in(x)]
|
| 482 |
+
for i_level in range(self.num_resolutions):
|
| 483 |
+
for i_block in range(self.num_res_blocks):
|
| 484 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
| 485 |
+
if len(self.down[i_level].attn) > 0:
|
| 486 |
+
h = self.down[i_level].attn[i_block](h)
|
| 487 |
+
hs.append(h)
|
| 488 |
+
if i_level != self.num_resolutions-1:
|
| 489 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 490 |
+
|
| 491 |
+
# middle
|
| 492 |
+
h = hs[-1]
|
| 493 |
+
h = self.mid.block_1(h, temb)
|
| 494 |
+
h = self.mid.attn_1(h)
|
| 495 |
+
h = self.mid.block_2(h, temb)
|
| 496 |
+
|
| 497 |
+
# end
|
| 498 |
+
h = self.norm_out(h)
|
| 499 |
+
h = nonlinearity(h)
|
| 500 |
+
h = self.conv_out(h)
|
| 501 |
+
return h
|
| 502 |
+
|
| 503 |
+
class Encoder1d(Encoder):
|
| 504 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 505 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 506 |
+
resolution, z_channels, double_z=True, **ignore_kwargs):
|
| 507 |
+
super().__init__(ch=ch, out_ch=out_ch, ch_mult=ch_mult, num_res_blocks=num_res_blocks,
|
| 508 |
+
attn_resolutions=attn_resolutions, dropout=dropout,
|
| 509 |
+
resamp_with_conv=resamp_with_conv,
|
| 510 |
+
in_channels=in_channels, resolution=resolution, z_channels=z_channels,
|
| 511 |
+
double_z=double_z, **ignore_kwargs)
|
| 512 |
+
self.ch = ch
|
| 513 |
+
self.temb_ch = 0
|
| 514 |
+
self.num_resolutions = len(ch_mult)
|
| 515 |
+
self.num_res_blocks = num_res_blocks
|
| 516 |
+
self.resolution = resolution
|
| 517 |
+
self.in_channels = in_channels
|
| 518 |
+
|
| 519 |
+
# downsampling
|
| 520 |
+
self.conv_in = torch.nn.Conv1d(in_channels,
|
| 521 |
+
self.ch,
|
| 522 |
+
kernel_size=3,
|
| 523 |
+
stride=1,
|
| 524 |
+
padding=1)
|
| 525 |
+
|
| 526 |
+
curr_res = resolution
|
| 527 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 528 |
+
self.down = nn.ModuleList()
|
| 529 |
+
for i_level in range(self.num_resolutions):
|
| 530 |
+
block = nn.ModuleList()
|
| 531 |
+
attn = nn.ModuleList()
|
| 532 |
+
block_in = ch*in_ch_mult[i_level]
|
| 533 |
+
block_out = ch*ch_mult[i_level]
|
| 534 |
+
for i_block in range(self.num_res_blocks):
|
| 535 |
+
block.append(ResnetBlock1d(in_channels=block_in,
|
| 536 |
+
out_channels=block_out,
|
| 537 |
+
temb_channels=self.temb_ch,
|
| 538 |
+
dropout=dropout))
|
| 539 |
+
block_in = block_out
|
| 540 |
+
if curr_res in attn_resolutions:
|
| 541 |
+
attn.append(AttnBlock1d(block_in))
|
| 542 |
+
down = nn.Module()
|
| 543 |
+
down.block = block
|
| 544 |
+
down.attn = attn
|
| 545 |
+
if i_level != self.num_resolutions-1:
|
| 546 |
+
down.downsample = Downsample1d(block_in, resamp_with_conv)
|
| 547 |
+
curr_res = curr_res // 2
|
| 548 |
+
self.down.append(down)
|
| 549 |
+
|
| 550 |
+
# middle
|
| 551 |
+
self.mid = nn.Module()
|
| 552 |
+
self.mid.block_1 = ResnetBlock1d(in_channels=block_in,
|
| 553 |
+
out_channels=block_in,
|
| 554 |
+
temb_channels=self.temb_ch,
|
| 555 |
+
dropout=dropout)
|
| 556 |
+
self.mid.attn_1 = AttnBlock1d(block_in)
|
| 557 |
+
self.mid.block_2 = ResnetBlock1d(in_channels=block_in,
|
| 558 |
+
out_channels=block_in,
|
| 559 |
+
temb_channels=self.temb_ch,
|
| 560 |
+
dropout=dropout)
|
| 561 |
+
|
| 562 |
+
# end
|
| 563 |
+
self.norm_out = Normalize(block_in)
|
| 564 |
+
self.conv_out = torch.nn.Conv1d(block_in,
|
| 565 |
+
2*z_channels if double_z else z_channels,
|
| 566 |
+
kernel_size=3,
|
| 567 |
+
stride=1,
|
| 568 |
+
padding=1)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
class Decoder(nn.Module):
|
| 572 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 573 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 574 |
+
resolution, z_channels, give_pre_end=False, **ignorekwargs):
|
| 575 |
+
super().__init__()
|
| 576 |
+
self.ch = ch
|
| 577 |
+
self.temb_ch = 0
|
| 578 |
+
self.num_resolutions = len(ch_mult)
|
| 579 |
+
self.num_res_blocks = num_res_blocks
|
| 580 |
+
self.resolution = resolution
|
| 581 |
+
self.in_channels = in_channels
|
| 582 |
+
self.give_pre_end = give_pre_end
|
| 583 |
+
|
| 584 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
| 585 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 586 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
| 587 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
| 588 |
+
# self.z_shape = (1,z_channels,curr_res,curr_res)
|
| 589 |
+
# print("Working with z of shape {} = {} dimensions.".format(
|
| 590 |
+
# self.z_shape, np.prod(self.z_shape)))
|
| 591 |
+
|
| 592 |
+
# z to block_in
|
| 593 |
+
self.conv_in = torch.nn.Conv2d(z_channels,
|
| 594 |
+
block_in,
|
| 595 |
+
kernel_size=3,
|
| 596 |
+
stride=1,
|
| 597 |
+
padding=1)
|
| 598 |
+
|
| 599 |
+
# middle
|
| 600 |
+
self.mid = nn.Module()
|
| 601 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 602 |
+
out_channels=block_in,
|
| 603 |
+
temb_channels=self.temb_ch,
|
| 604 |
+
dropout=dropout)
|
| 605 |
+
self.mid.attn_1 = AttnBlock(block_in)
|
| 606 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 607 |
+
out_channels=block_in,
|
| 608 |
+
temb_channels=self.temb_ch,
|
| 609 |
+
dropout=dropout)
|
| 610 |
+
|
| 611 |
+
# upsampling
|
| 612 |
+
self.up = nn.ModuleList()
|
| 613 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 614 |
+
block = nn.ModuleList()
|
| 615 |
+
attn = nn.ModuleList()
|
| 616 |
+
block_out = ch*ch_mult[i_level]
|
| 617 |
+
for i_block in range(self.num_res_blocks+1):
|
| 618 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 619 |
+
out_channels=block_out,
|
| 620 |
+
temb_channels=self.temb_ch,
|
| 621 |
+
dropout=dropout))
|
| 622 |
+
block_in = block_out
|
| 623 |
+
if curr_res in attn_resolutions:
|
| 624 |
+
attn.append(AttnBlock(block_in))
|
| 625 |
+
up = nn.Module()
|
| 626 |
+
up.block = block
|
| 627 |
+
up.attn = attn
|
| 628 |
+
if i_level != 0:
|
| 629 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
| 630 |
+
curr_res = curr_res * 2
|
| 631 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 632 |
+
|
| 633 |
+
# end
|
| 634 |
+
self.norm_out = Normalize(block_in)
|
| 635 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 636 |
+
out_ch,
|
| 637 |
+
kernel_size=3,
|
| 638 |
+
stride=1,
|
| 639 |
+
padding=1)
|
| 640 |
+
|
| 641 |
+
def forward(self, z):
|
| 642 |
+
#assert z.shape[1:] == self.z_shape[1:]
|
| 643 |
+
self.last_z_shape = z.shape
|
| 644 |
+
|
| 645 |
+
# timestep embedding
|
| 646 |
+
temb = None
|
| 647 |
+
|
| 648 |
+
# z to block_in
|
| 649 |
+
h = self.conv_in(z)
|
| 650 |
+
|
| 651 |
+
# middle
|
| 652 |
+
h = self.mid.block_1(h, temb)
|
| 653 |
+
h = self.mid.attn_1(h)
|
| 654 |
+
h = self.mid.block_2(h, temb)
|
| 655 |
+
|
| 656 |
+
# upsampling
|
| 657 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 658 |
+
for i_block in range(self.num_res_blocks+1):
|
| 659 |
+
h = self.up[i_level].block[i_block](h, temb)
|
| 660 |
+
if len(self.up[i_level].attn) > 0:
|
| 661 |
+
h = self.up[i_level].attn[i_block](h)
|
| 662 |
+
if i_level != 0:
|
| 663 |
+
h = self.up[i_level].upsample(h)
|
| 664 |
+
|
| 665 |
+
# end
|
| 666 |
+
if self.give_pre_end:
|
| 667 |
+
return h
|
| 668 |
+
|
| 669 |
+
h = self.norm_out(h)
|
| 670 |
+
h = nonlinearity(h)
|
| 671 |
+
h = self.conv_out(h)
|
| 672 |
+
return h
|
| 673 |
+
|
| 674 |
+
class Decoder1d(Decoder):
|
| 675 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 676 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 677 |
+
resolution, z_channels, give_pre_end=False, **ignorekwargs):
|
| 678 |
+
super().__init__(ch=ch, out_ch=out_ch, ch_mult=ch_mult, num_res_blocks=num_res_blocks,
|
| 679 |
+
attn_resolutions=attn_resolutions, dropout=dropout,
|
| 680 |
+
resamp_with_conv=resamp_with_conv,
|
| 681 |
+
in_channels=in_channels, resolution=resolution, z_channels=z_channels,
|
| 682 |
+
give_pre_end=give_pre_end, **ignorekwargs)
|
| 683 |
+
self.ch = ch
|
| 684 |
+
self.temb_ch = 0
|
| 685 |
+
self.num_resolutions = len(ch_mult)
|
| 686 |
+
self.num_res_blocks = num_res_blocks
|
| 687 |
+
self.resolution = resolution
|
| 688 |
+
self.in_channels = in_channels
|
| 689 |
+
self.give_pre_end = give_pre_end
|
| 690 |
+
|
| 691 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
| 692 |
+
in_ch_mult = (1,) + tuple(ch_mult)
|
| 693 |
+
block_in = ch * ch_mult[self.num_resolutions-1]
|
| 694 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
| 695 |
+
# self.z_shape = (1,z_channels,curr_res,curr_res)
|
| 696 |
+
# print("Working with z of shape {} = {} dimensions.".format(
|
| 697 |
+
# self.z_shape, np.prod(self.z_shape)))
|
| 698 |
+
|
| 699 |
+
# z to block_in
|
| 700 |
+
self.conv_in = torch.nn.Conv1d(z_channels, block_in, kernel_size=3, stride=1, padding=1)
|
| 701 |
+
|
| 702 |
+
# middle
|
| 703 |
+
self.mid = nn.Module()
|
| 704 |
+
self.mid.block_1 = ResnetBlock1d(in_channels=block_in, out_channels=block_in,
|
| 705 |
+
temb_channels=self.temb_ch, dropout=dropout)
|
| 706 |
+
self.mid.attn_1 = AttnBlock1d(block_in)
|
| 707 |
+
self.mid.block_2 = ResnetBlock1d(in_channels=block_in, out_channels=block_in,
|
| 708 |
+
temb_channels=self.temb_ch, dropout=dropout)
|
| 709 |
+
|
| 710 |
+
# upsampling
|
| 711 |
+
self.up = nn.ModuleList()
|
| 712 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 713 |
+
block = nn.ModuleList()
|
| 714 |
+
attn = nn.ModuleList()
|
| 715 |
+
block_out = ch * ch_mult[i_level]
|
| 716 |
+
for i_block in range(self.num_res_blocks+1):
|
| 717 |
+
block.append(ResnetBlock1d(in_channels=block_in, out_channels=block_out,
|
| 718 |
+
temb_channels=self.temb_ch, dropout=dropout))
|
| 719 |
+
block_in = block_out
|
| 720 |
+
if curr_res in attn_resolutions:
|
| 721 |
+
attn.append(AttnBlock1d(block_in))
|
| 722 |
+
up = nn.Module()
|
| 723 |
+
up.block = block
|
| 724 |
+
up.attn = attn
|
| 725 |
+
if i_level != 0:
|
| 726 |
+
up.upsample = Upsample1d(block_in, resamp_with_conv)
|
| 727 |
+
curr_res = curr_res * 2
|
| 728 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 729 |
+
|
| 730 |
+
# end
|
| 731 |
+
self.norm_out = Normalize(block_in)
|
| 732 |
+
self.conv_out = torch.nn.Conv1d(block_in, out_ch, kernel_size=3, stride=1, padding=1)
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
class VUNet(nn.Module):
|
| 736 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 737 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True,
|
| 738 |
+
in_channels, c_channels,
|
| 739 |
+
resolution, z_channels, use_timestep=False, **ignore_kwargs):
|
| 740 |
+
super().__init__()
|
| 741 |
+
self.ch = ch
|
| 742 |
+
self.temb_ch = self.ch*4
|
| 743 |
+
self.num_resolutions = len(ch_mult)
|
| 744 |
+
self.num_res_blocks = num_res_blocks
|
| 745 |
+
self.resolution = resolution
|
| 746 |
+
|
| 747 |
+
self.use_timestep = use_timestep
|
| 748 |
+
if self.use_timestep:
|
| 749 |
+
# timestep embedding
|
| 750 |
+
self.temb = nn.Module()
|
| 751 |
+
self.temb.dense = nn.ModuleList([
|
| 752 |
+
torch.nn.Linear(self.ch,
|
| 753 |
+
self.temb_ch),
|
| 754 |
+
torch.nn.Linear(self.temb_ch,
|
| 755 |
+
self.temb_ch),
|
| 756 |
+
])
|
| 757 |
+
|
| 758 |
+
# downsampling
|
| 759 |
+
self.conv_in = torch.nn.Conv2d(c_channels,
|
| 760 |
+
self.ch,
|
| 761 |
+
kernel_size=3,
|
| 762 |
+
stride=1,
|
| 763 |
+
padding=1)
|
| 764 |
+
|
| 765 |
+
curr_res = resolution
|
| 766 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 767 |
+
self.down = nn.ModuleList()
|
| 768 |
+
for i_level in range(self.num_resolutions):
|
| 769 |
+
block = nn.ModuleList()
|
| 770 |
+
attn = nn.ModuleList()
|
| 771 |
+
block_in = ch*in_ch_mult[i_level]
|
| 772 |
+
block_out = ch*ch_mult[i_level]
|
| 773 |
+
for i_block in range(self.num_res_blocks):
|
| 774 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 775 |
+
out_channels=block_out,
|
| 776 |
+
temb_channels=self.temb_ch,
|
| 777 |
+
dropout=dropout))
|
| 778 |
+
block_in = block_out
|
| 779 |
+
if curr_res in attn_resolutions:
|
| 780 |
+
attn.append(AttnBlock(block_in))
|
| 781 |
+
down = nn.Module()
|
| 782 |
+
down.block = block
|
| 783 |
+
down.attn = attn
|
| 784 |
+
if i_level != self.num_resolutions-1:
|
| 785 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
| 786 |
+
curr_res = curr_res // 2
|
| 787 |
+
self.down.append(down)
|
| 788 |
+
|
| 789 |
+
self.z_in = torch.nn.Conv2d(z_channels,
|
| 790 |
+
block_in,
|
| 791 |
+
kernel_size=1,
|
| 792 |
+
stride=1,
|
| 793 |
+
padding=0)
|
| 794 |
+
# middle
|
| 795 |
+
self.mid = nn.Module()
|
| 796 |
+
self.mid.block_1 = ResnetBlock(in_channels=2*block_in,
|
| 797 |
+
out_channels=block_in,
|
| 798 |
+
temb_channels=self.temb_ch,
|
| 799 |
+
dropout=dropout)
|
| 800 |
+
self.mid.attn_1 = AttnBlock(block_in)
|
| 801 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 802 |
+
out_channels=block_in,
|
| 803 |
+
temb_channels=self.temb_ch,
|
| 804 |
+
dropout=dropout)
|
| 805 |
+
|
| 806 |
+
# upsampling
|
| 807 |
+
self.up = nn.ModuleList()
|
| 808 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 809 |
+
block = nn.ModuleList()
|
| 810 |
+
attn = nn.ModuleList()
|
| 811 |
+
block_out = ch*ch_mult[i_level]
|
| 812 |
+
skip_in = ch*ch_mult[i_level]
|
| 813 |
+
for i_block in range(self.num_res_blocks+1):
|
| 814 |
+
if i_block == self.num_res_blocks:
|
| 815 |
+
skip_in = ch*in_ch_mult[i_level]
|
| 816 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
| 817 |
+
out_channels=block_out,
|
| 818 |
+
temb_channels=self.temb_ch,
|
| 819 |
+
dropout=dropout))
|
| 820 |
+
block_in = block_out
|
| 821 |
+
if curr_res in attn_resolutions:
|
| 822 |
+
attn.append(AttnBlock(block_in))
|
| 823 |
+
up = nn.Module()
|
| 824 |
+
up.block = block
|
| 825 |
+
up.attn = attn
|
| 826 |
+
if i_level != 0:
|
| 827 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
| 828 |
+
curr_res = curr_res * 2
|
| 829 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 830 |
+
|
| 831 |
+
# end
|
| 832 |
+
self.norm_out = Normalize(block_in)
|
| 833 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 834 |
+
out_ch,
|
| 835 |
+
kernel_size=3,
|
| 836 |
+
stride=1,
|
| 837 |
+
padding=1)
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
def forward(self, x, z):
|
| 841 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
| 842 |
+
|
| 843 |
+
if self.use_timestep:
|
| 844 |
+
# timestep embedding
|
| 845 |
+
assert t is not None
|
| 846 |
+
temb = get_timestep_embedding(t, self.ch)
|
| 847 |
+
temb = self.temb.dense[0](temb)
|
| 848 |
+
temb = nonlinearity(temb)
|
| 849 |
+
temb = self.temb.dense[1](temb)
|
| 850 |
+
else:
|
| 851 |
+
temb = None
|
| 852 |
+
|
| 853 |
+
# downsampling
|
| 854 |
+
hs = [self.conv_in(x)]
|
| 855 |
+
for i_level in range(self.num_resolutions):
|
| 856 |
+
for i_block in range(self.num_res_blocks):
|
| 857 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
| 858 |
+
if len(self.down[i_level].attn) > 0:
|
| 859 |
+
h = self.down[i_level].attn[i_block](h)
|
| 860 |
+
hs.append(h)
|
| 861 |
+
if i_level != self.num_resolutions-1:
|
| 862 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 863 |
+
|
| 864 |
+
# middle
|
| 865 |
+
h = hs[-1]
|
| 866 |
+
z = self.z_in(z)
|
| 867 |
+
h = torch.cat((h,z),dim=1)
|
| 868 |
+
h = self.mid.block_1(h, temb)
|
| 869 |
+
h = self.mid.attn_1(h)
|
| 870 |
+
h = self.mid.block_2(h, temb)
|
| 871 |
+
|
| 872 |
+
# upsampling
|
| 873 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 874 |
+
for i_block in range(self.num_res_blocks+1):
|
| 875 |
+
h = self.up[i_level].block[i_block](
|
| 876 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
| 877 |
+
if len(self.up[i_level].attn) > 0:
|
| 878 |
+
h = self.up[i_level].attn[i_block](h)
|
| 879 |
+
if i_level != 0:
|
| 880 |
+
h = self.up[i_level].upsample(h)
|
| 881 |
+
|
| 882 |
+
# end
|
| 883 |
+
h = self.norm_out(h)
|
| 884 |
+
h = nonlinearity(h)
|
| 885 |
+
h = self.conv_out(h)
|
| 886 |
+
return h
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
class SimpleDecoder(nn.Module):
|
| 890 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
| 891 |
+
super().__init__()
|
| 892 |
+
self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
|
| 893 |
+
ResnetBlock(in_channels=in_channels,
|
| 894 |
+
out_channels=2 * in_channels,
|
| 895 |
+
temb_channels=0, dropout=0.0),
|
| 896 |
+
ResnetBlock(in_channels=2 * in_channels,
|
| 897 |
+
out_channels=4 * in_channels,
|
| 898 |
+
temb_channels=0, dropout=0.0),
|
| 899 |
+
ResnetBlock(in_channels=4 * in_channels,
|
| 900 |
+
out_channels=2 * in_channels,
|
| 901 |
+
temb_channels=0, dropout=0.0),
|
| 902 |
+
nn.Conv2d(2*in_channels, in_channels, 1),
|
| 903 |
+
Upsample(in_channels, with_conv=True)])
|
| 904 |
+
# end
|
| 905 |
+
self.norm_out = Normalize(in_channels)
|
| 906 |
+
self.conv_out = torch.nn.Conv2d(in_channels,
|
| 907 |
+
out_channels,
|
| 908 |
+
kernel_size=3,
|
| 909 |
+
stride=1,
|
| 910 |
+
padding=1)
|
| 911 |
+
|
| 912 |
+
def forward(self, x):
|
| 913 |
+
for i, layer in enumerate(self.model):
|
| 914 |
+
if i in [1,2,3]:
|
| 915 |
+
x = layer(x, None)
|
| 916 |
+
else:
|
| 917 |
+
x = layer(x)
|
| 918 |
+
|
| 919 |
+
h = self.norm_out(x)
|
| 920 |
+
h = nonlinearity(h)
|
| 921 |
+
x = self.conv_out(h)
|
| 922 |
+
return x
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
class UpsampleDecoder(nn.Module):
|
| 926 |
+
def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
|
| 927 |
+
ch_mult=(2,2), dropout=0.0):
|
| 928 |
+
super().__init__()
|
| 929 |
+
# upsampling
|
| 930 |
+
self.temb_ch = 0
|
| 931 |
+
self.num_resolutions = len(ch_mult)
|
| 932 |
+
self.num_res_blocks = num_res_blocks
|
| 933 |
+
block_in = in_channels
|
| 934 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
| 935 |
+
self.res_blocks = nn.ModuleList()
|
| 936 |
+
self.upsample_blocks = nn.ModuleList()
|
| 937 |
+
for i_level in range(self.num_resolutions):
|
| 938 |
+
res_block = []
|
| 939 |
+
block_out = ch * ch_mult[i_level]
|
| 940 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 941 |
+
res_block.append(ResnetBlock(in_channels=block_in,
|
| 942 |
+
out_channels=block_out,
|
| 943 |
+
temb_channels=self.temb_ch,
|
| 944 |
+
dropout=dropout))
|
| 945 |
+
block_in = block_out
|
| 946 |
+
self.res_blocks.append(nn.ModuleList(res_block))
|
| 947 |
+
if i_level != self.num_resolutions - 1:
|
| 948 |
+
self.upsample_blocks.append(Upsample(block_in, True))
|
| 949 |
+
curr_res = curr_res * 2
|
| 950 |
+
|
| 951 |
+
# end
|
| 952 |
+
self.norm_out = Normalize(block_in)
|
| 953 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 954 |
+
out_channels,
|
| 955 |
+
kernel_size=3,
|
| 956 |
+
stride=1,
|
| 957 |
+
padding=1)
|
| 958 |
+
|
| 959 |
+
def forward(self, x):
|
| 960 |
+
# upsampling
|
| 961 |
+
h = x
|
| 962 |
+
for k, i_level in enumerate(range(self.num_resolutions)):
|
| 963 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 964 |
+
h = self.res_blocks[i_level][i_block](h, None)
|
| 965 |
+
if i_level != self.num_resolutions - 1:
|
| 966 |
+
h = self.upsample_blocks[k](h)
|
| 967 |
+
h = self.norm_out(h)
|
| 968 |
+
h = nonlinearity(h)
|
| 969 |
+
h = self.conv_out(h)
|
| 970 |
+
return h
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
if __name__ == '__main__':
|
| 974 |
+
ddconfig = {
|
| 975 |
+
'ch': 128,
|
| 976 |
+
'num_res_blocks': 2,
|
| 977 |
+
'dropout': 0.0,
|
| 978 |
+
'z_channels': 256,
|
| 979 |
+
'double_z': False,
|
| 980 |
+
}
|
| 981 |
+
|
| 982 |
+
# Audio example ##
|
| 983 |
+
ddconfig['in_channels'] = 1
|
| 984 |
+
ddconfig['resolution'] = 848
|
| 985 |
+
ddconfig['attn_resolutions'] = [53]
|
| 986 |
+
ddconfig['ch_mult'] = [1, 1, 2, 2, 4]
|
| 987 |
+
ddconfig['out_ch'] = 1
|
| 988 |
+
# input
|
| 989 |
+
inputs = torch.rand(4, 1, 80, 848)
|
| 990 |
+
print('Input:', inputs.shape)
|
| 991 |
+
# Encoder
|
| 992 |
+
encoder = Encoder(**ddconfig)
|
| 993 |
+
enc_outs = encoder(inputs)
|
| 994 |
+
print('Encoder out:', enc_outs.shape)
|
| 995 |
+
# Decoder
|
| 996 |
+
decoder = Decoder(**ddconfig)
|
| 997 |
+
quant_outs = torch.rand(4, 256, 5, 53)
|
| 998 |
+
dec_outs = decoder(quant_outs)
|
| 999 |
+
print('Decoder out:', dec_outs.shape)
|
instructany2pix/llm/model/vae/modules/discriminator_spec.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class ActNorm(nn.Module):
|
| 6 |
+
def __init__(self, num_features, logdet=False, affine=True,
|
| 7 |
+
allow_reverse_init=False):
|
| 8 |
+
assert affine
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.logdet = logdet
|
| 11 |
+
self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1))
|
| 12 |
+
self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1))
|
| 13 |
+
self.allow_reverse_init = allow_reverse_init
|
| 14 |
+
|
| 15 |
+
self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))
|
| 16 |
+
|
| 17 |
+
def initialize(self, input):
|
| 18 |
+
with torch.no_grad():
|
| 19 |
+
flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1)
|
| 20 |
+
mean = (
|
| 21 |
+
flatten.mean(1)
|
| 22 |
+
.unsqueeze(1)
|
| 23 |
+
.unsqueeze(2)
|
| 24 |
+
.unsqueeze(3)
|
| 25 |
+
.permute(1, 0, 2, 3)
|
| 26 |
+
)
|
| 27 |
+
std = (
|
| 28 |
+
flatten.std(1)
|
| 29 |
+
.unsqueeze(1)
|
| 30 |
+
.unsqueeze(2)
|
| 31 |
+
.unsqueeze(3)
|
| 32 |
+
.permute(1, 0, 2, 3)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
self.loc.data.copy_(-mean)
|
| 36 |
+
self.scale.data.copy_(1 / (std + 1e-6))
|
| 37 |
+
|
| 38 |
+
def forward(self, input, reverse=False):
|
| 39 |
+
if reverse:
|
| 40 |
+
return self.reverse(input)
|
| 41 |
+
if len(input.shape) == 2:
|
| 42 |
+
input = input[:, :, None, None]
|
| 43 |
+
squeeze = True
|
| 44 |
+
else:
|
| 45 |
+
squeeze = False
|
| 46 |
+
|
| 47 |
+
_, _, height, width = input.shape
|
| 48 |
+
|
| 49 |
+
if self.training and self.initialized.item() == 0:
|
| 50 |
+
self.initialize(input)
|
| 51 |
+
self.initialized.fill_(1)
|
| 52 |
+
|
| 53 |
+
h = self.scale * (input + self.loc)
|
| 54 |
+
|
| 55 |
+
if squeeze:
|
| 56 |
+
h = h.squeeze(-1).squeeze(-1)
|
| 57 |
+
|
| 58 |
+
if self.logdet:
|
| 59 |
+
log_abs = torch.log(torch.abs(self.scale))
|
| 60 |
+
logdet = height * width * torch.sum(log_abs)
|
| 61 |
+
logdet = logdet * torch.ones(input.shape[0]).to(input)
|
| 62 |
+
return h, logdet
|
| 63 |
+
|
| 64 |
+
return h
|
| 65 |
+
|
| 66 |
+
def reverse(self, output):
|
| 67 |
+
if self.training and self.initialized.item() == 0:
|
| 68 |
+
if not self.allow_reverse_init:
|
| 69 |
+
raise RuntimeError(
|
| 70 |
+
"Initializing ActNorm in reverse direction is "
|
| 71 |
+
"disabled by default. Use allow_reverse_init=True to enable."
|
| 72 |
+
)
|
| 73 |
+
else:
|
| 74 |
+
self.initialize(output)
|
| 75 |
+
self.initialized.fill_(1)
|
| 76 |
+
|
| 77 |
+
if len(output.shape) == 2:
|
| 78 |
+
output = output[:, :, None, None]
|
| 79 |
+
squeeze = True
|
| 80 |
+
else:
|
| 81 |
+
squeeze = False
|
| 82 |
+
|
| 83 |
+
h = output / self.scale - self.loc
|
| 84 |
+
|
| 85 |
+
if squeeze:
|
| 86 |
+
h = h.squeeze(-1).squeeze(-1)
|
| 87 |
+
return h
|
| 88 |
+
|
| 89 |
+
def weights_init(m):
|
| 90 |
+
classname = m.__class__.__name__
|
| 91 |
+
if classname.find('Conv') != -1:
|
| 92 |
+
nn.init.normal_(m.weight.data, 0.0, 0.02)
|
| 93 |
+
elif classname.find('BatchNorm') != -1:
|
| 94 |
+
nn.init.normal_(m.weight.data, 1.0, 0.02)
|
| 95 |
+
nn.init.constant_(m.bias.data, 0)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class NLayerDiscriminator(nn.Module):
|
| 99 |
+
"""Defines a PatchGAN discriminator as in Pix2Pix
|
| 100 |
+
--> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
|
| 101 |
+
"""
|
| 102 |
+
def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
|
| 103 |
+
"""Construct a PatchGAN discriminator
|
| 104 |
+
Parameters:
|
| 105 |
+
input_nc (int) -- the number of channels in input images
|
| 106 |
+
ndf (int) -- the number of filters in the last conv layer
|
| 107 |
+
n_layers (int) -- the number of conv layers in the discriminator
|
| 108 |
+
norm_layer -- normalization layer
|
| 109 |
+
"""
|
| 110 |
+
super(NLayerDiscriminator, self).__init__()
|
| 111 |
+
if not use_actnorm:
|
| 112 |
+
norm_layer = nn.BatchNorm2d
|
| 113 |
+
else:
|
| 114 |
+
norm_layer = ActNorm
|
| 115 |
+
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
|
| 116 |
+
use_bias = norm_layer.func != nn.BatchNorm2d
|
| 117 |
+
else:
|
| 118 |
+
use_bias = norm_layer != nn.BatchNorm2d
|
| 119 |
+
|
| 120 |
+
kw = 4
|
| 121 |
+
padw = 1
|
| 122 |
+
sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
|
| 123 |
+
nf_mult = 1
|
| 124 |
+
nf_mult_prev = 1
|
| 125 |
+
for n in range(1, n_layers): # gradually increase the number of filters
|
| 126 |
+
nf_mult_prev = nf_mult
|
| 127 |
+
nf_mult = min(2 ** n, 8)
|
| 128 |
+
sequence += [
|
| 129 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
|
| 130 |
+
norm_layer(ndf * nf_mult),
|
| 131 |
+
nn.LeakyReLU(0.2, True)
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
nf_mult_prev = nf_mult
|
| 135 |
+
nf_mult = min(2 ** n_layers, 8)
|
| 136 |
+
sequence += [
|
| 137 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
|
| 138 |
+
norm_layer(ndf * nf_mult),
|
| 139 |
+
nn.LeakyReLU(0.2, True)
|
| 140 |
+
]
|
| 141 |
+
# output 1 channel prediction map
|
| 142 |
+
sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]
|
| 143 |
+
self.main = nn.Sequential(*sequence)
|
| 144 |
+
|
| 145 |
+
def forward(self, input):
|
| 146 |
+
"""Standard forward."""
|
| 147 |
+
return self.main(input)
|
| 148 |
+
|
| 149 |
+
class NLayerDiscriminator1dFeats(NLayerDiscriminator):
|
| 150 |
+
"""Defines a PatchGAN discriminator as in Pix2Pix
|
| 151 |
+
--> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
|
| 152 |
+
"""
|
| 153 |
+
def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
|
| 154 |
+
"""Construct a PatchGAN discriminator
|
| 155 |
+
Parameters:
|
| 156 |
+
input_nc (int) -- the number of channels in input feats
|
| 157 |
+
ndf (int) -- the number of filters in the last conv layer
|
| 158 |
+
n_layers (int) -- the number of conv layers in the discriminator
|
| 159 |
+
norm_layer -- normalization layer
|
| 160 |
+
"""
|
| 161 |
+
super().__init__(input_nc=input_nc, ndf=64, n_layers=n_layers, use_actnorm=use_actnorm)
|
| 162 |
+
|
| 163 |
+
if not use_actnorm:
|
| 164 |
+
norm_layer = nn.BatchNorm1d
|
| 165 |
+
else:
|
| 166 |
+
norm_layer = ActNorm
|
| 167 |
+
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm has affine parameters
|
| 168 |
+
use_bias = norm_layer.func != nn.BatchNorm1d
|
| 169 |
+
else:
|
| 170 |
+
use_bias = norm_layer != nn.BatchNorm1d
|
| 171 |
+
|
| 172 |
+
kw = 4
|
| 173 |
+
padw = 1
|
| 174 |
+
sequence = [nn.Conv1d(input_nc, input_nc//2, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
|
| 175 |
+
nf_mult = input_nc//2
|
| 176 |
+
nf_mult_prev = 1
|
| 177 |
+
for n in range(1, n_layers): # gradually decrease the number of filters
|
| 178 |
+
nf_mult_prev = nf_mult
|
| 179 |
+
nf_mult = max(nf_mult_prev // (2 ** n), 8)
|
| 180 |
+
sequence += [
|
| 181 |
+
nn.Conv1d(nf_mult_prev, nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
|
| 182 |
+
norm_layer(nf_mult),
|
| 183 |
+
nn.LeakyReLU(0.2, True)
|
| 184 |
+
]
|
| 185 |
+
|
| 186 |
+
nf_mult_prev = nf_mult
|
| 187 |
+
nf_mult = max(nf_mult_prev // (2 ** n), 8)
|
| 188 |
+
sequence += [
|
| 189 |
+
nn.Conv1d(nf_mult_prev, nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
|
| 190 |
+
norm_layer(nf_mult),
|
| 191 |
+
nn.LeakyReLU(0.2, True)
|
| 192 |
+
]
|
| 193 |
+
nf_mult_prev = nf_mult
|
| 194 |
+
nf_mult = max(nf_mult_prev // (2 ** n), 8)
|
| 195 |
+
sequence += [
|
| 196 |
+
nn.Conv1d(nf_mult_prev, nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
|
| 197 |
+
norm_layer(nf_mult),
|
| 198 |
+
nn.LeakyReLU(0.2, True)
|
| 199 |
+
]
|
| 200 |
+
# output 1 channel prediction map
|
| 201 |
+
sequence += [nn.Conv1d(nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]
|
| 202 |
+
self.main = nn.Sequential(*sequence)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class NLayerDiscriminator1dSpecs(NLayerDiscriminator):
|
| 206 |
+
"""Defines a PatchGAN discriminator as in Pix2Pix
|
| 207 |
+
--> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
|
| 208 |
+
"""
|
| 209 |
+
def __init__(self, input_nc=80, ndf=64, n_layers=3, use_actnorm=False):
|
| 210 |
+
"""Construct a PatchGAN discriminator
|
| 211 |
+
Parameters:
|
| 212 |
+
input_nc (int) -- the number of channels in input specs
|
| 213 |
+
ndf (int) -- the number of filters in the last conv layer
|
| 214 |
+
n_layers (int) -- the number of conv layers in the discriminator
|
| 215 |
+
norm_layer -- normalization layer
|
| 216 |
+
"""
|
| 217 |
+
super().__init__(input_nc=input_nc, ndf=64, n_layers=n_layers, use_actnorm=use_actnorm)
|
| 218 |
+
|
| 219 |
+
if not use_actnorm:
|
| 220 |
+
norm_layer = nn.BatchNorm1d
|
| 221 |
+
else:
|
| 222 |
+
norm_layer = ActNorm
|
| 223 |
+
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm has affine parameters
|
| 224 |
+
use_bias = norm_layer.func != nn.BatchNorm1d
|
| 225 |
+
else:
|
| 226 |
+
use_bias = norm_layer != nn.BatchNorm1d
|
| 227 |
+
|
| 228 |
+
kw = 4
|
| 229 |
+
padw = 1
|
| 230 |
+
sequence = [nn.Conv1d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
|
| 231 |
+
nf_mult = 1
|
| 232 |
+
nf_mult_prev = 1
|
| 233 |
+
for n in range(1, n_layers): # gradually decrease the number of filters
|
| 234 |
+
nf_mult_prev = nf_mult
|
| 235 |
+
nf_mult = min(2 ** n, 8)
|
| 236 |
+
sequence += [
|
| 237 |
+
nn.Conv1d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
|
| 238 |
+
norm_layer(ndf * nf_mult),
|
| 239 |
+
nn.LeakyReLU(0.2, True)
|
| 240 |
+
]
|
| 241 |
+
|
| 242 |
+
nf_mult_prev = nf_mult
|
| 243 |
+
nf_mult = min(2 ** n_layers, 8)
|
| 244 |
+
sequence += [
|
| 245 |
+
nn.Conv1d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
|
| 246 |
+
norm_layer(ndf * nf_mult),
|
| 247 |
+
nn.LeakyReLU(0.2, True)
|
| 248 |
+
]
|
| 249 |
+
# output 1 channel prediction map
|
| 250 |
+
sequence += [nn.Conv1d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]
|
| 251 |
+
self.main = nn.Sequential(*sequence)
|
| 252 |
+
|
| 253 |
+
def forward(self, input):
|
| 254 |
+
"""Standard forward."""
|
| 255 |
+
# (B, C, L)
|
| 256 |
+
input = input.squeeze(1)
|
| 257 |
+
input = self.main(input)
|
| 258 |
+
return input
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
if __name__ == '__main__':
|
| 262 |
+
import torch
|
| 263 |
+
|
| 264 |
+
## FEATURES
|
| 265 |
+
disc_in_channels = 2048
|
| 266 |
+
disc_num_layers = 2
|
| 267 |
+
use_actnorm = False
|
| 268 |
+
disc_ndf = 64
|
| 269 |
+
discriminator = NLayerDiscriminator1dFeats(input_nc=disc_in_channels, n_layers=disc_num_layers,
|
| 270 |
+
use_actnorm=use_actnorm, ndf=disc_ndf).apply(weights_init)
|
| 271 |
+
inputs = torch.rand((6, 2048, 212))
|
| 272 |
+
outputs = discriminator(inputs)
|
| 273 |
+
print(outputs.shape)
|
| 274 |
+
|
| 275 |
+
## AUDIO
|
| 276 |
+
disc_in_channels = 1
|
| 277 |
+
disc_num_layers = 3
|
| 278 |
+
use_actnorm = False
|
| 279 |
+
disc_ndf = 64
|
| 280 |
+
discriminator = NLayerDiscriminator(input_nc=disc_in_channels, n_layers=disc_num_layers,
|
| 281 |
+
use_actnorm=use_actnorm, ndf=disc_ndf).apply(weights_init)
|
| 282 |
+
inputs = torch.rand((6, 1, 80, 848))
|
| 283 |
+
outputs = discriminator(inputs)
|
| 284 |
+
print(outputs.shape)
|
| 285 |
+
|
| 286 |
+
## IMAGE
|
| 287 |
+
disc_in_channels = 3
|
| 288 |
+
disc_num_layers = 3
|
| 289 |
+
use_actnorm = False
|
| 290 |
+
disc_ndf = 64
|
| 291 |
+
discriminator = NLayerDiscriminator(input_nc=disc_in_channels, n_layers=disc_num_layers,
|
| 292 |
+
use_actnorm=use_actnorm, ndf=disc_ndf).apply(weights_init)
|
| 293 |
+
inputs = torch.rand((6, 3, 256, 256))
|
| 294 |
+
outputs = discriminator(inputs)
|
| 295 |
+
print(outputs.shape)
|
instructany2pix/llm/model/vae/modules/distributions.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class AbstractDistribution:
|
| 6 |
+
def sample(self):
|
| 7 |
+
raise NotImplementedError()
|
| 8 |
+
|
| 9 |
+
def mode(self):
|
| 10 |
+
raise NotImplementedError()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class DiracDistribution(AbstractDistribution):
|
| 14 |
+
def __init__(self, value):
|
| 15 |
+
self.value = value
|
| 16 |
+
|
| 17 |
+
def sample(self):
|
| 18 |
+
return self.value
|
| 19 |
+
|
| 20 |
+
def mode(self):
|
| 21 |
+
return self.value
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DiagonalGaussianDistribution(object):
|
| 25 |
+
def __init__(self, parameters, deterministic=False):
|
| 26 |
+
self.parameters = parameters
|
| 27 |
+
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
|
| 28 |
+
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
|
| 29 |
+
self.deterministic = deterministic
|
| 30 |
+
self.std = torch.exp(0.5 * self.logvar)
|
| 31 |
+
self.var = torch.exp(self.logvar)
|
| 32 |
+
if self.deterministic:
|
| 33 |
+
self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
|
| 34 |
+
|
| 35 |
+
def sample(self):
|
| 36 |
+
x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
|
| 37 |
+
return x
|
| 38 |
+
|
| 39 |
+
def kl(self, other=None):
|
| 40 |
+
if self.deterministic:
|
| 41 |
+
return torch.Tensor([0.])
|
| 42 |
+
else:
|
| 43 |
+
if other is None:
|
| 44 |
+
return 0.5 * torch.sum(torch.pow(self.mean, 2)
|
| 45 |
+
+ self.var - 1.0 - self.logvar,
|
| 46 |
+
dim=[1, 2, 3])
|
| 47 |
+
else:
|
| 48 |
+
return 0.5 * torch.sum(
|
| 49 |
+
torch.pow(self.mean - other.mean, 2) / other.var
|
| 50 |
+
+ self.var / other.var - 1.0 - self.logvar + other.logvar,
|
| 51 |
+
dim=[1, 2, 3])
|
| 52 |
+
|
| 53 |
+
def nll(self, sample, dims=[1,2,3]):
|
| 54 |
+
if self.deterministic:
|
| 55 |
+
return torch.Tensor([0.])
|
| 56 |
+
logtwopi = np.log(2.0 * np.pi)
|
| 57 |
+
return 0.5 * torch.sum(
|
| 58 |
+
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
|
| 59 |
+
dim=dims)
|
| 60 |
+
|
| 61 |
+
def mode(self):
|
| 62 |
+
return self.mean
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def normal_kl(mean1, logvar1, mean2, logvar2):
|
| 66 |
+
"""
|
| 67 |
+
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
|
| 68 |
+
Compute the KL divergence between two gaussians.
|
| 69 |
+
Shapes are automatically broadcasted, so batches can be compared to
|
| 70 |
+
scalars, among other use cases.
|
| 71 |
+
"""
|
| 72 |
+
tensor = None
|
| 73 |
+
for obj in (mean1, logvar1, mean2, logvar2):
|
| 74 |
+
if isinstance(obj, torch.Tensor):
|
| 75 |
+
tensor = obj
|
| 76 |
+
break
|
| 77 |
+
assert tensor is not None, "at least one argument must be a Tensor"
|
| 78 |
+
|
| 79 |
+
# Force variances to be Tensors. Broadcasting helps convert scalars to
|
| 80 |
+
# Tensors, but it does not work for torch.exp().
|
| 81 |
+
logvar1, logvar2 = [
|
| 82 |
+
x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
|
| 83 |
+
for x in (logvar1, logvar2)
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
return 0.5 * (
|
| 87 |
+
-1.0
|
| 88 |
+
+ logvar2
|
| 89 |
+
- logvar1
|
| 90 |
+
+ torch.exp(logvar1 - logvar2)
|
| 91 |
+
+ ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
|
| 92 |
+
)
|