Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +4 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/modeling_tf_utils.cpython-310.pyc +3 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/modeling_utils.cpython-310.pyc +3 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/training_args.cpython-310.pyc +3 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/__pycache__/data_collator.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__init__.py +23 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/glue.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/language_modeling.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/squad.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/glue.py +161 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/language_modeling.py +530 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/squad.py +229 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp +40 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h +32 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu +156 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh +1467 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h +29 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh +1327 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/ms_deform_attn.h +61 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/vision.cpp +16 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/rwkv/wkv_cuda.cu +187 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/rwkv/wkv_cuda_bf16.cu +186 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/rwkv/wkv_op.cpp +66 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/yoso/common.h +10 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/modeling_flax_gptj.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/modeling_tf_gptj.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/modeling_flax_gptj.py +718 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/modeling_tf_gptj.py +1103 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc +3 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/utils/dummy_detectron2_objects.py +14 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/utils/model_parallel_utils.py +56 -0
- evalkit_internvl/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py +1511 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/animatediff/pipeline_animatediff.py +847 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__init__.py +49 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/convert_kandinsky3_unet.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/pipeline_kandinsky3.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/pipeline_kandinsky3_img2img.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/__init__.py +55 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/__pycache__/pipeline_leditspp_stable_diffusion_xl.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/__pycache__/pipeline_output.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +1505 -0
- evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +1797 -0
.gitattributes
CHANGED
|
@@ -593,3 +593,7 @@ evalkit_tf437/lib/python3.10/site-packages/decord.libs/libswscale-8e37dcfd.so.5.
|
|
| 593 |
evalkit_tf437/lib/python3.10/site-packages/decord.libs/libxcb-77222338.so.1.1.0 filter=lfs diff=lfs merge=lfs -text
|
| 594 |
evalkit_tf437/lib/python3.10/site-packages/decord.libs/libavfilter-1e2243e2.so.7.40.101 filter=lfs diff=lfs merge=lfs -text
|
| 595 |
evalkit_tf437/lib/python3.10/site-packages/decord.libs/libavdevice-bf61e037.so.58.5.100 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 593 |
evalkit_tf437/lib/python3.10/site-packages/decord.libs/libxcb-77222338.so.1.1.0 filter=lfs diff=lfs merge=lfs -text
|
| 594 |
evalkit_tf437/lib/python3.10/site-packages/decord.libs/libavfilter-1e2243e2.so.7.40.101 filter=lfs diff=lfs merge=lfs -text
|
| 595 |
evalkit_tf437/lib/python3.10/site-packages/decord.libs/libavdevice-bf61e037.so.58.5.100 filter=lfs diff=lfs merge=lfs -text
|
| 596 |
+
evalkit_internvl/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 597 |
+
evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/modeling_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 598 |
+
evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/training_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 599 |
+
evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/modeling_tf_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/modeling_tf_utils.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:35b1baebd8fd88e8cf8e5123672689d38375e18cc0723f7b0b428c097c6db7ab
|
| 3 |
+
size 105988
|
evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/modeling_utils.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b481c3d19da98ea8b9cb9bd3753734c18fd1934e2e075d2cfbe5c35db84afc40
|
| 3 |
+
size 153110
|
evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/training_args.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3d7f97e7277e151fd36345450d3f6bb6e9dda457de850e6aff018c6b93e5081f
|
| 3 |
+
size 109103
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/__pycache__/data_collator.cpython-310.pyc
ADDED
|
Binary file (46.5 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .glue import GlueDataset, GlueDataTrainingArguments
|
| 16 |
+
from .language_modeling import (
|
| 17 |
+
LineByLineTextDataset,
|
| 18 |
+
LineByLineWithRefDataset,
|
| 19 |
+
LineByLineWithSOPTextDataset,
|
| 20 |
+
TextDataset,
|
| 21 |
+
TextDatasetForNextSentencePrediction,
|
| 22 |
+
)
|
| 23 |
+
from .squad import SquadDataset, SquadDataTrainingArguments
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (549 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/glue.cpython-310.pyc
ADDED
|
Binary file (4.86 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/language_modeling.cpython-310.pyc
ADDED
|
Binary file (13 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/__pycache__/squad.cpython-310.pyc
ADDED
|
Binary file (6.35 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/glue.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 os
|
| 16 |
+
import time
|
| 17 |
+
import warnings
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from enum import Enum
|
| 20 |
+
from typing import List, Optional, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from filelock import FileLock
|
| 24 |
+
from torch.utils.data import Dataset
|
| 25 |
+
|
| 26 |
+
from ...tokenization_utils_base import PreTrainedTokenizerBase
|
| 27 |
+
from ...utils import logging
|
| 28 |
+
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
|
| 29 |
+
from ..processors.utils import InputFeatures
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class GlueDataTrainingArguments:
|
| 37 |
+
"""
|
| 38 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 39 |
+
|
| 40 |
+
Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command
|
| 41 |
+
line.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
task_name: str = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys())})
|
| 45 |
+
data_dir: str = field(
|
| 46 |
+
metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."}
|
| 47 |
+
)
|
| 48 |
+
max_seq_length: int = field(
|
| 49 |
+
default=128,
|
| 50 |
+
metadata={
|
| 51 |
+
"help": (
|
| 52 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 53 |
+
"than this will be truncated, sequences shorter will be padded."
|
| 54 |
+
)
|
| 55 |
+
},
|
| 56 |
+
)
|
| 57 |
+
overwrite_cache: bool = field(
|
| 58 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def __post_init__(self):
|
| 62 |
+
self.task_name = self.task_name.lower()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Split(Enum):
|
| 66 |
+
train = "train"
|
| 67 |
+
dev = "dev"
|
| 68 |
+
test = "test"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class GlueDataset(Dataset):
|
| 72 |
+
"""
|
| 73 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
args: GlueDataTrainingArguments
|
| 77 |
+
output_mode: str
|
| 78 |
+
features: List[InputFeatures]
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
args: GlueDataTrainingArguments,
|
| 83 |
+
tokenizer: PreTrainedTokenizerBase,
|
| 84 |
+
limit_length: Optional[int] = None,
|
| 85 |
+
mode: Union[str, Split] = Split.train,
|
| 86 |
+
cache_dir: Optional[str] = None,
|
| 87 |
+
):
|
| 88 |
+
warnings.warn(
|
| 89 |
+
"This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
|
| 90 |
+
"library. You can have a look at this example script for pointers: "
|
| 91 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py",
|
| 92 |
+
FutureWarning,
|
| 93 |
+
)
|
| 94 |
+
self.args = args
|
| 95 |
+
self.processor = glue_processors[args.task_name]()
|
| 96 |
+
self.output_mode = glue_output_modes[args.task_name]
|
| 97 |
+
if isinstance(mode, str):
|
| 98 |
+
try:
|
| 99 |
+
mode = Split[mode]
|
| 100 |
+
except KeyError:
|
| 101 |
+
raise KeyError("mode is not a valid split name")
|
| 102 |
+
# Load data features from cache or dataset file
|
| 103 |
+
cached_features_file = os.path.join(
|
| 104 |
+
cache_dir if cache_dir is not None else args.data_dir,
|
| 105 |
+
f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}",
|
| 106 |
+
)
|
| 107 |
+
label_list = self.processor.get_labels()
|
| 108 |
+
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
|
| 109 |
+
"RobertaTokenizer",
|
| 110 |
+
"RobertaTokenizerFast",
|
| 111 |
+
"XLMRobertaTokenizer",
|
| 112 |
+
"BartTokenizer",
|
| 113 |
+
"BartTokenizerFast",
|
| 114 |
+
):
|
| 115 |
+
# HACK(label indices are swapped in RoBERTa pretrained model)
|
| 116 |
+
label_list[1], label_list[2] = label_list[2], label_list[1]
|
| 117 |
+
self.label_list = label_list
|
| 118 |
+
|
| 119 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 120 |
+
# and the others will use the cache.
|
| 121 |
+
lock_path = cached_features_file + ".lock"
|
| 122 |
+
with FileLock(lock_path):
|
| 123 |
+
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
| 124 |
+
start = time.time()
|
| 125 |
+
self.features = torch.load(cached_features_file)
|
| 126 |
+
logger.info(
|
| 127 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 128 |
+
)
|
| 129 |
+
else:
|
| 130 |
+
logger.info(f"Creating features from dataset file at {args.data_dir}")
|
| 131 |
+
|
| 132 |
+
if mode == Split.dev:
|
| 133 |
+
examples = self.processor.get_dev_examples(args.data_dir)
|
| 134 |
+
elif mode == Split.test:
|
| 135 |
+
examples = self.processor.get_test_examples(args.data_dir)
|
| 136 |
+
else:
|
| 137 |
+
examples = self.processor.get_train_examples(args.data_dir)
|
| 138 |
+
if limit_length is not None:
|
| 139 |
+
examples = examples[:limit_length]
|
| 140 |
+
self.features = glue_convert_examples_to_features(
|
| 141 |
+
examples,
|
| 142 |
+
tokenizer,
|
| 143 |
+
max_length=args.max_seq_length,
|
| 144 |
+
label_list=label_list,
|
| 145 |
+
output_mode=self.output_mode,
|
| 146 |
+
)
|
| 147 |
+
start = time.time()
|
| 148 |
+
torch.save(self.features, cached_features_file)
|
| 149 |
+
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
|
| 150 |
+
logger.info(
|
| 151 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
def __len__(self):
|
| 155 |
+
return len(self.features)
|
| 156 |
+
|
| 157 |
+
def __getitem__(self, i) -> InputFeatures:
|
| 158 |
+
return self.features[i]
|
| 159 |
+
|
| 160 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 json
|
| 16 |
+
import os
|
| 17 |
+
import pickle
|
| 18 |
+
import random
|
| 19 |
+
import time
|
| 20 |
+
import warnings
|
| 21 |
+
from typing import Dict, List, Optional
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from filelock import FileLock
|
| 25 |
+
from torch.utils.data import Dataset
|
| 26 |
+
|
| 27 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 28 |
+
from ...utils import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
DEPRECATION_WARNING = (
|
| 35 |
+
"This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
|
| 36 |
+
"library. You can have a look at this example script for pointers: {0}"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TextDataset(Dataset):
|
| 41 |
+
"""
|
| 42 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
tokenizer: PreTrainedTokenizer,
|
| 48 |
+
file_path: str,
|
| 49 |
+
block_size: int,
|
| 50 |
+
overwrite_cache=False,
|
| 51 |
+
cache_dir: Optional[str] = None,
|
| 52 |
+
):
|
| 53 |
+
warnings.warn(
|
| 54 |
+
DEPRECATION_WARNING.format(
|
| 55 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 56 |
+
),
|
| 57 |
+
FutureWarning,
|
| 58 |
+
)
|
| 59 |
+
if os.path.isfile(file_path) is False:
|
| 60 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 61 |
+
|
| 62 |
+
block_size = block_size - tokenizer.num_special_tokens_to_add(pair=False)
|
| 63 |
+
|
| 64 |
+
directory, filename = os.path.split(file_path)
|
| 65 |
+
cached_features_file = os.path.join(
|
| 66 |
+
cache_dir if cache_dir is not None else directory,
|
| 67 |
+
f"cached_lm_{tokenizer.__class__.__name__}_{block_size}_{filename}",
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 71 |
+
# and the others will use the cache.
|
| 72 |
+
lock_path = cached_features_file + ".lock"
|
| 73 |
+
with FileLock(lock_path):
|
| 74 |
+
if os.path.exists(cached_features_file) and not overwrite_cache:
|
| 75 |
+
start = time.time()
|
| 76 |
+
with open(cached_features_file, "rb") as handle:
|
| 77 |
+
self.examples = pickle.load(handle)
|
| 78 |
+
logger.info(
|
| 79 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
else:
|
| 83 |
+
logger.info(f"Creating features from dataset file at {directory}")
|
| 84 |
+
|
| 85 |
+
self.examples = []
|
| 86 |
+
with open(file_path, encoding="utf-8") as f:
|
| 87 |
+
text = f.read()
|
| 88 |
+
|
| 89 |
+
tokenized_text = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(text))
|
| 90 |
+
|
| 91 |
+
for i in range(0, len(tokenized_text) - block_size + 1, block_size): # Truncate in block of block_size
|
| 92 |
+
self.examples.append(
|
| 93 |
+
tokenizer.build_inputs_with_special_tokens(tokenized_text[i : i + block_size])
|
| 94 |
+
)
|
| 95 |
+
# Note that we are losing the last truncated example here for the sake of simplicity (no padding)
|
| 96 |
+
# If your dataset is small, first you should look for a bigger one :-) and second you
|
| 97 |
+
# can change this behavior by adding (model specific) padding.
|
| 98 |
+
|
| 99 |
+
start = time.time()
|
| 100 |
+
with open(cached_features_file, "wb") as handle:
|
| 101 |
+
pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
| 102 |
+
logger.info(
|
| 103 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
def __len__(self):
|
| 107 |
+
return len(self.examples)
|
| 108 |
+
|
| 109 |
+
def __getitem__(self, i) -> torch.Tensor:
|
| 110 |
+
return torch.tensor(self.examples[i], dtype=torch.long)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class LineByLineTextDataset(Dataset):
|
| 114 |
+
"""
|
| 115 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int):
|
| 119 |
+
warnings.warn(
|
| 120 |
+
DEPRECATION_WARNING.format(
|
| 121 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 122 |
+
),
|
| 123 |
+
FutureWarning,
|
| 124 |
+
)
|
| 125 |
+
if os.path.isfile(file_path) is False:
|
| 126 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 127 |
+
# Here, we do not cache the features, operating under the assumption
|
| 128 |
+
# that we will soon use fast multithreaded tokenizers from the
|
| 129 |
+
# `tokenizers` repo everywhere =)
|
| 130 |
+
logger.info(f"Creating features from dataset file at {file_path}")
|
| 131 |
+
|
| 132 |
+
with open(file_path, encoding="utf-8") as f:
|
| 133 |
+
lines = [line for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())]
|
| 134 |
+
|
| 135 |
+
batch_encoding = tokenizer(lines, add_special_tokens=True, truncation=True, max_length=block_size)
|
| 136 |
+
self.examples = batch_encoding["input_ids"]
|
| 137 |
+
self.examples = [{"input_ids": torch.tensor(e, dtype=torch.long)} for e in self.examples]
|
| 138 |
+
|
| 139 |
+
def __len__(self):
|
| 140 |
+
return len(self.examples)
|
| 141 |
+
|
| 142 |
+
def __getitem__(self, i) -> Dict[str, torch.tensor]:
|
| 143 |
+
return self.examples[i]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class LineByLineWithRefDataset(Dataset):
|
| 147 |
+
"""
|
| 148 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int, ref_path: str):
|
| 152 |
+
warnings.warn(
|
| 153 |
+
DEPRECATION_WARNING.format(
|
| 154 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm_wwm.py"
|
| 155 |
+
),
|
| 156 |
+
FutureWarning,
|
| 157 |
+
)
|
| 158 |
+
if os.path.isfile(file_path) is False:
|
| 159 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 160 |
+
if os.path.isfile(ref_path) is False:
|
| 161 |
+
raise ValueError(f"Ref file path {file_path} not found")
|
| 162 |
+
# Here, we do not cache the features, operating under the assumption
|
| 163 |
+
# that we will soon use fast multithreaded tokenizers from the
|
| 164 |
+
# `tokenizers` repo everywhere =)
|
| 165 |
+
logger.info(f"Creating features from dataset file at {file_path}")
|
| 166 |
+
logger.info(f"Use ref segment results at {ref_path}")
|
| 167 |
+
with open(file_path, encoding="utf-8") as f:
|
| 168 |
+
data = f.readlines() # use this method to avoid delimiter '\u2029' to split a line
|
| 169 |
+
data = [line.strip() for line in data if len(line) > 0 and not line.isspace()]
|
| 170 |
+
# Get ref inf from file
|
| 171 |
+
with open(ref_path, encoding="utf-8") as f:
|
| 172 |
+
ref = [json.loads(line) for line in f.read().splitlines() if (len(line) > 0 and not line.isspace())]
|
| 173 |
+
if len(data) != len(ref):
|
| 174 |
+
raise ValueError(
|
| 175 |
+
f"Length of Input file should be equal to Ref file. But the length of {file_path} is {len(data)} "
|
| 176 |
+
f"while length of {ref_path} is {len(ref)}"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
batch_encoding = tokenizer(data, add_special_tokens=True, truncation=True, max_length=block_size)
|
| 180 |
+
self.examples = batch_encoding["input_ids"]
|
| 181 |
+
self.examples = [{"input_ids": torch.tensor(e, dtype=torch.long)} for e in self.examples]
|
| 182 |
+
|
| 183 |
+
n = len(self.examples)
|
| 184 |
+
for i in range(n):
|
| 185 |
+
self.examples[i]["chinese_ref"] = torch.tensor(ref[i], dtype=torch.long)
|
| 186 |
+
|
| 187 |
+
def __len__(self):
|
| 188 |
+
return len(self.examples)
|
| 189 |
+
|
| 190 |
+
def __getitem__(self, i) -> Dict[str, torch.tensor]:
|
| 191 |
+
return self.examples[i]
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class LineByLineWithSOPTextDataset(Dataset):
|
| 195 |
+
"""
|
| 196 |
+
Dataset for sentence order prediction task, prepare sentence pairs for SOP task
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
def __init__(self, tokenizer: PreTrainedTokenizer, file_dir: str, block_size: int):
|
| 200 |
+
warnings.warn(
|
| 201 |
+
DEPRECATION_WARNING.format(
|
| 202 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 203 |
+
),
|
| 204 |
+
FutureWarning,
|
| 205 |
+
)
|
| 206 |
+
if os.path.isdir(file_dir) is False:
|
| 207 |
+
raise ValueError(f"{file_dir} is not a directory")
|
| 208 |
+
logger.info(f"Creating features from dataset file folder at {file_dir}")
|
| 209 |
+
self.examples = []
|
| 210 |
+
# TODO: randomness could apply a random seed, ex. rng = random.Random(random_seed)
|
| 211 |
+
# file path looks like ./dataset/wiki_1, ./dataset/wiki_2
|
| 212 |
+
for file_name in os.listdir(file_dir):
|
| 213 |
+
file_path = os.path.join(file_dir, file_name)
|
| 214 |
+
if os.path.isfile(file_path) is False:
|
| 215 |
+
raise ValueError(f"{file_path} is not a file")
|
| 216 |
+
article_open = False
|
| 217 |
+
with open(file_path, encoding="utf-8") as f:
|
| 218 |
+
original_lines = f.readlines()
|
| 219 |
+
article_lines = []
|
| 220 |
+
for line in original_lines:
|
| 221 |
+
if "<doc id=" in line:
|
| 222 |
+
article_open = True
|
| 223 |
+
elif "</doc>" in line:
|
| 224 |
+
article_open = False
|
| 225 |
+
document = [
|
| 226 |
+
tokenizer.convert_tokens_to_ids(tokenizer.tokenize(line))
|
| 227 |
+
for line in article_lines[1:]
|
| 228 |
+
if (len(line) > 0 and not line.isspace())
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
examples = self.create_examples_from_document(document, block_size, tokenizer)
|
| 232 |
+
self.examples.extend(examples)
|
| 233 |
+
article_lines = []
|
| 234 |
+
else:
|
| 235 |
+
if article_open:
|
| 236 |
+
article_lines.append(line)
|
| 237 |
+
|
| 238 |
+
logger.info("Dataset parse finished.")
|
| 239 |
+
|
| 240 |
+
def create_examples_from_document(self, document, block_size, tokenizer, short_seq_prob=0.1):
|
| 241 |
+
"""Creates examples for a single document."""
|
| 242 |
+
|
| 243 |
+
# Account for special tokens
|
| 244 |
+
max_num_tokens = block_size - tokenizer.num_special_tokens_to_add(pair=True)
|
| 245 |
+
|
| 246 |
+
# We *usually* want to fill up the entire sequence since we are padding
|
| 247 |
+
# to `block_size` anyways, so short sequences are generally wasted
|
| 248 |
+
# computation. However, we *sometimes*
|
| 249 |
+
# (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
|
| 250 |
+
# sequences to minimize the mismatch between pretraining and fine-tuning.
|
| 251 |
+
# The `target_seq_length` is just a rough target however, whereas
|
| 252 |
+
# `block_size` is a hard limit.
|
| 253 |
+
target_seq_length = max_num_tokens
|
| 254 |
+
if random.random() < short_seq_prob:
|
| 255 |
+
target_seq_length = random.randint(2, max_num_tokens)
|
| 256 |
+
|
| 257 |
+
# We DON'T just concatenate all of the tokens from a document into a long
|
| 258 |
+
# sequence and choose an arbitrary split point because this would make the
|
| 259 |
+
# next sentence prediction task too easy. Instead, we split the input into
|
| 260 |
+
# segments "A" and "B" based on the actual "sentences" provided by the user
|
| 261 |
+
# input.
|
| 262 |
+
examples = []
|
| 263 |
+
current_chunk = [] # a buffer stored current working segments
|
| 264 |
+
current_length = 0
|
| 265 |
+
i = 0
|
| 266 |
+
while i < len(document):
|
| 267 |
+
segment = document[i] # get a segment
|
| 268 |
+
if not segment:
|
| 269 |
+
i += 1
|
| 270 |
+
continue
|
| 271 |
+
current_chunk.append(segment) # add a segment to current chunk
|
| 272 |
+
current_length += len(segment) # overall token length
|
| 273 |
+
# if current length goes to the target length or reaches the end of file, start building token a and b
|
| 274 |
+
if i == len(document) - 1 or current_length >= target_seq_length:
|
| 275 |
+
if current_chunk:
|
| 276 |
+
# `a_end` is how many segments from `current_chunk` go into the `A` (first) sentence.
|
| 277 |
+
a_end = 1
|
| 278 |
+
# if current chunk has more than 2 sentences, pick part of it `A` (first) sentence
|
| 279 |
+
if len(current_chunk) >= 2:
|
| 280 |
+
a_end = random.randint(1, len(current_chunk) - 1)
|
| 281 |
+
# token a
|
| 282 |
+
tokens_a = []
|
| 283 |
+
for j in range(a_end):
|
| 284 |
+
tokens_a.extend(current_chunk[j])
|
| 285 |
+
|
| 286 |
+
# token b
|
| 287 |
+
tokens_b = []
|
| 288 |
+
for j in range(a_end, len(current_chunk)):
|
| 289 |
+
tokens_b.extend(current_chunk[j])
|
| 290 |
+
|
| 291 |
+
if len(tokens_a) == 0 or len(tokens_b) == 0:
|
| 292 |
+
continue
|
| 293 |
+
|
| 294 |
+
# switch tokens_a and tokens_b randomly
|
| 295 |
+
if random.random() < 0.5:
|
| 296 |
+
is_next = False
|
| 297 |
+
tokens_a, tokens_b = tokens_b, tokens_a
|
| 298 |
+
else:
|
| 299 |
+
is_next = True
|
| 300 |
+
|
| 301 |
+
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens):
|
| 302 |
+
"""Truncates a pair of sequences to a maximum sequence length."""
|
| 303 |
+
while True:
|
| 304 |
+
total_length = len(tokens_a) + len(tokens_b)
|
| 305 |
+
if total_length <= max_num_tokens:
|
| 306 |
+
break
|
| 307 |
+
trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
|
| 308 |
+
if not (len(trunc_tokens) >= 1):
|
| 309 |
+
raise ValueError("Sequence length to be truncated must be no less than one")
|
| 310 |
+
# We want to sometimes truncate from the front and sometimes from the
|
| 311 |
+
# back to add more randomness and avoid biases.
|
| 312 |
+
if random.random() < 0.5:
|
| 313 |
+
del trunc_tokens[0]
|
| 314 |
+
else:
|
| 315 |
+
trunc_tokens.pop()
|
| 316 |
+
|
| 317 |
+
truncate_seq_pair(tokens_a, tokens_b, max_num_tokens)
|
| 318 |
+
if not (len(tokens_a) >= 1):
|
| 319 |
+
raise ValueError(f"Length of sequence a is {len(tokens_a)} which must be no less than 1")
|
| 320 |
+
if not (len(tokens_b) >= 1):
|
| 321 |
+
raise ValueError(f"Length of sequence b is {len(tokens_b)} which must be no less than 1")
|
| 322 |
+
|
| 323 |
+
# add special tokens
|
| 324 |
+
input_ids = tokenizer.build_inputs_with_special_tokens(tokens_a, tokens_b)
|
| 325 |
+
# add token type ids, 0 for sentence a, 1 for sentence b
|
| 326 |
+
token_type_ids = tokenizer.create_token_type_ids_from_sequences(tokens_a, tokens_b)
|
| 327 |
+
|
| 328 |
+
example = {
|
| 329 |
+
"input_ids": torch.tensor(input_ids, dtype=torch.long),
|
| 330 |
+
"token_type_ids": torch.tensor(token_type_ids, dtype=torch.long),
|
| 331 |
+
"sentence_order_label": torch.tensor(0 if is_next else 1, dtype=torch.long),
|
| 332 |
+
}
|
| 333 |
+
examples.append(example)
|
| 334 |
+
current_chunk = [] # clear current chunk
|
| 335 |
+
current_length = 0 # reset current text length
|
| 336 |
+
i += 1 # go to next line
|
| 337 |
+
return examples
|
| 338 |
+
|
| 339 |
+
def __len__(self):
|
| 340 |
+
return len(self.examples)
|
| 341 |
+
|
| 342 |
+
def __getitem__(self, i) -> Dict[str, torch.tensor]:
|
| 343 |
+
return self.examples[i]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class TextDatasetForNextSentencePrediction(Dataset):
|
| 347 |
+
"""
|
| 348 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
def __init__(
|
| 352 |
+
self,
|
| 353 |
+
tokenizer: PreTrainedTokenizer,
|
| 354 |
+
file_path: str,
|
| 355 |
+
block_size: int,
|
| 356 |
+
overwrite_cache=False,
|
| 357 |
+
short_seq_probability=0.1,
|
| 358 |
+
nsp_probability=0.5,
|
| 359 |
+
):
|
| 360 |
+
warnings.warn(
|
| 361 |
+
DEPRECATION_WARNING.format(
|
| 362 |
+
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm.py"
|
| 363 |
+
),
|
| 364 |
+
FutureWarning,
|
| 365 |
+
)
|
| 366 |
+
if not os.path.isfile(file_path):
|
| 367 |
+
raise ValueError(f"Input file path {file_path} not found")
|
| 368 |
+
|
| 369 |
+
self.short_seq_probability = short_seq_probability
|
| 370 |
+
self.nsp_probability = nsp_probability
|
| 371 |
+
|
| 372 |
+
directory, filename = os.path.split(file_path)
|
| 373 |
+
cached_features_file = os.path.join(
|
| 374 |
+
directory,
|
| 375 |
+
f"cached_nsp_{tokenizer.__class__.__name__}_{block_size}_{filename}",
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
self.tokenizer = tokenizer
|
| 379 |
+
|
| 380 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 381 |
+
# and the others will use the cache.
|
| 382 |
+
lock_path = cached_features_file + ".lock"
|
| 383 |
+
|
| 384 |
+
# Input file format:
|
| 385 |
+
# (1) One sentence per line. These should ideally be actual sentences, not
|
| 386 |
+
# entire paragraphs or arbitrary spans of text. (Because we use the
|
| 387 |
+
# sentence boundaries for the "next sentence prediction" task).
|
| 388 |
+
# (2) Blank lines between documents. Document boundaries are needed so
|
| 389 |
+
# that the "next sentence prediction" task doesn't span between documents.
|
| 390 |
+
#
|
| 391 |
+
# Example:
|
| 392 |
+
# I am very happy.
|
| 393 |
+
# Here is the second sentence.
|
| 394 |
+
#
|
| 395 |
+
# A new document.
|
| 396 |
+
|
| 397 |
+
with FileLock(lock_path):
|
| 398 |
+
if os.path.exists(cached_features_file) and not overwrite_cache:
|
| 399 |
+
start = time.time()
|
| 400 |
+
with open(cached_features_file, "rb") as handle:
|
| 401 |
+
self.examples = pickle.load(handle)
|
| 402 |
+
logger.info(
|
| 403 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 404 |
+
)
|
| 405 |
+
else:
|
| 406 |
+
logger.info(f"Creating features from dataset file at {directory}")
|
| 407 |
+
|
| 408 |
+
self.documents = [[]]
|
| 409 |
+
with open(file_path, encoding="utf-8") as f:
|
| 410 |
+
while True:
|
| 411 |
+
line = f.readline()
|
| 412 |
+
if not line:
|
| 413 |
+
break
|
| 414 |
+
line = line.strip()
|
| 415 |
+
|
| 416 |
+
# Empty lines are used as document delimiters
|
| 417 |
+
if not line and len(self.documents[-1]) != 0:
|
| 418 |
+
self.documents.append([])
|
| 419 |
+
tokens = tokenizer.tokenize(line)
|
| 420 |
+
tokens = tokenizer.convert_tokens_to_ids(tokens)
|
| 421 |
+
if tokens:
|
| 422 |
+
self.documents[-1].append(tokens)
|
| 423 |
+
|
| 424 |
+
logger.info(f"Creating examples from {len(self.documents)} documents.")
|
| 425 |
+
self.examples = []
|
| 426 |
+
for doc_index, document in enumerate(self.documents):
|
| 427 |
+
self.create_examples_from_document(document, doc_index, block_size)
|
| 428 |
+
|
| 429 |
+
start = time.time()
|
| 430 |
+
with open(cached_features_file, "wb") as handle:
|
| 431 |
+
pickle.dump(self.examples, handle, protocol=pickle.HIGHEST_PROTOCOL)
|
| 432 |
+
logger.info(
|
| 433 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
def create_examples_from_document(self, document: List[List[int]], doc_index: int, block_size: int):
|
| 437 |
+
"""Creates examples for a single document."""
|
| 438 |
+
|
| 439 |
+
max_num_tokens = block_size - self.tokenizer.num_special_tokens_to_add(pair=True)
|
| 440 |
+
|
| 441 |
+
# We *usually* want to fill up the entire sequence since we are padding
|
| 442 |
+
# to `block_size` anyways, so short sequences are generally wasted
|
| 443 |
+
# computation. However, we *sometimes*
|
| 444 |
+
# (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
|
| 445 |
+
# sequences to minimize the mismatch between pretraining and fine-tuning.
|
| 446 |
+
# The `target_seq_length` is just a rough target however, whereas
|
| 447 |
+
# `block_size` is a hard limit.
|
| 448 |
+
target_seq_length = max_num_tokens
|
| 449 |
+
if random.random() < self.short_seq_probability:
|
| 450 |
+
target_seq_length = random.randint(2, max_num_tokens)
|
| 451 |
+
|
| 452 |
+
current_chunk = [] # a buffer stored current working segments
|
| 453 |
+
current_length = 0
|
| 454 |
+
i = 0
|
| 455 |
+
|
| 456 |
+
while i < len(document):
|
| 457 |
+
segment = document[i]
|
| 458 |
+
current_chunk.append(segment)
|
| 459 |
+
current_length += len(segment)
|
| 460 |
+
if i == len(document) - 1 or current_length >= target_seq_length:
|
| 461 |
+
if current_chunk:
|
| 462 |
+
# `a_end` is how many segments from `current_chunk` go into the `A`
|
| 463 |
+
# (first) sentence.
|
| 464 |
+
a_end = 1
|
| 465 |
+
if len(current_chunk) >= 2:
|
| 466 |
+
a_end = random.randint(1, len(current_chunk) - 1)
|
| 467 |
+
|
| 468 |
+
tokens_a = []
|
| 469 |
+
for j in range(a_end):
|
| 470 |
+
tokens_a.extend(current_chunk[j])
|
| 471 |
+
|
| 472 |
+
tokens_b = []
|
| 473 |
+
|
| 474 |
+
if len(current_chunk) == 1 or random.random() < self.nsp_probability:
|
| 475 |
+
is_random_next = True
|
| 476 |
+
target_b_length = target_seq_length - len(tokens_a)
|
| 477 |
+
|
| 478 |
+
# This should rarely go for more than one iteration for large
|
| 479 |
+
# corpora. However, just to be careful, we try to make sure that
|
| 480 |
+
# the random document is not the same as the document
|
| 481 |
+
# we're processing.
|
| 482 |
+
for _ in range(10):
|
| 483 |
+
random_document_index = random.randint(0, len(self.documents) - 1)
|
| 484 |
+
if random_document_index != doc_index:
|
| 485 |
+
break
|
| 486 |
+
|
| 487 |
+
random_document = self.documents[random_document_index]
|
| 488 |
+
random_start = random.randint(0, len(random_document) - 1)
|
| 489 |
+
for j in range(random_start, len(random_document)):
|
| 490 |
+
tokens_b.extend(random_document[j])
|
| 491 |
+
if len(tokens_b) >= target_b_length:
|
| 492 |
+
break
|
| 493 |
+
# We didn't actually use these segments so we "put them back" so
|
| 494 |
+
# they don't go to waste.
|
| 495 |
+
num_unused_segments = len(current_chunk) - a_end
|
| 496 |
+
i -= num_unused_segments
|
| 497 |
+
# Actual next
|
| 498 |
+
else:
|
| 499 |
+
is_random_next = False
|
| 500 |
+
for j in range(a_end, len(current_chunk)):
|
| 501 |
+
tokens_b.extend(current_chunk[j])
|
| 502 |
+
|
| 503 |
+
if not (len(tokens_a) >= 1):
|
| 504 |
+
raise ValueError(f"Length of sequence a is {len(tokens_a)} which must be no less than 1")
|
| 505 |
+
if not (len(tokens_b) >= 1):
|
| 506 |
+
raise ValueError(f"Length of sequence b is {len(tokens_b)} which must be no less than 1")
|
| 507 |
+
|
| 508 |
+
# add special tokens
|
| 509 |
+
input_ids = self.tokenizer.build_inputs_with_special_tokens(tokens_a, tokens_b)
|
| 510 |
+
# add token type ids, 0 for sentence a, 1 for sentence b
|
| 511 |
+
token_type_ids = self.tokenizer.create_token_type_ids_from_sequences(tokens_a, tokens_b)
|
| 512 |
+
|
| 513 |
+
example = {
|
| 514 |
+
"input_ids": torch.tensor(input_ids, dtype=torch.long),
|
| 515 |
+
"token_type_ids": torch.tensor(token_type_ids, dtype=torch.long),
|
| 516 |
+
"next_sentence_label": torch.tensor(1 if is_random_next else 0, dtype=torch.long),
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
self.examples.append(example)
|
| 520 |
+
|
| 521 |
+
current_chunk = []
|
| 522 |
+
current_length = 0
|
| 523 |
+
|
| 524 |
+
i += 1
|
| 525 |
+
|
| 526 |
+
def __len__(self):
|
| 527 |
+
return len(self.examples)
|
| 528 |
+
|
| 529 |
+
def __getitem__(self, i):
|
| 530 |
+
return self.examples[i]
|
evalkit_internvl/lib/python3.10/site-packages/transformers/data/datasets/squad.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 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 os
|
| 16 |
+
import time
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
from enum import Enum
|
| 19 |
+
from typing import Dict, List, Optional, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
from filelock import FileLock
|
| 23 |
+
from torch.utils.data import Dataset
|
| 24 |
+
|
| 25 |
+
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
|
| 26 |
+
from ...tokenization_utils import PreTrainedTokenizer
|
| 27 |
+
from ...utils import logging
|
| 28 |
+
from ..processors.squad import SquadFeatures, SquadV1Processor, SquadV2Processor, squad_convert_examples_to_features
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logger = logging.get_logger(__name__)
|
| 32 |
+
|
| 33 |
+
MODEL_CONFIG_CLASSES = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
|
| 34 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
class SquadDataTrainingArguments:
|
| 39 |
+
"""
|
| 40 |
+
Arguments pertaining to what data we are going to input our model for training and eval.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
model_type: str = field(
|
| 44 |
+
default=None, metadata={"help": "Model type selected in the list: " + ", ".join(MODEL_TYPES)}
|
| 45 |
+
)
|
| 46 |
+
data_dir: str = field(
|
| 47 |
+
default=None, metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."}
|
| 48 |
+
)
|
| 49 |
+
max_seq_length: int = field(
|
| 50 |
+
default=128,
|
| 51 |
+
metadata={
|
| 52 |
+
"help": (
|
| 53 |
+
"The maximum total input sequence length after tokenization. Sequences longer "
|
| 54 |
+
"than this will be truncated, sequences shorter will be padded."
|
| 55 |
+
)
|
| 56 |
+
},
|
| 57 |
+
)
|
| 58 |
+
doc_stride: int = field(
|
| 59 |
+
default=128,
|
| 60 |
+
metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."},
|
| 61 |
+
)
|
| 62 |
+
max_query_length: int = field(
|
| 63 |
+
default=64,
|
| 64 |
+
metadata={
|
| 65 |
+
"help": (
|
| 66 |
+
"The maximum number of tokens for the question. Questions longer than this will "
|
| 67 |
+
"be truncated to this length."
|
| 68 |
+
)
|
| 69 |
+
},
|
| 70 |
+
)
|
| 71 |
+
max_answer_length: int = field(
|
| 72 |
+
default=30,
|
| 73 |
+
metadata={
|
| 74 |
+
"help": (
|
| 75 |
+
"The maximum length of an answer that can be generated. This is needed because the start "
|
| 76 |
+
"and end predictions are not conditioned on one another."
|
| 77 |
+
)
|
| 78 |
+
},
|
| 79 |
+
)
|
| 80 |
+
overwrite_cache: bool = field(
|
| 81 |
+
default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
|
| 82 |
+
)
|
| 83 |
+
version_2_with_negative: bool = field(
|
| 84 |
+
default=False, metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."}
|
| 85 |
+
)
|
| 86 |
+
null_score_diff_threshold: float = field(
|
| 87 |
+
default=0.0, metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}
|
| 88 |
+
)
|
| 89 |
+
n_best_size: int = field(
|
| 90 |
+
default=20, metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."}
|
| 91 |
+
)
|
| 92 |
+
lang_id: int = field(
|
| 93 |
+
default=0,
|
| 94 |
+
metadata={
|
| 95 |
+
"help": (
|
| 96 |
+
"language id of input for language-specific xlm models (see"
|
| 97 |
+
" tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"
|
| 98 |
+
)
|
| 99 |
+
},
|
| 100 |
+
)
|
| 101 |
+
threads: int = field(default=1, metadata={"help": "multiple threads for converting example to features"})
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class Split(Enum):
|
| 105 |
+
train = "train"
|
| 106 |
+
dev = "dev"
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class SquadDataset(Dataset):
|
| 110 |
+
"""
|
| 111 |
+
This will be superseded by a framework-agnostic approach soon.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
args: SquadDataTrainingArguments
|
| 115 |
+
features: List[SquadFeatures]
|
| 116 |
+
mode: Split
|
| 117 |
+
is_language_sensitive: bool
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
args: SquadDataTrainingArguments,
|
| 122 |
+
tokenizer: PreTrainedTokenizer,
|
| 123 |
+
limit_length: Optional[int] = None,
|
| 124 |
+
mode: Union[str, Split] = Split.train,
|
| 125 |
+
is_language_sensitive: Optional[bool] = False,
|
| 126 |
+
cache_dir: Optional[str] = None,
|
| 127 |
+
dataset_format: Optional[str] = "pt",
|
| 128 |
+
):
|
| 129 |
+
self.args = args
|
| 130 |
+
self.is_language_sensitive = is_language_sensitive
|
| 131 |
+
self.processor = SquadV2Processor() if args.version_2_with_negative else SquadV1Processor()
|
| 132 |
+
if isinstance(mode, str):
|
| 133 |
+
try:
|
| 134 |
+
mode = Split[mode]
|
| 135 |
+
except KeyError:
|
| 136 |
+
raise KeyError("mode is not a valid split name")
|
| 137 |
+
self.mode = mode
|
| 138 |
+
# Load data features from cache or dataset file
|
| 139 |
+
version_tag = "v2" if args.version_2_with_negative else "v1"
|
| 140 |
+
cached_features_file = os.path.join(
|
| 141 |
+
cache_dir if cache_dir is not None else args.data_dir,
|
| 142 |
+
f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}",
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Make sure only the first process in distributed training processes the dataset,
|
| 146 |
+
# and the others will use the cache.
|
| 147 |
+
lock_path = cached_features_file + ".lock"
|
| 148 |
+
with FileLock(lock_path):
|
| 149 |
+
if os.path.exists(cached_features_file) and not args.overwrite_cache:
|
| 150 |
+
start = time.time()
|
| 151 |
+
self.old_features = torch.load(cached_features_file)
|
| 152 |
+
|
| 153 |
+
# Legacy cache files have only features, while new cache files
|
| 154 |
+
# will have dataset and examples also.
|
| 155 |
+
self.features = self.old_features["features"]
|
| 156 |
+
self.dataset = self.old_features.get("dataset", None)
|
| 157 |
+
self.examples = self.old_features.get("examples", None)
|
| 158 |
+
logger.info(
|
| 159 |
+
f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if self.dataset is None or self.examples is None:
|
| 163 |
+
logger.warning(
|
| 164 |
+
f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"
|
| 165 |
+
" future run"
|
| 166 |
+
)
|
| 167 |
+
else:
|
| 168 |
+
if mode == Split.dev:
|
| 169 |
+
self.examples = self.processor.get_dev_examples(args.data_dir)
|
| 170 |
+
else:
|
| 171 |
+
self.examples = self.processor.get_train_examples(args.data_dir)
|
| 172 |
+
|
| 173 |
+
self.features, self.dataset = squad_convert_examples_to_features(
|
| 174 |
+
examples=self.examples,
|
| 175 |
+
tokenizer=tokenizer,
|
| 176 |
+
max_seq_length=args.max_seq_length,
|
| 177 |
+
doc_stride=args.doc_stride,
|
| 178 |
+
max_query_length=args.max_query_length,
|
| 179 |
+
is_training=mode == Split.train,
|
| 180 |
+
threads=args.threads,
|
| 181 |
+
return_dataset=dataset_format,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
start = time.time()
|
| 185 |
+
torch.save(
|
| 186 |
+
{"features": self.features, "dataset": self.dataset, "examples": self.examples},
|
| 187 |
+
cached_features_file,
|
| 188 |
+
)
|
| 189 |
+
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
|
| 190 |
+
logger.info(
|
| 191 |
+
f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
def __len__(self):
|
| 195 |
+
return len(self.features)
|
| 196 |
+
|
| 197 |
+
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
|
| 198 |
+
# Convert to Tensors and build dataset
|
| 199 |
+
feature = self.features[i]
|
| 200 |
+
|
| 201 |
+
input_ids = torch.tensor(feature.input_ids, dtype=torch.long)
|
| 202 |
+
attention_mask = torch.tensor(feature.attention_mask, dtype=torch.long)
|
| 203 |
+
token_type_ids = torch.tensor(feature.token_type_ids, dtype=torch.long)
|
| 204 |
+
cls_index = torch.tensor(feature.cls_index, dtype=torch.long)
|
| 205 |
+
p_mask = torch.tensor(feature.p_mask, dtype=torch.float)
|
| 206 |
+
is_impossible = torch.tensor(feature.is_impossible, dtype=torch.float)
|
| 207 |
+
|
| 208 |
+
inputs = {
|
| 209 |
+
"input_ids": input_ids,
|
| 210 |
+
"attention_mask": attention_mask,
|
| 211 |
+
"token_type_ids": token_type_ids,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
|
| 215 |
+
del inputs["token_type_ids"]
|
| 216 |
+
|
| 217 |
+
if self.args.model_type in ["xlnet", "xlm"]:
|
| 218 |
+
inputs.update({"cls_index": cls_index, "p_mask": p_mask})
|
| 219 |
+
if self.args.version_2_with_negative:
|
| 220 |
+
inputs.update({"is_impossible": is_impossible})
|
| 221 |
+
if self.is_language_sensitive:
|
| 222 |
+
inputs.update({"langs": (torch.ones(input_ids.shape, dtype=torch.int64) * self.args.lang_id)})
|
| 223 |
+
|
| 224 |
+
if self.mode == Split.train:
|
| 225 |
+
start_positions = torch.tensor(feature.start_position, dtype=torch.long)
|
| 226 |
+
end_positions = torch.tensor(feature.end_position, dtype=torch.long)
|
| 227 |
+
inputs.update({"start_positions": start_positions, "end_positions": end_positions})
|
| 228 |
+
|
| 229 |
+
return inputs
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.cpp
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************************************
|
| 7 |
+
* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
|
| 8 |
+
**************************************************************************************************
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#include <vector>
|
| 12 |
+
|
| 13 |
+
#include <ATen/ATen.h>
|
| 14 |
+
#include <ATen/cuda/CUDAContext.h>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
at::Tensor
|
| 18 |
+
ms_deform_attn_cpu_forward(
|
| 19 |
+
const at::Tensor &value,
|
| 20 |
+
const at::Tensor &spatial_shapes,
|
| 21 |
+
const at::Tensor &level_start_index,
|
| 22 |
+
const at::Tensor &sampling_loc,
|
| 23 |
+
const at::Tensor &attn_weight,
|
| 24 |
+
const int im2col_step)
|
| 25 |
+
{
|
| 26 |
+
AT_ERROR("Not implement on cpu");
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
std::vector<at::Tensor>
|
| 30 |
+
ms_deform_attn_cpu_backward(
|
| 31 |
+
const at::Tensor &value,
|
| 32 |
+
const at::Tensor &spatial_shapes,
|
| 33 |
+
const at::Tensor &level_start_index,
|
| 34 |
+
const at::Tensor &sampling_loc,
|
| 35 |
+
const at::Tensor &attn_weight,
|
| 36 |
+
const at::Tensor &grad_output,
|
| 37 |
+
const int im2col_step)
|
| 38 |
+
{
|
| 39 |
+
AT_ERROR("Not implement on cpu");
|
| 40 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cpu/ms_deform_attn_cpu.h
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************************************
|
| 7 |
+
* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
|
| 8 |
+
**************************************************************************************************
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#pragma once
|
| 12 |
+
#include <torch/extension.h>
|
| 13 |
+
|
| 14 |
+
at::Tensor
|
| 15 |
+
ms_deform_attn_cpu_forward(
|
| 16 |
+
const at::Tensor &value,
|
| 17 |
+
const at::Tensor &spatial_shapes,
|
| 18 |
+
const at::Tensor &level_start_index,
|
| 19 |
+
const at::Tensor &sampling_loc,
|
| 20 |
+
const at::Tensor &attn_weight,
|
| 21 |
+
const int im2col_step);
|
| 22 |
+
|
| 23 |
+
std::vector<at::Tensor>
|
| 24 |
+
ms_deform_attn_cpu_backward(
|
| 25 |
+
const at::Tensor &value,
|
| 26 |
+
const at::Tensor &spatial_shapes,
|
| 27 |
+
const at::Tensor &level_start_index,
|
| 28 |
+
const at::Tensor &sampling_loc,
|
| 29 |
+
const at::Tensor &attn_weight,
|
| 30 |
+
const at::Tensor &grad_output,
|
| 31 |
+
const int im2col_step);
|
| 32 |
+
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cu
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************************************
|
| 7 |
+
* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
|
| 8 |
+
**************************************************************************************************
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#include <vector>
|
| 12 |
+
#include "cuda/ms_deform_im2col_cuda.cuh"
|
| 13 |
+
|
| 14 |
+
#include <ATen/ATen.h>
|
| 15 |
+
#include <ATen/cuda/CUDAContext.h>
|
| 16 |
+
#include <cuda.h>
|
| 17 |
+
#include <cuda_runtime.h>
|
| 18 |
+
|
| 19 |
+
#pragma once
|
| 20 |
+
#include <torch/extension.h>
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
at::Tensor ms_deform_attn_cuda_forward(
|
| 24 |
+
const at::Tensor &value,
|
| 25 |
+
const at::Tensor &spatial_shapes,
|
| 26 |
+
const at::Tensor &level_start_index,
|
| 27 |
+
const at::Tensor &sampling_loc,
|
| 28 |
+
const at::Tensor &attn_weight,
|
| 29 |
+
const int im2col_step)
|
| 30 |
+
{
|
| 31 |
+
AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
|
| 32 |
+
AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
|
| 33 |
+
AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
|
| 34 |
+
AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
|
| 35 |
+
AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
|
| 36 |
+
|
| 37 |
+
AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
|
| 38 |
+
AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
|
| 39 |
+
AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
|
| 40 |
+
AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
|
| 41 |
+
AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
|
| 42 |
+
|
| 43 |
+
const int batch = value.size(0);
|
| 44 |
+
const int spatial_size = value.size(1);
|
| 45 |
+
const int num_heads = value.size(2);
|
| 46 |
+
const int channels = value.size(3);
|
| 47 |
+
|
| 48 |
+
const int num_levels = spatial_shapes.size(0);
|
| 49 |
+
|
| 50 |
+
const int num_query = sampling_loc.size(1);
|
| 51 |
+
const int num_point = sampling_loc.size(4);
|
| 52 |
+
|
| 53 |
+
const int im2col_step_ = std::min(batch, im2col_step);
|
| 54 |
+
|
| 55 |
+
AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
|
| 56 |
+
|
| 57 |
+
auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
|
| 58 |
+
|
| 59 |
+
const int batch_n = im2col_step_;
|
| 60 |
+
auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
|
| 61 |
+
auto per_value_size = spatial_size * num_heads * channels;
|
| 62 |
+
auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
|
| 63 |
+
auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
|
| 64 |
+
for (int n = 0; n < batch/im2col_step_; ++n)
|
| 65 |
+
{
|
| 66 |
+
auto columns = output_n.select(0, n);
|
| 67 |
+
AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
|
| 68 |
+
ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
|
| 69 |
+
value.data<scalar_t>() + n * im2col_step_ * per_value_size,
|
| 70 |
+
spatial_shapes.data<int64_t>(),
|
| 71 |
+
level_start_index.data<int64_t>(),
|
| 72 |
+
sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
|
| 73 |
+
attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size,
|
| 74 |
+
batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
|
| 75 |
+
columns.data<scalar_t>());
|
| 76 |
+
|
| 77 |
+
}));
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
output = output.view({batch, num_query, num_heads*channels});
|
| 81 |
+
|
| 82 |
+
return output;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
std::vector<at::Tensor> ms_deform_attn_cuda_backward(
|
| 87 |
+
const at::Tensor &value,
|
| 88 |
+
const at::Tensor &spatial_shapes,
|
| 89 |
+
const at::Tensor &level_start_index,
|
| 90 |
+
const at::Tensor &sampling_loc,
|
| 91 |
+
const at::Tensor &attn_weight,
|
| 92 |
+
const at::Tensor &grad_output,
|
| 93 |
+
const int im2col_step)
|
| 94 |
+
{
|
| 95 |
+
|
| 96 |
+
AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
|
| 97 |
+
AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
|
| 98 |
+
AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
|
| 99 |
+
AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
|
| 100 |
+
AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
|
| 101 |
+
AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
|
| 102 |
+
|
| 103 |
+
AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
|
| 104 |
+
AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
|
| 105 |
+
AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
|
| 106 |
+
AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
|
| 107 |
+
AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
|
| 108 |
+
AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
|
| 109 |
+
|
| 110 |
+
const int batch = value.size(0);
|
| 111 |
+
const int spatial_size = value.size(1);
|
| 112 |
+
const int num_heads = value.size(2);
|
| 113 |
+
const int channels = value.size(3);
|
| 114 |
+
|
| 115 |
+
const int num_levels = spatial_shapes.size(0);
|
| 116 |
+
|
| 117 |
+
const int num_query = sampling_loc.size(1);
|
| 118 |
+
const int num_point = sampling_loc.size(4);
|
| 119 |
+
|
| 120 |
+
const int im2col_step_ = std::min(batch, im2col_step);
|
| 121 |
+
|
| 122 |
+
AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
|
| 123 |
+
|
| 124 |
+
auto grad_value = at::zeros_like(value);
|
| 125 |
+
auto grad_sampling_loc = at::zeros_like(sampling_loc);
|
| 126 |
+
auto grad_attn_weight = at::zeros_like(attn_weight);
|
| 127 |
+
|
| 128 |
+
const int batch_n = im2col_step_;
|
| 129 |
+
auto per_value_size = spatial_size * num_heads * channels;
|
| 130 |
+
auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
|
| 131 |
+
auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
|
| 132 |
+
auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
|
| 133 |
+
|
| 134 |
+
for (int n = 0; n < batch/im2col_step_; ++n)
|
| 135 |
+
{
|
| 136 |
+
auto grad_output_g = grad_output_n.select(0, n);
|
| 137 |
+
AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
|
| 138 |
+
ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
|
| 139 |
+
grad_output_g.data<scalar_t>(),
|
| 140 |
+
value.data<scalar_t>() + n * im2col_step_ * per_value_size,
|
| 141 |
+
spatial_shapes.data<int64_t>(),
|
| 142 |
+
level_start_index.data<int64_t>(),
|
| 143 |
+
sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
|
| 144 |
+
attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size,
|
| 145 |
+
batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
|
| 146 |
+
grad_value.data<scalar_t>() + n * im2col_step_ * per_value_size,
|
| 147 |
+
grad_sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
|
| 148 |
+
grad_attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size);
|
| 149 |
+
|
| 150 |
+
}));
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
return {
|
| 154 |
+
grad_value, grad_sampling_loc, grad_attn_weight
|
| 155 |
+
};
|
| 156 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.cuh
ADDED
|
@@ -0,0 +1,1467 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************************************
|
| 7 |
+
* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
|
| 8 |
+
**************************************************************************************************
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#include <vector>
|
| 12 |
+
|
| 13 |
+
#include <cuda.h>
|
| 14 |
+
#include <cuda_runtime.h>
|
| 15 |
+
|
| 16 |
+
#include <cstdio>
|
| 17 |
+
#include <algorithm>
|
| 18 |
+
#include <cstring>
|
| 19 |
+
|
| 20 |
+
#include <ATen/ATen.h>
|
| 21 |
+
#include <ATen/cuda/CUDAContext.h>
|
| 22 |
+
|
| 23 |
+
#include <THC/THCAtomics.cuh>
|
| 24 |
+
|
| 25 |
+
#define CUDA_KERNEL_LOOP(i, n) \
|
| 26 |
+
for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
|
| 27 |
+
i < (n); \
|
| 28 |
+
i += blockDim.x * gridDim.x)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
at::Tensor ms_deform_attn_cuda_forward(
|
| 32 |
+
const at::Tensor &value,
|
| 33 |
+
const at::Tensor &spatial_shapes,
|
| 34 |
+
const at::Tensor &level_start_index,
|
| 35 |
+
const at::Tensor &sampling_loc,
|
| 36 |
+
const at::Tensor &attn_weight,
|
| 37 |
+
const int im2col_step)
|
| 38 |
+
{
|
| 39 |
+
AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
|
| 40 |
+
AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
|
| 41 |
+
AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
|
| 42 |
+
AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
|
| 43 |
+
AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
|
| 44 |
+
|
| 45 |
+
AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
|
| 46 |
+
AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
|
| 47 |
+
AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
|
| 48 |
+
AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
|
| 49 |
+
AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
|
| 50 |
+
|
| 51 |
+
const int batch = value.size(0);
|
| 52 |
+
const int spatial_size = value.size(1);
|
| 53 |
+
const int num_heads = value.size(2);
|
| 54 |
+
const int channels = value.size(3);
|
| 55 |
+
|
| 56 |
+
const int num_levels = spatial_shapes.size(0);
|
| 57 |
+
|
| 58 |
+
const int num_query = sampling_loc.size(1);
|
| 59 |
+
const int num_point = sampling_loc.size(4);
|
| 60 |
+
|
| 61 |
+
const int im2col_step_ = std::min(batch, im2col_step);
|
| 62 |
+
|
| 63 |
+
AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
|
| 64 |
+
|
| 65 |
+
auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
|
| 66 |
+
|
| 67 |
+
const int batch_n = im2col_step_;
|
| 68 |
+
auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
|
| 69 |
+
auto per_value_size = spatial_size * num_heads * channels;
|
| 70 |
+
auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
|
| 71 |
+
auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
|
| 72 |
+
for (int n = 0; n < batch/im2col_step_; ++n)
|
| 73 |
+
{
|
| 74 |
+
auto columns = output_n.select(0, n);
|
| 75 |
+
AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
|
| 76 |
+
ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
|
| 77 |
+
value.data<scalar_t>() + n * im2col_step_ * per_value_size,
|
| 78 |
+
spatial_shapes.data<int64_t>(),
|
| 79 |
+
level_start_index.data<int64_t>(),
|
| 80 |
+
sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
|
| 81 |
+
attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size,
|
| 82 |
+
batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
|
| 83 |
+
columns.data<scalar_t>());
|
| 84 |
+
|
| 85 |
+
}));
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
output = output.view({batch, num_query, num_heads*channels});
|
| 89 |
+
|
| 90 |
+
return output;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
std::vector<at::Tensor> ms_deform_attn_cuda_backward(
|
| 95 |
+
const at::Tensor &value,
|
| 96 |
+
const at::Tensor &spatial_shapes,
|
| 97 |
+
const at::Tensor &level_start_index,
|
| 98 |
+
const at::Tensor &sampling_loc,
|
| 99 |
+
const at::Tensor &attn_weight,
|
| 100 |
+
const at::Tensor &grad_output,
|
| 101 |
+
const int im2col_step)
|
| 102 |
+
{
|
| 103 |
+
|
| 104 |
+
AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
|
| 105 |
+
AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
|
| 106 |
+
AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
|
| 107 |
+
AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
|
| 108 |
+
AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
|
| 109 |
+
AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
|
| 110 |
+
|
| 111 |
+
AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
|
| 112 |
+
AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
|
| 113 |
+
AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
|
| 114 |
+
AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
|
| 115 |
+
AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
|
| 116 |
+
AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
|
| 117 |
+
|
| 118 |
+
const int batch = value.size(0);
|
| 119 |
+
const int spatial_size = value.size(1);
|
| 120 |
+
const int num_heads = value.size(2);
|
| 121 |
+
const int channels = value.size(3);
|
| 122 |
+
|
| 123 |
+
const int num_levels = spatial_shapes.size(0);
|
| 124 |
+
|
| 125 |
+
const int num_query = sampling_loc.size(1);
|
| 126 |
+
const int num_point = sampling_loc.size(4);
|
| 127 |
+
|
| 128 |
+
const int im2col_step_ = std::min(batch, im2col_step);
|
| 129 |
+
|
| 130 |
+
AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
|
| 131 |
+
|
| 132 |
+
auto grad_value = at::zeros_like(value);
|
| 133 |
+
auto grad_sampling_loc = at::zeros_like(sampling_loc);
|
| 134 |
+
auto grad_attn_weight = at::zeros_like(attn_weight);
|
| 135 |
+
|
| 136 |
+
const int batch_n = im2col_step_;
|
| 137 |
+
auto per_value_size = spatial_size * num_heads * channels;
|
| 138 |
+
auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
|
| 139 |
+
auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
|
| 140 |
+
auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
|
| 141 |
+
|
| 142 |
+
for (int n = 0; n < batch/im2col_step_; ++n)
|
| 143 |
+
{
|
| 144 |
+
auto grad_output_g = grad_output_n.select(0, n);
|
| 145 |
+
AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
|
| 146 |
+
ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
|
| 147 |
+
grad_output_g.data<scalar_t>(),
|
| 148 |
+
value.data<scalar_t>() + n * im2col_step_ * per_value_size,
|
| 149 |
+
spatial_shapes.data<int64_t>(),
|
| 150 |
+
level_start_index.data<int64_t>(),
|
| 151 |
+
sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
|
| 152 |
+
attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size,
|
| 153 |
+
batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
|
| 154 |
+
grad_value.data<scalar_t>() + n * im2col_step_ * per_value_size,
|
| 155 |
+
grad_sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
|
| 156 |
+
grad_attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size);
|
| 157 |
+
|
| 158 |
+
}));
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
return {
|
| 162 |
+
grad_value, grad_sampling_loc, grad_attn_weight
|
| 163 |
+
};
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
const int CUDA_NUM_THREADS = 1024;
|
| 167 |
+
inline int GET_BLOCKS(const int N, const int num_threads)
|
| 168 |
+
{
|
| 169 |
+
return (N + num_threads - 1) / num_threads;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
template <typename scalar_t>
|
| 174 |
+
__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
|
| 175 |
+
const int &height, const int &width, const int &nheads, const int &channels,
|
| 176 |
+
const scalar_t &h, const scalar_t &w, const int &m, const int &c)
|
| 177 |
+
{
|
| 178 |
+
const int h_low = floor(h);
|
| 179 |
+
const int w_low = floor(w);
|
| 180 |
+
const int h_high = h_low + 1;
|
| 181 |
+
const int w_high = w_low + 1;
|
| 182 |
+
|
| 183 |
+
const scalar_t lh = h - h_low;
|
| 184 |
+
const scalar_t lw = w - w_low;
|
| 185 |
+
const scalar_t hh = 1 - lh, hw = 1 - lw;
|
| 186 |
+
|
| 187 |
+
const int w_stride = nheads * channels;
|
| 188 |
+
const int h_stride = width * w_stride;
|
| 189 |
+
const int h_low_ptr_offset = h_low * h_stride;
|
| 190 |
+
const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
|
| 191 |
+
const int w_low_ptr_offset = w_low * w_stride;
|
| 192 |
+
const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
|
| 193 |
+
const int base_ptr = m * channels + c;
|
| 194 |
+
|
| 195 |
+
scalar_t v1 = 0;
|
| 196 |
+
if (h_low >= 0 && w_low >= 0)
|
| 197 |
+
{
|
| 198 |
+
const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 199 |
+
v1 = bottom_data[ptr1];
|
| 200 |
+
}
|
| 201 |
+
scalar_t v2 = 0;
|
| 202 |
+
if (h_low >= 0 && w_high <= width - 1)
|
| 203 |
+
{
|
| 204 |
+
const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 205 |
+
v2 = bottom_data[ptr2];
|
| 206 |
+
}
|
| 207 |
+
scalar_t v3 = 0;
|
| 208 |
+
if (h_high <= height - 1 && w_low >= 0)
|
| 209 |
+
{
|
| 210 |
+
const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 211 |
+
v3 = bottom_data[ptr3];
|
| 212 |
+
}
|
| 213 |
+
scalar_t v4 = 0;
|
| 214 |
+
if (h_high <= height - 1 && w_high <= width - 1)
|
| 215 |
+
{
|
| 216 |
+
const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 217 |
+
v4 = bottom_data[ptr4];
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
|
| 221 |
+
|
| 222 |
+
const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
|
| 223 |
+
return val;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
template <typename scalar_t>
|
| 228 |
+
__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
|
| 229 |
+
const int &height, const int &width, const int &nheads, const int &channels,
|
| 230 |
+
const scalar_t &h, const scalar_t &w, const int &m, const int &c,
|
| 231 |
+
const scalar_t &top_grad,
|
| 232 |
+
const scalar_t &attn_weight,
|
| 233 |
+
scalar_t* &grad_value,
|
| 234 |
+
scalar_t* grad_sampling_loc,
|
| 235 |
+
scalar_t* grad_attn_weight)
|
| 236 |
+
{
|
| 237 |
+
const int h_low = floor(h);
|
| 238 |
+
const int w_low = floor(w);
|
| 239 |
+
const int h_high = h_low + 1;
|
| 240 |
+
const int w_high = w_low + 1;
|
| 241 |
+
|
| 242 |
+
const scalar_t lh = h - h_low;
|
| 243 |
+
const scalar_t lw = w - w_low;
|
| 244 |
+
const scalar_t hh = 1 - lh, hw = 1 - lw;
|
| 245 |
+
|
| 246 |
+
const int w_stride = nheads * channels;
|
| 247 |
+
const int h_stride = width * w_stride;
|
| 248 |
+
const int h_low_ptr_offset = h_low * h_stride;
|
| 249 |
+
const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
|
| 250 |
+
const int w_low_ptr_offset = w_low * w_stride;
|
| 251 |
+
const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
|
| 252 |
+
const int base_ptr = m * channels + c;
|
| 253 |
+
|
| 254 |
+
const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
|
| 255 |
+
const scalar_t top_grad_value = top_grad * attn_weight;
|
| 256 |
+
scalar_t grad_h_weight = 0, grad_w_weight = 0;
|
| 257 |
+
|
| 258 |
+
scalar_t v1 = 0;
|
| 259 |
+
if (h_low >= 0 && w_low >= 0)
|
| 260 |
+
{
|
| 261 |
+
const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 262 |
+
v1 = bottom_data[ptr1];
|
| 263 |
+
grad_h_weight -= hw * v1;
|
| 264 |
+
grad_w_weight -= hh * v1;
|
| 265 |
+
atomicAdd(grad_value+ptr1, w1*top_grad_value);
|
| 266 |
+
}
|
| 267 |
+
scalar_t v2 = 0;
|
| 268 |
+
if (h_low >= 0 && w_high <= width - 1)
|
| 269 |
+
{
|
| 270 |
+
const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 271 |
+
v2 = bottom_data[ptr2];
|
| 272 |
+
grad_h_weight -= lw * v2;
|
| 273 |
+
grad_w_weight += hh * v2;
|
| 274 |
+
atomicAdd(grad_value+ptr2, w2*top_grad_value);
|
| 275 |
+
}
|
| 276 |
+
scalar_t v3 = 0;
|
| 277 |
+
if (h_high <= height - 1 && w_low >= 0)
|
| 278 |
+
{
|
| 279 |
+
const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 280 |
+
v3 = bottom_data[ptr3];
|
| 281 |
+
grad_h_weight += hw * v3;
|
| 282 |
+
grad_w_weight -= lh * v3;
|
| 283 |
+
atomicAdd(grad_value+ptr3, w3*top_grad_value);
|
| 284 |
+
}
|
| 285 |
+
scalar_t v4 = 0;
|
| 286 |
+
if (h_high <= height - 1 && w_high <= width - 1)
|
| 287 |
+
{
|
| 288 |
+
const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 289 |
+
v4 = bottom_data[ptr4];
|
| 290 |
+
grad_h_weight += lw * v4;
|
| 291 |
+
grad_w_weight += lh * v4;
|
| 292 |
+
atomicAdd(grad_value+ptr4, w4*top_grad_value);
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
|
| 296 |
+
*grad_attn_weight = top_grad * val;
|
| 297 |
+
*grad_sampling_loc = width * grad_w_weight * top_grad_value;
|
| 298 |
+
*(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
template <typename scalar_t>
|
| 303 |
+
__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
|
| 304 |
+
const int &height, const int &width, const int &nheads, const int &channels,
|
| 305 |
+
const scalar_t &h, const scalar_t &w, const int &m, const int &c,
|
| 306 |
+
const scalar_t &top_grad,
|
| 307 |
+
const scalar_t &attn_weight,
|
| 308 |
+
scalar_t* &grad_value,
|
| 309 |
+
scalar_t* grad_sampling_loc,
|
| 310 |
+
scalar_t* grad_attn_weight)
|
| 311 |
+
{
|
| 312 |
+
const int h_low = floor(h);
|
| 313 |
+
const int w_low = floor(w);
|
| 314 |
+
const int h_high = h_low + 1;
|
| 315 |
+
const int w_high = w_low + 1;
|
| 316 |
+
|
| 317 |
+
const scalar_t lh = h - h_low;
|
| 318 |
+
const scalar_t lw = w - w_low;
|
| 319 |
+
const scalar_t hh = 1 - lh, hw = 1 - lw;
|
| 320 |
+
|
| 321 |
+
const int w_stride = nheads * channels;
|
| 322 |
+
const int h_stride = width * w_stride;
|
| 323 |
+
const int h_low_ptr_offset = h_low * h_stride;
|
| 324 |
+
const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
|
| 325 |
+
const int w_low_ptr_offset = w_low * w_stride;
|
| 326 |
+
const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
|
| 327 |
+
const int base_ptr = m * channels + c;
|
| 328 |
+
|
| 329 |
+
const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
|
| 330 |
+
const scalar_t top_grad_value = top_grad * attn_weight;
|
| 331 |
+
scalar_t grad_h_weight = 0, grad_w_weight = 0;
|
| 332 |
+
|
| 333 |
+
scalar_t v1 = 0;
|
| 334 |
+
if (h_low >= 0 && w_low >= 0)
|
| 335 |
+
{
|
| 336 |
+
const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 337 |
+
v1 = bottom_data[ptr1];
|
| 338 |
+
grad_h_weight -= hw * v1;
|
| 339 |
+
grad_w_weight -= hh * v1;
|
| 340 |
+
atomicAdd(grad_value+ptr1, w1*top_grad_value);
|
| 341 |
+
}
|
| 342 |
+
scalar_t v2 = 0;
|
| 343 |
+
if (h_low >= 0 && w_high <= width - 1)
|
| 344 |
+
{
|
| 345 |
+
const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 346 |
+
v2 = bottom_data[ptr2];
|
| 347 |
+
grad_h_weight -= lw * v2;
|
| 348 |
+
grad_w_weight += hh * v2;
|
| 349 |
+
atomicAdd(grad_value+ptr2, w2*top_grad_value);
|
| 350 |
+
}
|
| 351 |
+
scalar_t v3 = 0;
|
| 352 |
+
if (h_high <= height - 1 && w_low >= 0)
|
| 353 |
+
{
|
| 354 |
+
const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 355 |
+
v3 = bottom_data[ptr3];
|
| 356 |
+
grad_h_weight += hw * v3;
|
| 357 |
+
grad_w_weight -= lh * v3;
|
| 358 |
+
atomicAdd(grad_value+ptr3, w3*top_grad_value);
|
| 359 |
+
}
|
| 360 |
+
scalar_t v4 = 0;
|
| 361 |
+
if (h_high <= height - 1 && w_high <= width - 1)
|
| 362 |
+
{
|
| 363 |
+
const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 364 |
+
v4 = bottom_data[ptr4];
|
| 365 |
+
grad_h_weight += lw * v4;
|
| 366 |
+
grad_w_weight += lh * v4;
|
| 367 |
+
atomicAdd(grad_value+ptr4, w4*top_grad_value);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
|
| 371 |
+
atomicAdd(grad_attn_weight, top_grad * val);
|
| 372 |
+
atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
|
| 373 |
+
atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
template <typename scalar_t>
|
| 378 |
+
__global__ void ms_deformable_im2col_gpu_kernel(const int n,
|
| 379 |
+
const scalar_t *data_value,
|
| 380 |
+
const int64_t *data_spatial_shapes,
|
| 381 |
+
const int64_t *data_level_start_index,
|
| 382 |
+
const scalar_t *data_sampling_loc,
|
| 383 |
+
const scalar_t *data_attn_weight,
|
| 384 |
+
const int batch_size,
|
| 385 |
+
const int spatial_size,
|
| 386 |
+
const int num_heads,
|
| 387 |
+
const int channels,
|
| 388 |
+
const int num_levels,
|
| 389 |
+
const int num_query,
|
| 390 |
+
const int num_point,
|
| 391 |
+
scalar_t *data_col)
|
| 392 |
+
{
|
| 393 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 394 |
+
{
|
| 395 |
+
int _temp = index;
|
| 396 |
+
const int c_col = _temp % channels;
|
| 397 |
+
_temp /= channels;
|
| 398 |
+
const int sampling_index = _temp;
|
| 399 |
+
const int m_col = _temp % num_heads;
|
| 400 |
+
_temp /= num_heads;
|
| 401 |
+
const int q_col = _temp % num_query;
|
| 402 |
+
_temp /= num_query;
|
| 403 |
+
const int b_col = _temp;
|
| 404 |
+
|
| 405 |
+
scalar_t *data_col_ptr = data_col + index;
|
| 406 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 407 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 408 |
+
const int qid_stride = num_heads * channels;
|
| 409 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 410 |
+
scalar_t col = 0;
|
| 411 |
+
|
| 412 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 413 |
+
{
|
| 414 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 415 |
+
const int spatial_h_ptr = l_col << 1;
|
| 416 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 417 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 418 |
+
const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
|
| 419 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 420 |
+
{
|
| 421 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 422 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 423 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 424 |
+
|
| 425 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 426 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 427 |
+
|
| 428 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 429 |
+
{
|
| 430 |
+
col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
data_weight_ptr += 1;
|
| 434 |
+
data_loc_w_ptr += 2;
|
| 435 |
+
}
|
| 436 |
+
}
|
| 437 |
+
*data_col_ptr = col;
|
| 438 |
+
}
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
template <typename scalar_t, unsigned int blockSize>
|
| 442 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
|
| 443 |
+
const scalar_t *grad_col,
|
| 444 |
+
const scalar_t *data_value,
|
| 445 |
+
const int64_t *data_spatial_shapes,
|
| 446 |
+
const int64_t *data_level_start_index,
|
| 447 |
+
const scalar_t *data_sampling_loc,
|
| 448 |
+
const scalar_t *data_attn_weight,
|
| 449 |
+
const int batch_size,
|
| 450 |
+
const int spatial_size,
|
| 451 |
+
const int num_heads,
|
| 452 |
+
const int channels,
|
| 453 |
+
const int num_levels,
|
| 454 |
+
const int num_query,
|
| 455 |
+
const int num_point,
|
| 456 |
+
scalar_t *grad_value,
|
| 457 |
+
scalar_t *grad_sampling_loc,
|
| 458 |
+
scalar_t *grad_attn_weight)
|
| 459 |
+
{
|
| 460 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 461 |
+
{
|
| 462 |
+
__shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
|
| 463 |
+
__shared__ scalar_t cache_grad_attn_weight[blockSize];
|
| 464 |
+
unsigned int tid = threadIdx.x;
|
| 465 |
+
int _temp = index;
|
| 466 |
+
const int c_col = _temp % channels;
|
| 467 |
+
_temp /= channels;
|
| 468 |
+
const int sampling_index = _temp;
|
| 469 |
+
const int m_col = _temp % num_heads;
|
| 470 |
+
_temp /= num_heads;
|
| 471 |
+
const int q_col = _temp % num_query;
|
| 472 |
+
_temp /= num_query;
|
| 473 |
+
const int b_col = _temp;
|
| 474 |
+
|
| 475 |
+
const scalar_t top_grad = grad_col[index];
|
| 476 |
+
|
| 477 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 478 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 479 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 480 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 481 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 482 |
+
const int grad_weight_stride = 1;
|
| 483 |
+
const int grad_loc_stride = 2;
|
| 484 |
+
const int qid_stride = num_heads * channels;
|
| 485 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 486 |
+
|
| 487 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 488 |
+
{
|
| 489 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 490 |
+
const int spatial_h_ptr = l_col << 1;
|
| 491 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 492 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 493 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 494 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 495 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 496 |
+
|
| 497 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 498 |
+
{
|
| 499 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 500 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 501 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 502 |
+
|
| 503 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 504 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 505 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 506 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 507 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 508 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 509 |
+
{
|
| 510 |
+
ms_deform_attn_col2im_bilinear(
|
| 511 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 512 |
+
top_grad, weight, grad_value_ptr,
|
| 513 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
__syncthreads();
|
| 517 |
+
if (tid == 0)
|
| 518 |
+
{
|
| 519 |
+
scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
|
| 520 |
+
int sid=2;
|
| 521 |
+
for (unsigned int tid = 1; tid < blockSize; ++tid)
|
| 522 |
+
{
|
| 523 |
+
_grad_w += cache_grad_sampling_loc[sid];
|
| 524 |
+
_grad_h += cache_grad_sampling_loc[sid + 1];
|
| 525 |
+
_grad_a += cache_grad_attn_weight[tid];
|
| 526 |
+
sid += 2;
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
*grad_sampling_loc = _grad_w;
|
| 531 |
+
*(grad_sampling_loc + 1) = _grad_h;
|
| 532 |
+
*grad_attn_weight = _grad_a;
|
| 533 |
+
}
|
| 534 |
+
__syncthreads();
|
| 535 |
+
|
| 536 |
+
data_weight_ptr += 1;
|
| 537 |
+
data_loc_w_ptr += 2;
|
| 538 |
+
grad_attn_weight += grad_weight_stride;
|
| 539 |
+
grad_sampling_loc += grad_loc_stride;
|
| 540 |
+
}
|
| 541 |
+
}
|
| 542 |
+
}
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
template <typename scalar_t, unsigned int blockSize>
|
| 547 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
|
| 548 |
+
const scalar_t *grad_col,
|
| 549 |
+
const scalar_t *data_value,
|
| 550 |
+
const int64_t *data_spatial_shapes,
|
| 551 |
+
const int64_t *data_level_start_index,
|
| 552 |
+
const scalar_t *data_sampling_loc,
|
| 553 |
+
const scalar_t *data_attn_weight,
|
| 554 |
+
const int batch_size,
|
| 555 |
+
const int spatial_size,
|
| 556 |
+
const int num_heads,
|
| 557 |
+
const int channels,
|
| 558 |
+
const int num_levels,
|
| 559 |
+
const int num_query,
|
| 560 |
+
const int num_point,
|
| 561 |
+
scalar_t *grad_value,
|
| 562 |
+
scalar_t *grad_sampling_loc,
|
| 563 |
+
scalar_t *grad_attn_weight)
|
| 564 |
+
{
|
| 565 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 566 |
+
{
|
| 567 |
+
__shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
|
| 568 |
+
__shared__ scalar_t cache_grad_attn_weight[blockSize];
|
| 569 |
+
unsigned int tid = threadIdx.x;
|
| 570 |
+
int _temp = index;
|
| 571 |
+
const int c_col = _temp % channels;
|
| 572 |
+
_temp /= channels;
|
| 573 |
+
const int sampling_index = _temp;
|
| 574 |
+
const int m_col = _temp % num_heads;
|
| 575 |
+
_temp /= num_heads;
|
| 576 |
+
const int q_col = _temp % num_query;
|
| 577 |
+
_temp /= num_query;
|
| 578 |
+
const int b_col = _temp;
|
| 579 |
+
|
| 580 |
+
const scalar_t top_grad = grad_col[index];
|
| 581 |
+
|
| 582 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 583 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 584 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 585 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 586 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 587 |
+
const int grad_weight_stride = 1;
|
| 588 |
+
const int grad_loc_stride = 2;
|
| 589 |
+
const int qid_stride = num_heads * channels;
|
| 590 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 591 |
+
|
| 592 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 593 |
+
{
|
| 594 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 595 |
+
const int spatial_h_ptr = l_col << 1;
|
| 596 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 597 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 598 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 599 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 600 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 601 |
+
|
| 602 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 603 |
+
{
|
| 604 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 605 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 606 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 607 |
+
|
| 608 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 609 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 610 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 611 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 612 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 613 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 614 |
+
{
|
| 615 |
+
ms_deform_attn_col2im_bilinear(
|
| 616 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 617 |
+
top_grad, weight, grad_value_ptr,
|
| 618 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
__syncthreads();
|
| 622 |
+
|
| 623 |
+
for (unsigned int s=blockSize/2; s>0; s>>=1)
|
| 624 |
+
{
|
| 625 |
+
if (tid < s) {
|
| 626 |
+
const unsigned int xid1 = tid << 1;
|
| 627 |
+
const unsigned int xid2 = (tid + s) << 1;
|
| 628 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
|
| 629 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
|
| 630 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
|
| 631 |
+
}
|
| 632 |
+
__syncthreads();
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
if (tid == 0)
|
| 636 |
+
{
|
| 637 |
+
*grad_sampling_loc = cache_grad_sampling_loc[0];
|
| 638 |
+
*(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
|
| 639 |
+
*grad_attn_weight = cache_grad_attn_weight[0];
|
| 640 |
+
}
|
| 641 |
+
__syncthreads();
|
| 642 |
+
|
| 643 |
+
data_weight_ptr += 1;
|
| 644 |
+
data_loc_w_ptr += 2;
|
| 645 |
+
grad_attn_weight += grad_weight_stride;
|
| 646 |
+
grad_sampling_loc += grad_loc_stride;
|
| 647 |
+
}
|
| 648 |
+
}
|
| 649 |
+
}
|
| 650 |
+
}
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
template <typename scalar_t>
|
| 654 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
|
| 655 |
+
const scalar_t *grad_col,
|
| 656 |
+
const scalar_t *data_value,
|
| 657 |
+
const int64_t *data_spatial_shapes,
|
| 658 |
+
const int64_t *data_level_start_index,
|
| 659 |
+
const scalar_t *data_sampling_loc,
|
| 660 |
+
const scalar_t *data_attn_weight,
|
| 661 |
+
const int batch_size,
|
| 662 |
+
const int spatial_size,
|
| 663 |
+
const int num_heads,
|
| 664 |
+
const int channels,
|
| 665 |
+
const int num_levels,
|
| 666 |
+
const int num_query,
|
| 667 |
+
const int num_point,
|
| 668 |
+
scalar_t *grad_value,
|
| 669 |
+
scalar_t *grad_sampling_loc,
|
| 670 |
+
scalar_t *grad_attn_weight)
|
| 671 |
+
{
|
| 672 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 673 |
+
{
|
| 674 |
+
extern __shared__ int _s[];
|
| 675 |
+
scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
|
| 676 |
+
scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
|
| 677 |
+
unsigned int tid = threadIdx.x;
|
| 678 |
+
int _temp = index;
|
| 679 |
+
const int c_col = _temp % channels;
|
| 680 |
+
_temp /= channels;
|
| 681 |
+
const int sampling_index = _temp;
|
| 682 |
+
const int m_col = _temp % num_heads;
|
| 683 |
+
_temp /= num_heads;
|
| 684 |
+
const int q_col = _temp % num_query;
|
| 685 |
+
_temp /= num_query;
|
| 686 |
+
const int b_col = _temp;
|
| 687 |
+
|
| 688 |
+
const scalar_t top_grad = grad_col[index];
|
| 689 |
+
|
| 690 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 691 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 692 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 693 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 694 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 695 |
+
const int grad_weight_stride = 1;
|
| 696 |
+
const int grad_loc_stride = 2;
|
| 697 |
+
const int qid_stride = num_heads * channels;
|
| 698 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 699 |
+
|
| 700 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 701 |
+
{
|
| 702 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 703 |
+
const int spatial_h_ptr = l_col << 1;
|
| 704 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 705 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 706 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 707 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 708 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 709 |
+
|
| 710 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 711 |
+
{
|
| 712 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 713 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 714 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 715 |
+
|
| 716 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 717 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 718 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 719 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 720 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 721 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 722 |
+
{
|
| 723 |
+
ms_deform_attn_col2im_bilinear(
|
| 724 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 725 |
+
top_grad, weight, grad_value_ptr,
|
| 726 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
__syncthreads();
|
| 730 |
+
if (tid == 0)
|
| 731 |
+
{
|
| 732 |
+
scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
|
| 733 |
+
int sid=2;
|
| 734 |
+
for (unsigned int tid = 1; tid < blockDim.x; ++tid)
|
| 735 |
+
{
|
| 736 |
+
_grad_w += cache_grad_sampling_loc[sid];
|
| 737 |
+
_grad_h += cache_grad_sampling_loc[sid + 1];
|
| 738 |
+
_grad_a += cache_grad_attn_weight[tid];
|
| 739 |
+
sid += 2;
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
*grad_sampling_loc = _grad_w;
|
| 744 |
+
*(grad_sampling_loc + 1) = _grad_h;
|
| 745 |
+
*grad_attn_weight = _grad_a;
|
| 746 |
+
}
|
| 747 |
+
__syncthreads();
|
| 748 |
+
|
| 749 |
+
data_weight_ptr += 1;
|
| 750 |
+
data_loc_w_ptr += 2;
|
| 751 |
+
grad_attn_weight += grad_weight_stride;
|
| 752 |
+
grad_sampling_loc += grad_loc_stride;
|
| 753 |
+
}
|
| 754 |
+
}
|
| 755 |
+
}
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
template <typename scalar_t>
|
| 759 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
|
| 760 |
+
const scalar_t *grad_col,
|
| 761 |
+
const scalar_t *data_value,
|
| 762 |
+
const int64_t *data_spatial_shapes,
|
| 763 |
+
const int64_t *data_level_start_index,
|
| 764 |
+
const scalar_t *data_sampling_loc,
|
| 765 |
+
const scalar_t *data_attn_weight,
|
| 766 |
+
const int batch_size,
|
| 767 |
+
const int spatial_size,
|
| 768 |
+
const int num_heads,
|
| 769 |
+
const int channels,
|
| 770 |
+
const int num_levels,
|
| 771 |
+
const int num_query,
|
| 772 |
+
const int num_point,
|
| 773 |
+
scalar_t *grad_value,
|
| 774 |
+
scalar_t *grad_sampling_loc,
|
| 775 |
+
scalar_t *grad_attn_weight)
|
| 776 |
+
{
|
| 777 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 778 |
+
{
|
| 779 |
+
extern __shared__ int _s[];
|
| 780 |
+
scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
|
| 781 |
+
scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
|
| 782 |
+
unsigned int tid = threadIdx.x;
|
| 783 |
+
int _temp = index;
|
| 784 |
+
const int c_col = _temp % channels;
|
| 785 |
+
_temp /= channels;
|
| 786 |
+
const int sampling_index = _temp;
|
| 787 |
+
const int m_col = _temp % num_heads;
|
| 788 |
+
_temp /= num_heads;
|
| 789 |
+
const int q_col = _temp % num_query;
|
| 790 |
+
_temp /= num_query;
|
| 791 |
+
const int b_col = _temp;
|
| 792 |
+
|
| 793 |
+
const scalar_t top_grad = grad_col[index];
|
| 794 |
+
|
| 795 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 796 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 797 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 798 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 799 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 800 |
+
const int grad_weight_stride = 1;
|
| 801 |
+
const int grad_loc_stride = 2;
|
| 802 |
+
const int qid_stride = num_heads * channels;
|
| 803 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 804 |
+
|
| 805 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 806 |
+
{
|
| 807 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 808 |
+
const int spatial_h_ptr = l_col << 1;
|
| 809 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 810 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 811 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 812 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 813 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 814 |
+
|
| 815 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 816 |
+
{
|
| 817 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 818 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 819 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 820 |
+
|
| 821 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 822 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 823 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 824 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 825 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 826 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 827 |
+
{
|
| 828 |
+
ms_deform_attn_col2im_bilinear(
|
| 829 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 830 |
+
top_grad, weight, grad_value_ptr,
|
| 831 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 832 |
+
}
|
| 833 |
+
|
| 834 |
+
__syncthreads();
|
| 835 |
+
|
| 836 |
+
for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
|
| 837 |
+
{
|
| 838 |
+
if (tid < s) {
|
| 839 |
+
const unsigned int xid1 = tid << 1;
|
| 840 |
+
const unsigned int xid2 = (tid + s) << 1;
|
| 841 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
|
| 842 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
|
| 843 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
|
| 844 |
+
if (tid + (s << 1) < spre)
|
| 845 |
+
{
|
| 846 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
|
| 847 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
|
| 848 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
|
| 849 |
+
}
|
| 850 |
+
}
|
| 851 |
+
__syncthreads();
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
if (tid == 0)
|
| 855 |
+
{
|
| 856 |
+
*grad_sampling_loc = cache_grad_sampling_loc[0];
|
| 857 |
+
*(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
|
| 858 |
+
*grad_attn_weight = cache_grad_attn_weight[0];
|
| 859 |
+
}
|
| 860 |
+
__syncthreads();
|
| 861 |
+
|
| 862 |
+
data_weight_ptr += 1;
|
| 863 |
+
data_loc_w_ptr += 2;
|
| 864 |
+
grad_attn_weight += grad_weight_stride;
|
| 865 |
+
grad_sampling_loc += grad_loc_stride;
|
| 866 |
+
}
|
| 867 |
+
}
|
| 868 |
+
}
|
| 869 |
+
}
|
| 870 |
+
|
| 871 |
+
template <typename scalar_t>
|
| 872 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
|
| 873 |
+
const scalar_t *grad_col,
|
| 874 |
+
const scalar_t *data_value,
|
| 875 |
+
const int64_t *data_spatial_shapes,
|
| 876 |
+
const int64_t *data_level_start_index,
|
| 877 |
+
const scalar_t *data_sampling_loc,
|
| 878 |
+
const scalar_t *data_attn_weight,
|
| 879 |
+
const int batch_size,
|
| 880 |
+
const int spatial_size,
|
| 881 |
+
const int num_heads,
|
| 882 |
+
const int channels,
|
| 883 |
+
const int num_levels,
|
| 884 |
+
const int num_query,
|
| 885 |
+
const int num_point,
|
| 886 |
+
scalar_t *grad_value,
|
| 887 |
+
scalar_t *grad_sampling_loc,
|
| 888 |
+
scalar_t *grad_attn_weight)
|
| 889 |
+
{
|
| 890 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 891 |
+
{
|
| 892 |
+
extern __shared__ int _s[];
|
| 893 |
+
scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
|
| 894 |
+
scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
|
| 895 |
+
unsigned int tid = threadIdx.x;
|
| 896 |
+
int _temp = index;
|
| 897 |
+
const int c_col = _temp % channels;
|
| 898 |
+
_temp /= channels;
|
| 899 |
+
const int sampling_index = _temp;
|
| 900 |
+
const int m_col = _temp % num_heads;
|
| 901 |
+
_temp /= num_heads;
|
| 902 |
+
const int q_col = _temp % num_query;
|
| 903 |
+
_temp /= num_query;
|
| 904 |
+
const int b_col = _temp;
|
| 905 |
+
|
| 906 |
+
const scalar_t top_grad = grad_col[index];
|
| 907 |
+
|
| 908 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 909 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 910 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 911 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 912 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 913 |
+
const int grad_weight_stride = 1;
|
| 914 |
+
const int grad_loc_stride = 2;
|
| 915 |
+
const int qid_stride = num_heads * channels;
|
| 916 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 917 |
+
|
| 918 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 919 |
+
{
|
| 920 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 921 |
+
const int spatial_h_ptr = l_col << 1;
|
| 922 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 923 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 924 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 925 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 926 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 927 |
+
|
| 928 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 929 |
+
{
|
| 930 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 931 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 932 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 933 |
+
|
| 934 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 935 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 936 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 937 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 938 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 939 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 940 |
+
{
|
| 941 |
+
ms_deform_attn_col2im_bilinear(
|
| 942 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 943 |
+
top_grad, weight, grad_value_ptr,
|
| 944 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 945 |
+
}
|
| 946 |
+
|
| 947 |
+
__syncthreads();
|
| 948 |
+
|
| 949 |
+
for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
|
| 950 |
+
{
|
| 951 |
+
if (tid < s) {
|
| 952 |
+
const unsigned int xid1 = tid << 1;
|
| 953 |
+
const unsigned int xid2 = (tid + s) << 1;
|
| 954 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
|
| 955 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
|
| 956 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
|
| 957 |
+
if (tid + (s << 1) < spre)
|
| 958 |
+
{
|
| 959 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
|
| 960 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
|
| 961 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
|
| 962 |
+
}
|
| 963 |
+
}
|
| 964 |
+
__syncthreads();
|
| 965 |
+
}
|
| 966 |
+
|
| 967 |
+
if (tid == 0)
|
| 968 |
+
{
|
| 969 |
+
atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
|
| 970 |
+
atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
|
| 971 |
+
atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
|
| 972 |
+
}
|
| 973 |
+
__syncthreads();
|
| 974 |
+
|
| 975 |
+
data_weight_ptr += 1;
|
| 976 |
+
data_loc_w_ptr += 2;
|
| 977 |
+
grad_attn_weight += grad_weight_stride;
|
| 978 |
+
grad_sampling_loc += grad_loc_stride;
|
| 979 |
+
}
|
| 980 |
+
}
|
| 981 |
+
}
|
| 982 |
+
}
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
template <typename scalar_t>
|
| 986 |
+
__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
|
| 987 |
+
const scalar_t *grad_col,
|
| 988 |
+
const scalar_t *data_value,
|
| 989 |
+
const int64_t *data_spatial_shapes,
|
| 990 |
+
const int64_t *data_level_start_index,
|
| 991 |
+
const scalar_t *data_sampling_loc,
|
| 992 |
+
const scalar_t *data_attn_weight,
|
| 993 |
+
const int batch_size,
|
| 994 |
+
const int spatial_size,
|
| 995 |
+
const int num_heads,
|
| 996 |
+
const int channels,
|
| 997 |
+
const int num_levels,
|
| 998 |
+
const int num_query,
|
| 999 |
+
const int num_point,
|
| 1000 |
+
scalar_t *grad_value,
|
| 1001 |
+
scalar_t *grad_sampling_loc,
|
| 1002 |
+
scalar_t *grad_attn_weight)
|
| 1003 |
+
{
|
| 1004 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 1005 |
+
{
|
| 1006 |
+
int _temp = index;
|
| 1007 |
+
const int c_col = _temp % channels;
|
| 1008 |
+
_temp /= channels;
|
| 1009 |
+
const int sampling_index = _temp;
|
| 1010 |
+
const int m_col = _temp % num_heads;
|
| 1011 |
+
_temp /= num_heads;
|
| 1012 |
+
const int q_col = _temp % num_query;
|
| 1013 |
+
_temp /= num_query;
|
| 1014 |
+
const int b_col = _temp;
|
| 1015 |
+
|
| 1016 |
+
const scalar_t top_grad = grad_col[index];
|
| 1017 |
+
|
| 1018 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 1019 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 1020 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 1021 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 1022 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 1023 |
+
const int grad_weight_stride = 1;
|
| 1024 |
+
const int grad_loc_stride = 2;
|
| 1025 |
+
const int qid_stride = num_heads * channels;
|
| 1026 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 1027 |
+
|
| 1028 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 1029 |
+
{
|
| 1030 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 1031 |
+
const int spatial_h_ptr = l_col << 1;
|
| 1032 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 1033 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 1034 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 1035 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 1036 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 1037 |
+
|
| 1038 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 1039 |
+
{
|
| 1040 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 1041 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 1042 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 1043 |
+
|
| 1044 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 1045 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 1046 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 1047 |
+
{
|
| 1048 |
+
ms_deform_attn_col2im_bilinear_gm(
|
| 1049 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 1050 |
+
top_grad, weight, grad_value_ptr,
|
| 1051 |
+
grad_sampling_loc, grad_attn_weight);
|
| 1052 |
+
}
|
| 1053 |
+
data_weight_ptr += 1;
|
| 1054 |
+
data_loc_w_ptr += 2;
|
| 1055 |
+
grad_attn_weight += grad_weight_stride;
|
| 1056 |
+
grad_sampling_loc += grad_loc_stride;
|
| 1057 |
+
}
|
| 1058 |
+
}
|
| 1059 |
+
}
|
| 1060 |
+
}
|
| 1061 |
+
|
| 1062 |
+
|
| 1063 |
+
template <typename scalar_t>
|
| 1064 |
+
void ms_deformable_im2col_cuda(cudaStream_t stream,
|
| 1065 |
+
const scalar_t* data_value,
|
| 1066 |
+
const int64_t* data_spatial_shapes,
|
| 1067 |
+
const int64_t* data_level_start_index,
|
| 1068 |
+
const scalar_t* data_sampling_loc,
|
| 1069 |
+
const scalar_t* data_attn_weight,
|
| 1070 |
+
const int batch_size,
|
| 1071 |
+
const int spatial_size,
|
| 1072 |
+
const int num_heads,
|
| 1073 |
+
const int channels,
|
| 1074 |
+
const int num_levels,
|
| 1075 |
+
const int num_query,
|
| 1076 |
+
const int num_point,
|
| 1077 |
+
scalar_t* data_col)
|
| 1078 |
+
{
|
| 1079 |
+
const int num_kernels = batch_size * num_query * num_heads * channels;
|
| 1080 |
+
const int num_actual_kernels = batch_size * num_query * num_heads * channels;
|
| 1081 |
+
const int num_threads = CUDA_NUM_THREADS;
|
| 1082 |
+
ms_deformable_im2col_gpu_kernel<scalar_t>
|
| 1083 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1084 |
+
0, stream>>>(
|
| 1085 |
+
num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
|
| 1086 |
+
batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
|
| 1087 |
+
|
| 1088 |
+
cudaError_t err = cudaGetLastError();
|
| 1089 |
+
if (err != cudaSuccess)
|
| 1090 |
+
{
|
| 1091 |
+
printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
|
| 1092 |
+
}
|
| 1093 |
+
|
| 1094 |
+
}
|
| 1095 |
+
|
| 1096 |
+
template <typename scalar_t>
|
| 1097 |
+
void ms_deformable_col2im_cuda(cudaStream_t stream,
|
| 1098 |
+
const scalar_t* grad_col,
|
| 1099 |
+
const scalar_t* data_value,
|
| 1100 |
+
const int64_t * data_spatial_shapes,
|
| 1101 |
+
const int64_t * data_level_start_index,
|
| 1102 |
+
const scalar_t * data_sampling_loc,
|
| 1103 |
+
const scalar_t * data_attn_weight,
|
| 1104 |
+
const int batch_size,
|
| 1105 |
+
const int spatial_size,
|
| 1106 |
+
const int num_heads,
|
| 1107 |
+
const int channels,
|
| 1108 |
+
const int num_levels,
|
| 1109 |
+
const int num_query,
|
| 1110 |
+
const int num_point,
|
| 1111 |
+
scalar_t* grad_value,
|
| 1112 |
+
scalar_t* grad_sampling_loc,
|
| 1113 |
+
scalar_t* grad_attn_weight)
|
| 1114 |
+
{
|
| 1115 |
+
const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
|
| 1116 |
+
const int num_kernels = batch_size * num_query * num_heads * channels;
|
| 1117 |
+
const int num_actual_kernels = batch_size * num_query * num_heads * channels;
|
| 1118 |
+
if (channels > 1024)
|
| 1119 |
+
{
|
| 1120 |
+
if ((channels & 1023) == 0)
|
| 1121 |
+
{
|
| 1122 |
+
ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks<scalar_t>
|
| 1123 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1124 |
+
num_threads*3*sizeof(scalar_t), stream>>>(
|
| 1125 |
+
num_kernels,
|
| 1126 |
+
grad_col,
|
| 1127 |
+
data_value,
|
| 1128 |
+
data_spatial_shapes,
|
| 1129 |
+
data_level_start_index,
|
| 1130 |
+
data_sampling_loc,
|
| 1131 |
+
data_attn_weight,
|
| 1132 |
+
batch_size,
|
| 1133 |
+
spatial_size,
|
| 1134 |
+
num_heads,
|
| 1135 |
+
channels,
|
| 1136 |
+
num_levels,
|
| 1137 |
+
num_query,
|
| 1138 |
+
num_point,
|
| 1139 |
+
grad_value,
|
| 1140 |
+
grad_sampling_loc,
|
| 1141 |
+
grad_attn_weight);
|
| 1142 |
+
}
|
| 1143 |
+
else
|
| 1144 |
+
{
|
| 1145 |
+
ms_deformable_col2im_gpu_kernel_gm<scalar_t>
|
| 1146 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1147 |
+
0, stream>>>(
|
| 1148 |
+
num_kernels,
|
| 1149 |
+
grad_col,
|
| 1150 |
+
data_value,
|
| 1151 |
+
data_spatial_shapes,
|
| 1152 |
+
data_level_start_index,
|
| 1153 |
+
data_sampling_loc,
|
| 1154 |
+
data_attn_weight,
|
| 1155 |
+
batch_size,
|
| 1156 |
+
spatial_size,
|
| 1157 |
+
num_heads,
|
| 1158 |
+
channels,
|
| 1159 |
+
num_levels,
|
| 1160 |
+
num_query,
|
| 1161 |
+
num_point,
|
| 1162 |
+
grad_value,
|
| 1163 |
+
grad_sampling_loc,
|
| 1164 |
+
grad_attn_weight);
|
| 1165 |
+
}
|
| 1166 |
+
}
|
| 1167 |
+
else{
|
| 1168 |
+
switch(channels)
|
| 1169 |
+
{
|
| 1170 |
+
case 1:
|
| 1171 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 1>
|
| 1172 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1173 |
+
0, stream>>>(
|
| 1174 |
+
num_kernels,
|
| 1175 |
+
grad_col,
|
| 1176 |
+
data_value,
|
| 1177 |
+
data_spatial_shapes,
|
| 1178 |
+
data_level_start_index,
|
| 1179 |
+
data_sampling_loc,
|
| 1180 |
+
data_attn_weight,
|
| 1181 |
+
batch_size,
|
| 1182 |
+
spatial_size,
|
| 1183 |
+
num_heads,
|
| 1184 |
+
channels,
|
| 1185 |
+
num_levels,
|
| 1186 |
+
num_query,
|
| 1187 |
+
num_point,
|
| 1188 |
+
grad_value,
|
| 1189 |
+
grad_sampling_loc,
|
| 1190 |
+
grad_attn_weight);
|
| 1191 |
+
break;
|
| 1192 |
+
case 2:
|
| 1193 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 2>
|
| 1194 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1195 |
+
0, stream>>>(
|
| 1196 |
+
num_kernels,
|
| 1197 |
+
grad_col,
|
| 1198 |
+
data_value,
|
| 1199 |
+
data_spatial_shapes,
|
| 1200 |
+
data_level_start_index,
|
| 1201 |
+
data_sampling_loc,
|
| 1202 |
+
data_attn_weight,
|
| 1203 |
+
batch_size,
|
| 1204 |
+
spatial_size,
|
| 1205 |
+
num_heads,
|
| 1206 |
+
channels,
|
| 1207 |
+
num_levels,
|
| 1208 |
+
num_query,
|
| 1209 |
+
num_point,
|
| 1210 |
+
grad_value,
|
| 1211 |
+
grad_sampling_loc,
|
| 1212 |
+
grad_attn_weight);
|
| 1213 |
+
break;
|
| 1214 |
+
case 4:
|
| 1215 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 4>
|
| 1216 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1217 |
+
0, stream>>>(
|
| 1218 |
+
num_kernels,
|
| 1219 |
+
grad_col,
|
| 1220 |
+
data_value,
|
| 1221 |
+
data_spatial_shapes,
|
| 1222 |
+
data_level_start_index,
|
| 1223 |
+
data_sampling_loc,
|
| 1224 |
+
data_attn_weight,
|
| 1225 |
+
batch_size,
|
| 1226 |
+
spatial_size,
|
| 1227 |
+
num_heads,
|
| 1228 |
+
channels,
|
| 1229 |
+
num_levels,
|
| 1230 |
+
num_query,
|
| 1231 |
+
num_point,
|
| 1232 |
+
grad_value,
|
| 1233 |
+
grad_sampling_loc,
|
| 1234 |
+
grad_attn_weight);
|
| 1235 |
+
break;
|
| 1236 |
+
case 8:
|
| 1237 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 8>
|
| 1238 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1239 |
+
0, stream>>>(
|
| 1240 |
+
num_kernels,
|
| 1241 |
+
grad_col,
|
| 1242 |
+
data_value,
|
| 1243 |
+
data_spatial_shapes,
|
| 1244 |
+
data_level_start_index,
|
| 1245 |
+
data_sampling_loc,
|
| 1246 |
+
data_attn_weight,
|
| 1247 |
+
batch_size,
|
| 1248 |
+
spatial_size,
|
| 1249 |
+
num_heads,
|
| 1250 |
+
channels,
|
| 1251 |
+
num_levels,
|
| 1252 |
+
num_query,
|
| 1253 |
+
num_point,
|
| 1254 |
+
grad_value,
|
| 1255 |
+
grad_sampling_loc,
|
| 1256 |
+
grad_attn_weight);
|
| 1257 |
+
break;
|
| 1258 |
+
case 16:
|
| 1259 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 16>
|
| 1260 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1261 |
+
0, stream>>>(
|
| 1262 |
+
num_kernels,
|
| 1263 |
+
grad_col,
|
| 1264 |
+
data_value,
|
| 1265 |
+
data_spatial_shapes,
|
| 1266 |
+
data_level_start_index,
|
| 1267 |
+
data_sampling_loc,
|
| 1268 |
+
data_attn_weight,
|
| 1269 |
+
batch_size,
|
| 1270 |
+
spatial_size,
|
| 1271 |
+
num_heads,
|
| 1272 |
+
channels,
|
| 1273 |
+
num_levels,
|
| 1274 |
+
num_query,
|
| 1275 |
+
num_point,
|
| 1276 |
+
grad_value,
|
| 1277 |
+
grad_sampling_loc,
|
| 1278 |
+
grad_attn_weight);
|
| 1279 |
+
break;
|
| 1280 |
+
case 32:
|
| 1281 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 32>
|
| 1282 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1283 |
+
0, stream>>>(
|
| 1284 |
+
num_kernels,
|
| 1285 |
+
grad_col,
|
| 1286 |
+
data_value,
|
| 1287 |
+
data_spatial_shapes,
|
| 1288 |
+
data_level_start_index,
|
| 1289 |
+
data_sampling_loc,
|
| 1290 |
+
data_attn_weight,
|
| 1291 |
+
batch_size,
|
| 1292 |
+
spatial_size,
|
| 1293 |
+
num_heads,
|
| 1294 |
+
channels,
|
| 1295 |
+
num_levels,
|
| 1296 |
+
num_query,
|
| 1297 |
+
num_point,
|
| 1298 |
+
grad_value,
|
| 1299 |
+
grad_sampling_loc,
|
| 1300 |
+
grad_attn_weight);
|
| 1301 |
+
break;
|
| 1302 |
+
case 64:
|
| 1303 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 64>
|
| 1304 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1305 |
+
0, stream>>>(
|
| 1306 |
+
num_kernels,
|
| 1307 |
+
grad_col,
|
| 1308 |
+
data_value,
|
| 1309 |
+
data_spatial_shapes,
|
| 1310 |
+
data_level_start_index,
|
| 1311 |
+
data_sampling_loc,
|
| 1312 |
+
data_attn_weight,
|
| 1313 |
+
batch_size,
|
| 1314 |
+
spatial_size,
|
| 1315 |
+
num_heads,
|
| 1316 |
+
channels,
|
| 1317 |
+
num_levels,
|
| 1318 |
+
num_query,
|
| 1319 |
+
num_point,
|
| 1320 |
+
grad_value,
|
| 1321 |
+
grad_sampling_loc,
|
| 1322 |
+
grad_attn_weight);
|
| 1323 |
+
break;
|
| 1324 |
+
case 128:
|
| 1325 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 128>
|
| 1326 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1327 |
+
0, stream>>>(
|
| 1328 |
+
num_kernels,
|
| 1329 |
+
grad_col,
|
| 1330 |
+
data_value,
|
| 1331 |
+
data_spatial_shapes,
|
| 1332 |
+
data_level_start_index,
|
| 1333 |
+
data_sampling_loc,
|
| 1334 |
+
data_attn_weight,
|
| 1335 |
+
batch_size,
|
| 1336 |
+
spatial_size,
|
| 1337 |
+
num_heads,
|
| 1338 |
+
channels,
|
| 1339 |
+
num_levels,
|
| 1340 |
+
num_query,
|
| 1341 |
+
num_point,
|
| 1342 |
+
grad_value,
|
| 1343 |
+
grad_sampling_loc,
|
| 1344 |
+
grad_attn_weight);
|
| 1345 |
+
break;
|
| 1346 |
+
case 256:
|
| 1347 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 256>
|
| 1348 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1349 |
+
0, stream>>>(
|
| 1350 |
+
num_kernels,
|
| 1351 |
+
grad_col,
|
| 1352 |
+
data_value,
|
| 1353 |
+
data_spatial_shapes,
|
| 1354 |
+
data_level_start_index,
|
| 1355 |
+
data_sampling_loc,
|
| 1356 |
+
data_attn_weight,
|
| 1357 |
+
batch_size,
|
| 1358 |
+
spatial_size,
|
| 1359 |
+
num_heads,
|
| 1360 |
+
channels,
|
| 1361 |
+
num_levels,
|
| 1362 |
+
num_query,
|
| 1363 |
+
num_point,
|
| 1364 |
+
grad_value,
|
| 1365 |
+
grad_sampling_loc,
|
| 1366 |
+
grad_attn_weight);
|
| 1367 |
+
break;
|
| 1368 |
+
case 512:
|
| 1369 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 512>
|
| 1370 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1371 |
+
0, stream>>>(
|
| 1372 |
+
num_kernels,
|
| 1373 |
+
grad_col,
|
| 1374 |
+
data_value,
|
| 1375 |
+
data_spatial_shapes,
|
| 1376 |
+
data_level_start_index,
|
| 1377 |
+
data_sampling_loc,
|
| 1378 |
+
data_attn_weight,
|
| 1379 |
+
batch_size,
|
| 1380 |
+
spatial_size,
|
| 1381 |
+
num_heads,
|
| 1382 |
+
channels,
|
| 1383 |
+
num_levels,
|
| 1384 |
+
num_query,
|
| 1385 |
+
num_point,
|
| 1386 |
+
grad_value,
|
| 1387 |
+
grad_sampling_loc,
|
| 1388 |
+
grad_attn_weight);
|
| 1389 |
+
break;
|
| 1390 |
+
case 1024:
|
| 1391 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 1024>
|
| 1392 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1393 |
+
0, stream>>>(
|
| 1394 |
+
num_kernels,
|
| 1395 |
+
grad_col,
|
| 1396 |
+
data_value,
|
| 1397 |
+
data_spatial_shapes,
|
| 1398 |
+
data_level_start_index,
|
| 1399 |
+
data_sampling_loc,
|
| 1400 |
+
data_attn_weight,
|
| 1401 |
+
batch_size,
|
| 1402 |
+
spatial_size,
|
| 1403 |
+
num_heads,
|
| 1404 |
+
channels,
|
| 1405 |
+
num_levels,
|
| 1406 |
+
num_query,
|
| 1407 |
+
num_point,
|
| 1408 |
+
grad_value,
|
| 1409 |
+
grad_sampling_loc,
|
| 1410 |
+
grad_attn_weight);
|
| 1411 |
+
break;
|
| 1412 |
+
default:
|
| 1413 |
+
if (channels < 64)
|
| 1414 |
+
{
|
| 1415 |
+
ms_deformable_col2im_gpu_kernel_shm_reduce_v1<scalar_t>
|
| 1416 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1417 |
+
num_threads*3*sizeof(scalar_t), stream>>>(
|
| 1418 |
+
num_kernels,
|
| 1419 |
+
grad_col,
|
| 1420 |
+
data_value,
|
| 1421 |
+
data_spatial_shapes,
|
| 1422 |
+
data_level_start_index,
|
| 1423 |
+
data_sampling_loc,
|
| 1424 |
+
data_attn_weight,
|
| 1425 |
+
batch_size,
|
| 1426 |
+
spatial_size,
|
| 1427 |
+
num_heads,
|
| 1428 |
+
channels,
|
| 1429 |
+
num_levels,
|
| 1430 |
+
num_query,
|
| 1431 |
+
num_point,
|
| 1432 |
+
grad_value,
|
| 1433 |
+
grad_sampling_loc,
|
| 1434 |
+
grad_attn_weight);
|
| 1435 |
+
}
|
| 1436 |
+
else
|
| 1437 |
+
{
|
| 1438 |
+
ms_deformable_col2im_gpu_kernel_shm_reduce_v2<scalar_t>
|
| 1439 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1440 |
+
num_threads*3*sizeof(scalar_t), stream>>>(
|
| 1441 |
+
num_kernels,
|
| 1442 |
+
grad_col,
|
| 1443 |
+
data_value,
|
| 1444 |
+
data_spatial_shapes,
|
| 1445 |
+
data_level_start_index,
|
| 1446 |
+
data_sampling_loc,
|
| 1447 |
+
data_attn_weight,
|
| 1448 |
+
batch_size,
|
| 1449 |
+
spatial_size,
|
| 1450 |
+
num_heads,
|
| 1451 |
+
channels,
|
| 1452 |
+
num_levels,
|
| 1453 |
+
num_query,
|
| 1454 |
+
num_point,
|
| 1455 |
+
grad_value,
|
| 1456 |
+
grad_sampling_loc,
|
| 1457 |
+
grad_attn_weight);
|
| 1458 |
+
}
|
| 1459 |
+
}
|
| 1460 |
+
}
|
| 1461 |
+
cudaError_t err = cudaGetLastError();
|
| 1462 |
+
if (err != cudaSuccess)
|
| 1463 |
+
{
|
| 1464 |
+
printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
|
| 1465 |
+
}
|
| 1466 |
+
|
| 1467 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_attn_cuda.h
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************************************
|
| 7 |
+
* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
|
| 8 |
+
**************************************************************************************************
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#pragma once
|
| 12 |
+
#include <torch/extension.h>
|
| 13 |
+
|
| 14 |
+
at::Tensor ms_deform_attn_cuda_forward(
|
| 15 |
+
const at::Tensor &value,
|
| 16 |
+
const at::Tensor &spatial_shapes,
|
| 17 |
+
const at::Tensor &level_start_index,
|
| 18 |
+
const at::Tensor &sampling_loc,
|
| 19 |
+
const at::Tensor &attn_weight,
|
| 20 |
+
const int im2col_step);
|
| 21 |
+
|
| 22 |
+
std::vector<at::Tensor> ms_deform_attn_cuda_backward(
|
| 23 |
+
const at::Tensor &value,
|
| 24 |
+
const at::Tensor &spatial_shapes,
|
| 25 |
+
const at::Tensor &level_start_index,
|
| 26 |
+
const at::Tensor &sampling_loc,
|
| 27 |
+
const at::Tensor &attn_weight,
|
| 28 |
+
const at::Tensor &grad_output,
|
| 29 |
+
const int im2col_step);
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/cuda/ms_deform_im2col_cuda.cuh
ADDED
|
@@ -0,0 +1,1327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************
|
| 7 |
+
* Modified from DCN (https://github.com/msracver/Deformable-ConvNets)
|
| 8 |
+
* Copyright (c) 2018 Microsoft
|
| 9 |
+
**************************************************************************
|
| 10 |
+
*/
|
| 11 |
+
|
| 12 |
+
#include <cstdio>
|
| 13 |
+
#include <algorithm>
|
| 14 |
+
#include <cstring>
|
| 15 |
+
|
| 16 |
+
#include <ATen/ATen.h>
|
| 17 |
+
#include <ATen/cuda/CUDAContext.h>
|
| 18 |
+
|
| 19 |
+
#include <THC/THCAtomics.cuh>
|
| 20 |
+
|
| 21 |
+
#define CUDA_KERNEL_LOOP(i, n) \
|
| 22 |
+
for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
|
| 23 |
+
i < (n); \
|
| 24 |
+
i += blockDim.x * gridDim.x)
|
| 25 |
+
|
| 26 |
+
const int CUDA_NUM_THREADS = 1024;
|
| 27 |
+
inline int GET_BLOCKS(const int N, const int num_threads)
|
| 28 |
+
{
|
| 29 |
+
return (N + num_threads - 1) / num_threads;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
template <typename scalar_t>
|
| 34 |
+
__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
|
| 35 |
+
const int &height, const int &width, const int &nheads, const int &channels,
|
| 36 |
+
const scalar_t &h, const scalar_t &w, const int &m, const int &c)
|
| 37 |
+
{
|
| 38 |
+
const int h_low = floor(h);
|
| 39 |
+
const int w_low = floor(w);
|
| 40 |
+
const int h_high = h_low + 1;
|
| 41 |
+
const int w_high = w_low + 1;
|
| 42 |
+
|
| 43 |
+
const scalar_t lh = h - h_low;
|
| 44 |
+
const scalar_t lw = w - w_low;
|
| 45 |
+
const scalar_t hh = 1 - lh, hw = 1 - lw;
|
| 46 |
+
|
| 47 |
+
const int w_stride = nheads * channels;
|
| 48 |
+
const int h_stride = width * w_stride;
|
| 49 |
+
const int h_low_ptr_offset = h_low * h_stride;
|
| 50 |
+
const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
|
| 51 |
+
const int w_low_ptr_offset = w_low * w_stride;
|
| 52 |
+
const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
|
| 53 |
+
const int base_ptr = m * channels + c;
|
| 54 |
+
|
| 55 |
+
scalar_t v1 = 0;
|
| 56 |
+
if (h_low >= 0 && w_low >= 0)
|
| 57 |
+
{
|
| 58 |
+
const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 59 |
+
v1 = bottom_data[ptr1];
|
| 60 |
+
}
|
| 61 |
+
scalar_t v2 = 0;
|
| 62 |
+
if (h_low >= 0 && w_high <= width - 1)
|
| 63 |
+
{
|
| 64 |
+
const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 65 |
+
v2 = bottom_data[ptr2];
|
| 66 |
+
}
|
| 67 |
+
scalar_t v3 = 0;
|
| 68 |
+
if (h_high <= height - 1 && w_low >= 0)
|
| 69 |
+
{
|
| 70 |
+
const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 71 |
+
v3 = bottom_data[ptr3];
|
| 72 |
+
}
|
| 73 |
+
scalar_t v4 = 0;
|
| 74 |
+
if (h_high <= height - 1 && w_high <= width - 1)
|
| 75 |
+
{
|
| 76 |
+
const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 77 |
+
v4 = bottom_data[ptr4];
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
|
| 81 |
+
|
| 82 |
+
const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
|
| 83 |
+
return val;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
template <typename scalar_t>
|
| 88 |
+
__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
|
| 89 |
+
const int &height, const int &width, const int &nheads, const int &channels,
|
| 90 |
+
const scalar_t &h, const scalar_t &w, const int &m, const int &c,
|
| 91 |
+
const scalar_t &top_grad,
|
| 92 |
+
const scalar_t &attn_weight,
|
| 93 |
+
scalar_t* &grad_value,
|
| 94 |
+
scalar_t* grad_sampling_loc,
|
| 95 |
+
scalar_t* grad_attn_weight)
|
| 96 |
+
{
|
| 97 |
+
const int h_low = floor(h);
|
| 98 |
+
const int w_low = floor(w);
|
| 99 |
+
const int h_high = h_low + 1;
|
| 100 |
+
const int w_high = w_low + 1;
|
| 101 |
+
|
| 102 |
+
const scalar_t lh = h - h_low;
|
| 103 |
+
const scalar_t lw = w - w_low;
|
| 104 |
+
const scalar_t hh = 1 - lh, hw = 1 - lw;
|
| 105 |
+
|
| 106 |
+
const int w_stride = nheads * channels;
|
| 107 |
+
const int h_stride = width * w_stride;
|
| 108 |
+
const int h_low_ptr_offset = h_low * h_stride;
|
| 109 |
+
const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
|
| 110 |
+
const int w_low_ptr_offset = w_low * w_stride;
|
| 111 |
+
const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
|
| 112 |
+
const int base_ptr = m * channels + c;
|
| 113 |
+
|
| 114 |
+
const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
|
| 115 |
+
const scalar_t top_grad_value = top_grad * attn_weight;
|
| 116 |
+
scalar_t grad_h_weight = 0, grad_w_weight = 0;
|
| 117 |
+
|
| 118 |
+
scalar_t v1 = 0;
|
| 119 |
+
if (h_low >= 0 && w_low >= 0)
|
| 120 |
+
{
|
| 121 |
+
const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 122 |
+
v1 = bottom_data[ptr1];
|
| 123 |
+
grad_h_weight -= hw * v1;
|
| 124 |
+
grad_w_weight -= hh * v1;
|
| 125 |
+
atomicAdd(grad_value+ptr1, w1*top_grad_value);
|
| 126 |
+
}
|
| 127 |
+
scalar_t v2 = 0;
|
| 128 |
+
if (h_low >= 0 && w_high <= width - 1)
|
| 129 |
+
{
|
| 130 |
+
const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 131 |
+
v2 = bottom_data[ptr2];
|
| 132 |
+
grad_h_weight -= lw * v2;
|
| 133 |
+
grad_w_weight += hh * v2;
|
| 134 |
+
atomicAdd(grad_value+ptr2, w2*top_grad_value);
|
| 135 |
+
}
|
| 136 |
+
scalar_t v3 = 0;
|
| 137 |
+
if (h_high <= height - 1 && w_low >= 0)
|
| 138 |
+
{
|
| 139 |
+
const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 140 |
+
v3 = bottom_data[ptr3];
|
| 141 |
+
grad_h_weight += hw * v3;
|
| 142 |
+
grad_w_weight -= lh * v3;
|
| 143 |
+
atomicAdd(grad_value+ptr3, w3*top_grad_value);
|
| 144 |
+
}
|
| 145 |
+
scalar_t v4 = 0;
|
| 146 |
+
if (h_high <= height - 1 && w_high <= width - 1)
|
| 147 |
+
{
|
| 148 |
+
const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 149 |
+
v4 = bottom_data[ptr4];
|
| 150 |
+
grad_h_weight += lw * v4;
|
| 151 |
+
grad_w_weight += lh * v4;
|
| 152 |
+
atomicAdd(grad_value+ptr4, w4*top_grad_value);
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
|
| 156 |
+
*grad_attn_weight = top_grad * val;
|
| 157 |
+
*grad_sampling_loc = width * grad_w_weight * top_grad_value;
|
| 158 |
+
*(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
template <typename scalar_t>
|
| 163 |
+
__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
|
| 164 |
+
const int &height, const int &width, const int &nheads, const int &channels,
|
| 165 |
+
const scalar_t &h, const scalar_t &w, const int &m, const int &c,
|
| 166 |
+
const scalar_t &top_grad,
|
| 167 |
+
const scalar_t &attn_weight,
|
| 168 |
+
scalar_t* &grad_value,
|
| 169 |
+
scalar_t* grad_sampling_loc,
|
| 170 |
+
scalar_t* grad_attn_weight)
|
| 171 |
+
{
|
| 172 |
+
const int h_low = floor(h);
|
| 173 |
+
const int w_low = floor(w);
|
| 174 |
+
const int h_high = h_low + 1;
|
| 175 |
+
const int w_high = w_low + 1;
|
| 176 |
+
|
| 177 |
+
const scalar_t lh = h - h_low;
|
| 178 |
+
const scalar_t lw = w - w_low;
|
| 179 |
+
const scalar_t hh = 1 - lh, hw = 1 - lw;
|
| 180 |
+
|
| 181 |
+
const int w_stride = nheads * channels;
|
| 182 |
+
const int h_stride = width * w_stride;
|
| 183 |
+
const int h_low_ptr_offset = h_low * h_stride;
|
| 184 |
+
const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
|
| 185 |
+
const int w_low_ptr_offset = w_low * w_stride;
|
| 186 |
+
const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
|
| 187 |
+
const int base_ptr = m * channels + c;
|
| 188 |
+
|
| 189 |
+
const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
|
| 190 |
+
const scalar_t top_grad_value = top_grad * attn_weight;
|
| 191 |
+
scalar_t grad_h_weight = 0, grad_w_weight = 0;
|
| 192 |
+
|
| 193 |
+
scalar_t v1 = 0;
|
| 194 |
+
if (h_low >= 0 && w_low >= 0)
|
| 195 |
+
{
|
| 196 |
+
const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 197 |
+
v1 = bottom_data[ptr1];
|
| 198 |
+
grad_h_weight -= hw * v1;
|
| 199 |
+
grad_w_weight -= hh * v1;
|
| 200 |
+
atomicAdd(grad_value+ptr1, w1*top_grad_value);
|
| 201 |
+
}
|
| 202 |
+
scalar_t v2 = 0;
|
| 203 |
+
if (h_low >= 0 && w_high <= width - 1)
|
| 204 |
+
{
|
| 205 |
+
const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 206 |
+
v2 = bottom_data[ptr2];
|
| 207 |
+
grad_h_weight -= lw * v2;
|
| 208 |
+
grad_w_weight += hh * v2;
|
| 209 |
+
atomicAdd(grad_value+ptr2, w2*top_grad_value);
|
| 210 |
+
}
|
| 211 |
+
scalar_t v3 = 0;
|
| 212 |
+
if (h_high <= height - 1 && w_low >= 0)
|
| 213 |
+
{
|
| 214 |
+
const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
|
| 215 |
+
v3 = bottom_data[ptr3];
|
| 216 |
+
grad_h_weight += hw * v3;
|
| 217 |
+
grad_w_weight -= lh * v3;
|
| 218 |
+
atomicAdd(grad_value+ptr3, w3*top_grad_value);
|
| 219 |
+
}
|
| 220 |
+
scalar_t v4 = 0;
|
| 221 |
+
if (h_high <= height - 1 && w_high <= width - 1)
|
| 222 |
+
{
|
| 223 |
+
const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
|
| 224 |
+
v4 = bottom_data[ptr4];
|
| 225 |
+
grad_h_weight += lw * v4;
|
| 226 |
+
grad_w_weight += lh * v4;
|
| 227 |
+
atomicAdd(grad_value+ptr4, w4*top_grad_value);
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
|
| 231 |
+
atomicAdd(grad_attn_weight, top_grad * val);
|
| 232 |
+
atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
|
| 233 |
+
atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
template <typename scalar_t>
|
| 238 |
+
__global__ void ms_deformable_im2col_gpu_kernel(const int n,
|
| 239 |
+
const scalar_t *data_value,
|
| 240 |
+
const int64_t *data_spatial_shapes,
|
| 241 |
+
const int64_t *data_level_start_index,
|
| 242 |
+
const scalar_t *data_sampling_loc,
|
| 243 |
+
const scalar_t *data_attn_weight,
|
| 244 |
+
const int batch_size,
|
| 245 |
+
const int spatial_size,
|
| 246 |
+
const int num_heads,
|
| 247 |
+
const int channels,
|
| 248 |
+
const int num_levels,
|
| 249 |
+
const int num_query,
|
| 250 |
+
const int num_point,
|
| 251 |
+
scalar_t *data_col)
|
| 252 |
+
{
|
| 253 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 254 |
+
{
|
| 255 |
+
int _temp = index;
|
| 256 |
+
const int c_col = _temp % channels;
|
| 257 |
+
_temp /= channels;
|
| 258 |
+
const int sampling_index = _temp;
|
| 259 |
+
const int m_col = _temp % num_heads;
|
| 260 |
+
_temp /= num_heads;
|
| 261 |
+
const int q_col = _temp % num_query;
|
| 262 |
+
_temp /= num_query;
|
| 263 |
+
const int b_col = _temp;
|
| 264 |
+
|
| 265 |
+
scalar_t *data_col_ptr = data_col + index;
|
| 266 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 267 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 268 |
+
const int qid_stride = num_heads * channels;
|
| 269 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 270 |
+
scalar_t col = 0;
|
| 271 |
+
|
| 272 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 273 |
+
{
|
| 274 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 275 |
+
const int spatial_h_ptr = l_col << 1;
|
| 276 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 277 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 278 |
+
const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
|
| 279 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 280 |
+
{
|
| 281 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 282 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 283 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 284 |
+
|
| 285 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 286 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 287 |
+
|
| 288 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 289 |
+
{
|
| 290 |
+
col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
data_weight_ptr += 1;
|
| 294 |
+
data_loc_w_ptr += 2;
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
*data_col_ptr = col;
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
template <typename scalar_t, unsigned int blockSize>
|
| 302 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
|
| 303 |
+
const scalar_t *grad_col,
|
| 304 |
+
const scalar_t *data_value,
|
| 305 |
+
const int64_t *data_spatial_shapes,
|
| 306 |
+
const int64_t *data_level_start_index,
|
| 307 |
+
const scalar_t *data_sampling_loc,
|
| 308 |
+
const scalar_t *data_attn_weight,
|
| 309 |
+
const int batch_size,
|
| 310 |
+
const int spatial_size,
|
| 311 |
+
const int num_heads,
|
| 312 |
+
const int channels,
|
| 313 |
+
const int num_levels,
|
| 314 |
+
const int num_query,
|
| 315 |
+
const int num_point,
|
| 316 |
+
scalar_t *grad_value,
|
| 317 |
+
scalar_t *grad_sampling_loc,
|
| 318 |
+
scalar_t *grad_attn_weight)
|
| 319 |
+
{
|
| 320 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 321 |
+
{
|
| 322 |
+
__shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
|
| 323 |
+
__shared__ scalar_t cache_grad_attn_weight[blockSize];
|
| 324 |
+
unsigned int tid = threadIdx.x;
|
| 325 |
+
int _temp = index;
|
| 326 |
+
const int c_col = _temp % channels;
|
| 327 |
+
_temp /= channels;
|
| 328 |
+
const int sampling_index = _temp;
|
| 329 |
+
const int m_col = _temp % num_heads;
|
| 330 |
+
_temp /= num_heads;
|
| 331 |
+
const int q_col = _temp % num_query;
|
| 332 |
+
_temp /= num_query;
|
| 333 |
+
const int b_col = _temp;
|
| 334 |
+
|
| 335 |
+
const scalar_t top_grad = grad_col[index];
|
| 336 |
+
|
| 337 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 338 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 339 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 340 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 341 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 342 |
+
const int grad_weight_stride = 1;
|
| 343 |
+
const int grad_loc_stride = 2;
|
| 344 |
+
const int qid_stride = num_heads * channels;
|
| 345 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 346 |
+
|
| 347 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 348 |
+
{
|
| 349 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 350 |
+
const int spatial_h_ptr = l_col << 1;
|
| 351 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 352 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 353 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 354 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 355 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 356 |
+
|
| 357 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 358 |
+
{
|
| 359 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 360 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 361 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 362 |
+
|
| 363 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 364 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 365 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 366 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 367 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 368 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 369 |
+
{
|
| 370 |
+
ms_deform_attn_col2im_bilinear(
|
| 371 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 372 |
+
top_grad, weight, grad_value_ptr,
|
| 373 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
__syncthreads();
|
| 377 |
+
if (tid == 0)
|
| 378 |
+
{
|
| 379 |
+
scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
|
| 380 |
+
int sid=2;
|
| 381 |
+
for (unsigned int tid = 1; tid < blockSize; ++tid)
|
| 382 |
+
{
|
| 383 |
+
_grad_w += cache_grad_sampling_loc[sid];
|
| 384 |
+
_grad_h += cache_grad_sampling_loc[sid + 1];
|
| 385 |
+
_grad_a += cache_grad_attn_weight[tid];
|
| 386 |
+
sid += 2;
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
*grad_sampling_loc = _grad_w;
|
| 391 |
+
*(grad_sampling_loc + 1) = _grad_h;
|
| 392 |
+
*grad_attn_weight = _grad_a;
|
| 393 |
+
}
|
| 394 |
+
__syncthreads();
|
| 395 |
+
|
| 396 |
+
data_weight_ptr += 1;
|
| 397 |
+
data_loc_w_ptr += 2;
|
| 398 |
+
grad_attn_weight += grad_weight_stride;
|
| 399 |
+
grad_sampling_loc += grad_loc_stride;
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
}
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
template <typename scalar_t, unsigned int blockSize>
|
| 407 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
|
| 408 |
+
const scalar_t *grad_col,
|
| 409 |
+
const scalar_t *data_value,
|
| 410 |
+
const int64_t *data_spatial_shapes,
|
| 411 |
+
const int64_t *data_level_start_index,
|
| 412 |
+
const scalar_t *data_sampling_loc,
|
| 413 |
+
const scalar_t *data_attn_weight,
|
| 414 |
+
const int batch_size,
|
| 415 |
+
const int spatial_size,
|
| 416 |
+
const int num_heads,
|
| 417 |
+
const int channels,
|
| 418 |
+
const int num_levels,
|
| 419 |
+
const int num_query,
|
| 420 |
+
const int num_point,
|
| 421 |
+
scalar_t *grad_value,
|
| 422 |
+
scalar_t *grad_sampling_loc,
|
| 423 |
+
scalar_t *grad_attn_weight)
|
| 424 |
+
{
|
| 425 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 426 |
+
{
|
| 427 |
+
__shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
|
| 428 |
+
__shared__ scalar_t cache_grad_attn_weight[blockSize];
|
| 429 |
+
unsigned int tid = threadIdx.x;
|
| 430 |
+
int _temp = index;
|
| 431 |
+
const int c_col = _temp % channels;
|
| 432 |
+
_temp /= channels;
|
| 433 |
+
const int sampling_index = _temp;
|
| 434 |
+
const int m_col = _temp % num_heads;
|
| 435 |
+
_temp /= num_heads;
|
| 436 |
+
const int q_col = _temp % num_query;
|
| 437 |
+
_temp /= num_query;
|
| 438 |
+
const int b_col = _temp;
|
| 439 |
+
|
| 440 |
+
const scalar_t top_grad = grad_col[index];
|
| 441 |
+
|
| 442 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 443 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 444 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 445 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 446 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 447 |
+
const int grad_weight_stride = 1;
|
| 448 |
+
const int grad_loc_stride = 2;
|
| 449 |
+
const int qid_stride = num_heads * channels;
|
| 450 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 451 |
+
|
| 452 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 453 |
+
{
|
| 454 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 455 |
+
const int spatial_h_ptr = l_col << 1;
|
| 456 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 457 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 458 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 459 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 460 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 461 |
+
|
| 462 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 463 |
+
{
|
| 464 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 465 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 466 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 467 |
+
|
| 468 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 469 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 470 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 471 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 472 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 473 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 474 |
+
{
|
| 475 |
+
ms_deform_attn_col2im_bilinear(
|
| 476 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 477 |
+
top_grad, weight, grad_value_ptr,
|
| 478 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
__syncthreads();
|
| 482 |
+
|
| 483 |
+
for (unsigned int s=blockSize/2; s>0; s>>=1)
|
| 484 |
+
{
|
| 485 |
+
if (tid < s) {
|
| 486 |
+
const unsigned int xid1 = tid << 1;
|
| 487 |
+
const unsigned int xid2 = (tid + s) << 1;
|
| 488 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
|
| 489 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
|
| 490 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
|
| 491 |
+
}
|
| 492 |
+
__syncthreads();
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
if (tid == 0)
|
| 496 |
+
{
|
| 497 |
+
*grad_sampling_loc = cache_grad_sampling_loc[0];
|
| 498 |
+
*(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
|
| 499 |
+
*grad_attn_weight = cache_grad_attn_weight[0];
|
| 500 |
+
}
|
| 501 |
+
__syncthreads();
|
| 502 |
+
|
| 503 |
+
data_weight_ptr += 1;
|
| 504 |
+
data_loc_w_ptr += 2;
|
| 505 |
+
grad_attn_weight += grad_weight_stride;
|
| 506 |
+
grad_sampling_loc += grad_loc_stride;
|
| 507 |
+
}
|
| 508 |
+
}
|
| 509 |
+
}
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
template <typename scalar_t>
|
| 514 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
|
| 515 |
+
const scalar_t *grad_col,
|
| 516 |
+
const scalar_t *data_value,
|
| 517 |
+
const int64_t *data_spatial_shapes,
|
| 518 |
+
const int64_t *data_level_start_index,
|
| 519 |
+
const scalar_t *data_sampling_loc,
|
| 520 |
+
const scalar_t *data_attn_weight,
|
| 521 |
+
const int batch_size,
|
| 522 |
+
const int spatial_size,
|
| 523 |
+
const int num_heads,
|
| 524 |
+
const int channels,
|
| 525 |
+
const int num_levels,
|
| 526 |
+
const int num_query,
|
| 527 |
+
const int num_point,
|
| 528 |
+
scalar_t *grad_value,
|
| 529 |
+
scalar_t *grad_sampling_loc,
|
| 530 |
+
scalar_t *grad_attn_weight)
|
| 531 |
+
{
|
| 532 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 533 |
+
{
|
| 534 |
+
extern __shared__ int _s[];
|
| 535 |
+
scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
|
| 536 |
+
scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
|
| 537 |
+
unsigned int tid = threadIdx.x;
|
| 538 |
+
int _temp = index;
|
| 539 |
+
const int c_col = _temp % channels;
|
| 540 |
+
_temp /= channels;
|
| 541 |
+
const int sampling_index = _temp;
|
| 542 |
+
const int m_col = _temp % num_heads;
|
| 543 |
+
_temp /= num_heads;
|
| 544 |
+
const int q_col = _temp % num_query;
|
| 545 |
+
_temp /= num_query;
|
| 546 |
+
const int b_col = _temp;
|
| 547 |
+
|
| 548 |
+
const scalar_t top_grad = grad_col[index];
|
| 549 |
+
|
| 550 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 551 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 552 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 553 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 554 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 555 |
+
const int grad_weight_stride = 1;
|
| 556 |
+
const int grad_loc_stride = 2;
|
| 557 |
+
const int qid_stride = num_heads * channels;
|
| 558 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 559 |
+
|
| 560 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 561 |
+
{
|
| 562 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 563 |
+
const int spatial_h_ptr = l_col << 1;
|
| 564 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 565 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 566 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 567 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 568 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 569 |
+
|
| 570 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 571 |
+
{
|
| 572 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 573 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 574 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 575 |
+
|
| 576 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 577 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 578 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 579 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 580 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 581 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 582 |
+
{
|
| 583 |
+
ms_deform_attn_col2im_bilinear(
|
| 584 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 585 |
+
top_grad, weight, grad_value_ptr,
|
| 586 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
__syncthreads();
|
| 590 |
+
if (tid == 0)
|
| 591 |
+
{
|
| 592 |
+
scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
|
| 593 |
+
int sid=2;
|
| 594 |
+
for (unsigned int tid = 1; tid < blockDim.x; ++tid)
|
| 595 |
+
{
|
| 596 |
+
_grad_w += cache_grad_sampling_loc[sid];
|
| 597 |
+
_grad_h += cache_grad_sampling_loc[sid + 1];
|
| 598 |
+
_grad_a += cache_grad_attn_weight[tid];
|
| 599 |
+
sid += 2;
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
*grad_sampling_loc = _grad_w;
|
| 604 |
+
*(grad_sampling_loc + 1) = _grad_h;
|
| 605 |
+
*grad_attn_weight = _grad_a;
|
| 606 |
+
}
|
| 607 |
+
__syncthreads();
|
| 608 |
+
|
| 609 |
+
data_weight_ptr += 1;
|
| 610 |
+
data_loc_w_ptr += 2;
|
| 611 |
+
grad_attn_weight += grad_weight_stride;
|
| 612 |
+
grad_sampling_loc += grad_loc_stride;
|
| 613 |
+
}
|
| 614 |
+
}
|
| 615 |
+
}
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
template <typename scalar_t>
|
| 619 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
|
| 620 |
+
const scalar_t *grad_col,
|
| 621 |
+
const scalar_t *data_value,
|
| 622 |
+
const int64_t *data_spatial_shapes,
|
| 623 |
+
const int64_t *data_level_start_index,
|
| 624 |
+
const scalar_t *data_sampling_loc,
|
| 625 |
+
const scalar_t *data_attn_weight,
|
| 626 |
+
const int batch_size,
|
| 627 |
+
const int spatial_size,
|
| 628 |
+
const int num_heads,
|
| 629 |
+
const int channels,
|
| 630 |
+
const int num_levels,
|
| 631 |
+
const int num_query,
|
| 632 |
+
const int num_point,
|
| 633 |
+
scalar_t *grad_value,
|
| 634 |
+
scalar_t *grad_sampling_loc,
|
| 635 |
+
scalar_t *grad_attn_weight)
|
| 636 |
+
{
|
| 637 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 638 |
+
{
|
| 639 |
+
extern __shared__ int _s[];
|
| 640 |
+
scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
|
| 641 |
+
scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
|
| 642 |
+
unsigned int tid = threadIdx.x;
|
| 643 |
+
int _temp = index;
|
| 644 |
+
const int c_col = _temp % channels;
|
| 645 |
+
_temp /= channels;
|
| 646 |
+
const int sampling_index = _temp;
|
| 647 |
+
const int m_col = _temp % num_heads;
|
| 648 |
+
_temp /= num_heads;
|
| 649 |
+
const int q_col = _temp % num_query;
|
| 650 |
+
_temp /= num_query;
|
| 651 |
+
const int b_col = _temp;
|
| 652 |
+
|
| 653 |
+
const scalar_t top_grad = grad_col[index];
|
| 654 |
+
|
| 655 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 656 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 657 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 658 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 659 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 660 |
+
const int grad_weight_stride = 1;
|
| 661 |
+
const int grad_loc_stride = 2;
|
| 662 |
+
const int qid_stride = num_heads * channels;
|
| 663 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 664 |
+
|
| 665 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 666 |
+
{
|
| 667 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 668 |
+
const int spatial_h_ptr = l_col << 1;
|
| 669 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 670 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 671 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 672 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 673 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 674 |
+
|
| 675 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 676 |
+
{
|
| 677 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 678 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 679 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 680 |
+
|
| 681 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 682 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 683 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 684 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 685 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 686 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 687 |
+
{
|
| 688 |
+
ms_deform_attn_col2im_bilinear(
|
| 689 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 690 |
+
top_grad, weight, grad_value_ptr,
|
| 691 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
__syncthreads();
|
| 695 |
+
|
| 696 |
+
for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
|
| 697 |
+
{
|
| 698 |
+
if (tid < s) {
|
| 699 |
+
const unsigned int xid1 = tid << 1;
|
| 700 |
+
const unsigned int xid2 = (tid + s) << 1;
|
| 701 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
|
| 702 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
|
| 703 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
|
| 704 |
+
if (tid + (s << 1) < spre)
|
| 705 |
+
{
|
| 706 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
|
| 707 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
|
| 708 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
|
| 709 |
+
}
|
| 710 |
+
}
|
| 711 |
+
__syncthreads();
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
if (tid == 0)
|
| 715 |
+
{
|
| 716 |
+
*grad_sampling_loc = cache_grad_sampling_loc[0];
|
| 717 |
+
*(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
|
| 718 |
+
*grad_attn_weight = cache_grad_attn_weight[0];
|
| 719 |
+
}
|
| 720 |
+
__syncthreads();
|
| 721 |
+
|
| 722 |
+
data_weight_ptr += 1;
|
| 723 |
+
data_loc_w_ptr += 2;
|
| 724 |
+
grad_attn_weight += grad_weight_stride;
|
| 725 |
+
grad_sampling_loc += grad_loc_stride;
|
| 726 |
+
}
|
| 727 |
+
}
|
| 728 |
+
}
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
template <typename scalar_t>
|
| 732 |
+
__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
|
| 733 |
+
const scalar_t *grad_col,
|
| 734 |
+
const scalar_t *data_value,
|
| 735 |
+
const int64_t *data_spatial_shapes,
|
| 736 |
+
const int64_t *data_level_start_index,
|
| 737 |
+
const scalar_t *data_sampling_loc,
|
| 738 |
+
const scalar_t *data_attn_weight,
|
| 739 |
+
const int batch_size,
|
| 740 |
+
const int spatial_size,
|
| 741 |
+
const int num_heads,
|
| 742 |
+
const int channels,
|
| 743 |
+
const int num_levels,
|
| 744 |
+
const int num_query,
|
| 745 |
+
const int num_point,
|
| 746 |
+
scalar_t *grad_value,
|
| 747 |
+
scalar_t *grad_sampling_loc,
|
| 748 |
+
scalar_t *grad_attn_weight)
|
| 749 |
+
{
|
| 750 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 751 |
+
{
|
| 752 |
+
extern __shared__ int _s[];
|
| 753 |
+
scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
|
| 754 |
+
scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
|
| 755 |
+
unsigned int tid = threadIdx.x;
|
| 756 |
+
int _temp = index;
|
| 757 |
+
const int c_col = _temp % channels;
|
| 758 |
+
_temp /= channels;
|
| 759 |
+
const int sampling_index = _temp;
|
| 760 |
+
const int m_col = _temp % num_heads;
|
| 761 |
+
_temp /= num_heads;
|
| 762 |
+
const int q_col = _temp % num_query;
|
| 763 |
+
_temp /= num_query;
|
| 764 |
+
const int b_col = _temp;
|
| 765 |
+
|
| 766 |
+
const scalar_t top_grad = grad_col[index];
|
| 767 |
+
|
| 768 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 769 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 770 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 771 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 772 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 773 |
+
const int grad_weight_stride = 1;
|
| 774 |
+
const int grad_loc_stride = 2;
|
| 775 |
+
const int qid_stride = num_heads * channels;
|
| 776 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 777 |
+
|
| 778 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 779 |
+
{
|
| 780 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 781 |
+
const int spatial_h_ptr = l_col << 1;
|
| 782 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 783 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 784 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 785 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 786 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 787 |
+
|
| 788 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 789 |
+
{
|
| 790 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 791 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 792 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 793 |
+
|
| 794 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 795 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 796 |
+
*(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
|
| 797 |
+
*(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
|
| 798 |
+
*(cache_grad_attn_weight+threadIdx.x)=0;
|
| 799 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 800 |
+
{
|
| 801 |
+
ms_deform_attn_col2im_bilinear(
|
| 802 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 803 |
+
top_grad, weight, grad_value_ptr,
|
| 804 |
+
cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
|
| 805 |
+
}
|
| 806 |
+
|
| 807 |
+
__syncthreads();
|
| 808 |
+
|
| 809 |
+
for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
|
| 810 |
+
{
|
| 811 |
+
if (tid < s) {
|
| 812 |
+
const unsigned int xid1 = tid << 1;
|
| 813 |
+
const unsigned int xid2 = (tid + s) << 1;
|
| 814 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
|
| 815 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
|
| 816 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
|
| 817 |
+
if (tid + (s << 1) < spre)
|
| 818 |
+
{
|
| 819 |
+
cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
|
| 820 |
+
cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
|
| 821 |
+
cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
|
| 822 |
+
}
|
| 823 |
+
}
|
| 824 |
+
__syncthreads();
|
| 825 |
+
}
|
| 826 |
+
|
| 827 |
+
if (tid == 0)
|
| 828 |
+
{
|
| 829 |
+
atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
|
| 830 |
+
atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
|
| 831 |
+
atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
|
| 832 |
+
}
|
| 833 |
+
__syncthreads();
|
| 834 |
+
|
| 835 |
+
data_weight_ptr += 1;
|
| 836 |
+
data_loc_w_ptr += 2;
|
| 837 |
+
grad_attn_weight += grad_weight_stride;
|
| 838 |
+
grad_sampling_loc += grad_loc_stride;
|
| 839 |
+
}
|
| 840 |
+
}
|
| 841 |
+
}
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
template <typename scalar_t>
|
| 846 |
+
__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
|
| 847 |
+
const scalar_t *grad_col,
|
| 848 |
+
const scalar_t *data_value,
|
| 849 |
+
const int64_t *data_spatial_shapes,
|
| 850 |
+
const int64_t *data_level_start_index,
|
| 851 |
+
const scalar_t *data_sampling_loc,
|
| 852 |
+
const scalar_t *data_attn_weight,
|
| 853 |
+
const int batch_size,
|
| 854 |
+
const int spatial_size,
|
| 855 |
+
const int num_heads,
|
| 856 |
+
const int channels,
|
| 857 |
+
const int num_levels,
|
| 858 |
+
const int num_query,
|
| 859 |
+
const int num_point,
|
| 860 |
+
scalar_t *grad_value,
|
| 861 |
+
scalar_t *grad_sampling_loc,
|
| 862 |
+
scalar_t *grad_attn_weight)
|
| 863 |
+
{
|
| 864 |
+
CUDA_KERNEL_LOOP(index, n)
|
| 865 |
+
{
|
| 866 |
+
int _temp = index;
|
| 867 |
+
const int c_col = _temp % channels;
|
| 868 |
+
_temp /= channels;
|
| 869 |
+
const int sampling_index = _temp;
|
| 870 |
+
const int m_col = _temp % num_heads;
|
| 871 |
+
_temp /= num_heads;
|
| 872 |
+
const int q_col = _temp % num_query;
|
| 873 |
+
_temp /= num_query;
|
| 874 |
+
const int b_col = _temp;
|
| 875 |
+
|
| 876 |
+
const scalar_t top_grad = grad_col[index];
|
| 877 |
+
|
| 878 |
+
int data_weight_ptr = sampling_index * num_levels * num_point;
|
| 879 |
+
int data_loc_w_ptr = data_weight_ptr << 1;
|
| 880 |
+
const int grad_sampling_ptr = data_weight_ptr;
|
| 881 |
+
grad_sampling_loc += grad_sampling_ptr << 1;
|
| 882 |
+
grad_attn_weight += grad_sampling_ptr;
|
| 883 |
+
const int grad_weight_stride = 1;
|
| 884 |
+
const int grad_loc_stride = 2;
|
| 885 |
+
const int qid_stride = num_heads * channels;
|
| 886 |
+
const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
|
| 887 |
+
|
| 888 |
+
for (int l_col=0; l_col < num_levels; ++l_col)
|
| 889 |
+
{
|
| 890 |
+
const int level_start_id = data_level_start_index[l_col];
|
| 891 |
+
const int spatial_h_ptr = l_col << 1;
|
| 892 |
+
const int spatial_h = data_spatial_shapes[spatial_h_ptr];
|
| 893 |
+
const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
|
| 894 |
+
const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
|
| 895 |
+
const scalar_t *data_value_ptr = data_value + value_ptr_offset;
|
| 896 |
+
scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
|
| 897 |
+
|
| 898 |
+
for (int p_col=0; p_col < num_point; ++p_col)
|
| 899 |
+
{
|
| 900 |
+
const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
|
| 901 |
+
const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
|
| 902 |
+
const scalar_t weight = data_attn_weight[data_weight_ptr];
|
| 903 |
+
|
| 904 |
+
const scalar_t h_im = loc_h * spatial_h - 0.5;
|
| 905 |
+
const scalar_t w_im = loc_w * spatial_w - 0.5;
|
| 906 |
+
if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
|
| 907 |
+
{
|
| 908 |
+
ms_deform_attn_col2im_bilinear_gm(
|
| 909 |
+
data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
|
| 910 |
+
top_grad, weight, grad_value_ptr,
|
| 911 |
+
grad_sampling_loc, grad_attn_weight);
|
| 912 |
+
}
|
| 913 |
+
data_weight_ptr += 1;
|
| 914 |
+
data_loc_w_ptr += 2;
|
| 915 |
+
grad_attn_weight += grad_weight_stride;
|
| 916 |
+
grad_sampling_loc += grad_loc_stride;
|
| 917 |
+
}
|
| 918 |
+
}
|
| 919 |
+
}
|
| 920 |
+
}
|
| 921 |
+
|
| 922 |
+
|
| 923 |
+
template <typename scalar_t>
|
| 924 |
+
void ms_deformable_im2col_cuda(cudaStream_t stream,
|
| 925 |
+
const scalar_t* data_value,
|
| 926 |
+
const int64_t* data_spatial_shapes,
|
| 927 |
+
const int64_t* data_level_start_index,
|
| 928 |
+
const scalar_t* data_sampling_loc,
|
| 929 |
+
const scalar_t* data_attn_weight,
|
| 930 |
+
const int batch_size,
|
| 931 |
+
const int spatial_size,
|
| 932 |
+
const int num_heads,
|
| 933 |
+
const int channels,
|
| 934 |
+
const int num_levels,
|
| 935 |
+
const int num_query,
|
| 936 |
+
const int num_point,
|
| 937 |
+
scalar_t* data_col)
|
| 938 |
+
{
|
| 939 |
+
const int num_kernels = batch_size * num_query * num_heads * channels;
|
| 940 |
+
const int num_actual_kernels = batch_size * num_query * num_heads * channels;
|
| 941 |
+
const int num_threads = CUDA_NUM_THREADS;
|
| 942 |
+
ms_deformable_im2col_gpu_kernel<scalar_t>
|
| 943 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 944 |
+
0, stream>>>(
|
| 945 |
+
num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
|
| 946 |
+
batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
|
| 947 |
+
|
| 948 |
+
cudaError_t err = cudaGetLastError();
|
| 949 |
+
if (err != cudaSuccess)
|
| 950 |
+
{
|
| 951 |
+
printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
|
| 952 |
+
}
|
| 953 |
+
|
| 954 |
+
}
|
| 955 |
+
|
| 956 |
+
template <typename scalar_t>
|
| 957 |
+
void ms_deformable_col2im_cuda(cudaStream_t stream,
|
| 958 |
+
const scalar_t* grad_col,
|
| 959 |
+
const scalar_t* data_value,
|
| 960 |
+
const int64_t * data_spatial_shapes,
|
| 961 |
+
const int64_t * data_level_start_index,
|
| 962 |
+
const scalar_t * data_sampling_loc,
|
| 963 |
+
const scalar_t * data_attn_weight,
|
| 964 |
+
const int batch_size,
|
| 965 |
+
const int spatial_size,
|
| 966 |
+
const int num_heads,
|
| 967 |
+
const int channels,
|
| 968 |
+
const int num_levels,
|
| 969 |
+
const int num_query,
|
| 970 |
+
const int num_point,
|
| 971 |
+
scalar_t* grad_value,
|
| 972 |
+
scalar_t* grad_sampling_loc,
|
| 973 |
+
scalar_t* grad_attn_weight)
|
| 974 |
+
{
|
| 975 |
+
const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
|
| 976 |
+
const int num_kernels = batch_size * num_query * num_heads * channels;
|
| 977 |
+
const int num_actual_kernels = batch_size * num_query * num_heads * channels;
|
| 978 |
+
if (channels > 1024)
|
| 979 |
+
{
|
| 980 |
+
if ((channels & 1023) == 0)
|
| 981 |
+
{
|
| 982 |
+
ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks<scalar_t>
|
| 983 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 984 |
+
num_threads*3*sizeof(scalar_t), stream>>>(
|
| 985 |
+
num_kernels,
|
| 986 |
+
grad_col,
|
| 987 |
+
data_value,
|
| 988 |
+
data_spatial_shapes,
|
| 989 |
+
data_level_start_index,
|
| 990 |
+
data_sampling_loc,
|
| 991 |
+
data_attn_weight,
|
| 992 |
+
batch_size,
|
| 993 |
+
spatial_size,
|
| 994 |
+
num_heads,
|
| 995 |
+
channels,
|
| 996 |
+
num_levels,
|
| 997 |
+
num_query,
|
| 998 |
+
num_point,
|
| 999 |
+
grad_value,
|
| 1000 |
+
grad_sampling_loc,
|
| 1001 |
+
grad_attn_weight);
|
| 1002 |
+
}
|
| 1003 |
+
else
|
| 1004 |
+
{
|
| 1005 |
+
ms_deformable_col2im_gpu_kernel_gm<scalar_t>
|
| 1006 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1007 |
+
0, stream>>>(
|
| 1008 |
+
num_kernels,
|
| 1009 |
+
grad_col,
|
| 1010 |
+
data_value,
|
| 1011 |
+
data_spatial_shapes,
|
| 1012 |
+
data_level_start_index,
|
| 1013 |
+
data_sampling_loc,
|
| 1014 |
+
data_attn_weight,
|
| 1015 |
+
batch_size,
|
| 1016 |
+
spatial_size,
|
| 1017 |
+
num_heads,
|
| 1018 |
+
channels,
|
| 1019 |
+
num_levels,
|
| 1020 |
+
num_query,
|
| 1021 |
+
num_point,
|
| 1022 |
+
grad_value,
|
| 1023 |
+
grad_sampling_loc,
|
| 1024 |
+
grad_attn_weight);
|
| 1025 |
+
}
|
| 1026 |
+
}
|
| 1027 |
+
else{
|
| 1028 |
+
switch(channels)
|
| 1029 |
+
{
|
| 1030 |
+
case 1:
|
| 1031 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 1>
|
| 1032 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1033 |
+
0, stream>>>(
|
| 1034 |
+
num_kernels,
|
| 1035 |
+
grad_col,
|
| 1036 |
+
data_value,
|
| 1037 |
+
data_spatial_shapes,
|
| 1038 |
+
data_level_start_index,
|
| 1039 |
+
data_sampling_loc,
|
| 1040 |
+
data_attn_weight,
|
| 1041 |
+
batch_size,
|
| 1042 |
+
spatial_size,
|
| 1043 |
+
num_heads,
|
| 1044 |
+
channels,
|
| 1045 |
+
num_levels,
|
| 1046 |
+
num_query,
|
| 1047 |
+
num_point,
|
| 1048 |
+
grad_value,
|
| 1049 |
+
grad_sampling_loc,
|
| 1050 |
+
grad_attn_weight);
|
| 1051 |
+
break;
|
| 1052 |
+
case 2:
|
| 1053 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 2>
|
| 1054 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1055 |
+
0, stream>>>(
|
| 1056 |
+
num_kernels,
|
| 1057 |
+
grad_col,
|
| 1058 |
+
data_value,
|
| 1059 |
+
data_spatial_shapes,
|
| 1060 |
+
data_level_start_index,
|
| 1061 |
+
data_sampling_loc,
|
| 1062 |
+
data_attn_weight,
|
| 1063 |
+
batch_size,
|
| 1064 |
+
spatial_size,
|
| 1065 |
+
num_heads,
|
| 1066 |
+
channels,
|
| 1067 |
+
num_levels,
|
| 1068 |
+
num_query,
|
| 1069 |
+
num_point,
|
| 1070 |
+
grad_value,
|
| 1071 |
+
grad_sampling_loc,
|
| 1072 |
+
grad_attn_weight);
|
| 1073 |
+
break;
|
| 1074 |
+
case 4:
|
| 1075 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 4>
|
| 1076 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1077 |
+
0, stream>>>(
|
| 1078 |
+
num_kernels,
|
| 1079 |
+
grad_col,
|
| 1080 |
+
data_value,
|
| 1081 |
+
data_spatial_shapes,
|
| 1082 |
+
data_level_start_index,
|
| 1083 |
+
data_sampling_loc,
|
| 1084 |
+
data_attn_weight,
|
| 1085 |
+
batch_size,
|
| 1086 |
+
spatial_size,
|
| 1087 |
+
num_heads,
|
| 1088 |
+
channels,
|
| 1089 |
+
num_levels,
|
| 1090 |
+
num_query,
|
| 1091 |
+
num_point,
|
| 1092 |
+
grad_value,
|
| 1093 |
+
grad_sampling_loc,
|
| 1094 |
+
grad_attn_weight);
|
| 1095 |
+
break;
|
| 1096 |
+
case 8:
|
| 1097 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 8>
|
| 1098 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1099 |
+
0, stream>>>(
|
| 1100 |
+
num_kernels,
|
| 1101 |
+
grad_col,
|
| 1102 |
+
data_value,
|
| 1103 |
+
data_spatial_shapes,
|
| 1104 |
+
data_level_start_index,
|
| 1105 |
+
data_sampling_loc,
|
| 1106 |
+
data_attn_weight,
|
| 1107 |
+
batch_size,
|
| 1108 |
+
spatial_size,
|
| 1109 |
+
num_heads,
|
| 1110 |
+
channels,
|
| 1111 |
+
num_levels,
|
| 1112 |
+
num_query,
|
| 1113 |
+
num_point,
|
| 1114 |
+
grad_value,
|
| 1115 |
+
grad_sampling_loc,
|
| 1116 |
+
grad_attn_weight);
|
| 1117 |
+
break;
|
| 1118 |
+
case 16:
|
| 1119 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 16>
|
| 1120 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1121 |
+
0, stream>>>(
|
| 1122 |
+
num_kernels,
|
| 1123 |
+
grad_col,
|
| 1124 |
+
data_value,
|
| 1125 |
+
data_spatial_shapes,
|
| 1126 |
+
data_level_start_index,
|
| 1127 |
+
data_sampling_loc,
|
| 1128 |
+
data_attn_weight,
|
| 1129 |
+
batch_size,
|
| 1130 |
+
spatial_size,
|
| 1131 |
+
num_heads,
|
| 1132 |
+
channels,
|
| 1133 |
+
num_levels,
|
| 1134 |
+
num_query,
|
| 1135 |
+
num_point,
|
| 1136 |
+
grad_value,
|
| 1137 |
+
grad_sampling_loc,
|
| 1138 |
+
grad_attn_weight);
|
| 1139 |
+
break;
|
| 1140 |
+
case 32:
|
| 1141 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 32>
|
| 1142 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1143 |
+
0, stream>>>(
|
| 1144 |
+
num_kernels,
|
| 1145 |
+
grad_col,
|
| 1146 |
+
data_value,
|
| 1147 |
+
data_spatial_shapes,
|
| 1148 |
+
data_level_start_index,
|
| 1149 |
+
data_sampling_loc,
|
| 1150 |
+
data_attn_weight,
|
| 1151 |
+
batch_size,
|
| 1152 |
+
spatial_size,
|
| 1153 |
+
num_heads,
|
| 1154 |
+
channels,
|
| 1155 |
+
num_levels,
|
| 1156 |
+
num_query,
|
| 1157 |
+
num_point,
|
| 1158 |
+
grad_value,
|
| 1159 |
+
grad_sampling_loc,
|
| 1160 |
+
grad_attn_weight);
|
| 1161 |
+
break;
|
| 1162 |
+
case 64:
|
| 1163 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 64>
|
| 1164 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1165 |
+
0, stream>>>(
|
| 1166 |
+
num_kernels,
|
| 1167 |
+
grad_col,
|
| 1168 |
+
data_value,
|
| 1169 |
+
data_spatial_shapes,
|
| 1170 |
+
data_level_start_index,
|
| 1171 |
+
data_sampling_loc,
|
| 1172 |
+
data_attn_weight,
|
| 1173 |
+
batch_size,
|
| 1174 |
+
spatial_size,
|
| 1175 |
+
num_heads,
|
| 1176 |
+
channels,
|
| 1177 |
+
num_levels,
|
| 1178 |
+
num_query,
|
| 1179 |
+
num_point,
|
| 1180 |
+
grad_value,
|
| 1181 |
+
grad_sampling_loc,
|
| 1182 |
+
grad_attn_weight);
|
| 1183 |
+
break;
|
| 1184 |
+
case 128:
|
| 1185 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 128>
|
| 1186 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1187 |
+
0, stream>>>(
|
| 1188 |
+
num_kernels,
|
| 1189 |
+
grad_col,
|
| 1190 |
+
data_value,
|
| 1191 |
+
data_spatial_shapes,
|
| 1192 |
+
data_level_start_index,
|
| 1193 |
+
data_sampling_loc,
|
| 1194 |
+
data_attn_weight,
|
| 1195 |
+
batch_size,
|
| 1196 |
+
spatial_size,
|
| 1197 |
+
num_heads,
|
| 1198 |
+
channels,
|
| 1199 |
+
num_levels,
|
| 1200 |
+
num_query,
|
| 1201 |
+
num_point,
|
| 1202 |
+
grad_value,
|
| 1203 |
+
grad_sampling_loc,
|
| 1204 |
+
grad_attn_weight);
|
| 1205 |
+
break;
|
| 1206 |
+
case 256:
|
| 1207 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 256>
|
| 1208 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1209 |
+
0, stream>>>(
|
| 1210 |
+
num_kernels,
|
| 1211 |
+
grad_col,
|
| 1212 |
+
data_value,
|
| 1213 |
+
data_spatial_shapes,
|
| 1214 |
+
data_level_start_index,
|
| 1215 |
+
data_sampling_loc,
|
| 1216 |
+
data_attn_weight,
|
| 1217 |
+
batch_size,
|
| 1218 |
+
spatial_size,
|
| 1219 |
+
num_heads,
|
| 1220 |
+
channels,
|
| 1221 |
+
num_levels,
|
| 1222 |
+
num_query,
|
| 1223 |
+
num_point,
|
| 1224 |
+
grad_value,
|
| 1225 |
+
grad_sampling_loc,
|
| 1226 |
+
grad_attn_weight);
|
| 1227 |
+
break;
|
| 1228 |
+
case 512:
|
| 1229 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 512>
|
| 1230 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1231 |
+
0, stream>>>(
|
| 1232 |
+
num_kernels,
|
| 1233 |
+
grad_col,
|
| 1234 |
+
data_value,
|
| 1235 |
+
data_spatial_shapes,
|
| 1236 |
+
data_level_start_index,
|
| 1237 |
+
data_sampling_loc,
|
| 1238 |
+
data_attn_weight,
|
| 1239 |
+
batch_size,
|
| 1240 |
+
spatial_size,
|
| 1241 |
+
num_heads,
|
| 1242 |
+
channels,
|
| 1243 |
+
num_levels,
|
| 1244 |
+
num_query,
|
| 1245 |
+
num_point,
|
| 1246 |
+
grad_value,
|
| 1247 |
+
grad_sampling_loc,
|
| 1248 |
+
grad_attn_weight);
|
| 1249 |
+
break;
|
| 1250 |
+
case 1024:
|
| 1251 |
+
ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 1024>
|
| 1252 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1253 |
+
0, stream>>>(
|
| 1254 |
+
num_kernels,
|
| 1255 |
+
grad_col,
|
| 1256 |
+
data_value,
|
| 1257 |
+
data_spatial_shapes,
|
| 1258 |
+
data_level_start_index,
|
| 1259 |
+
data_sampling_loc,
|
| 1260 |
+
data_attn_weight,
|
| 1261 |
+
batch_size,
|
| 1262 |
+
spatial_size,
|
| 1263 |
+
num_heads,
|
| 1264 |
+
channels,
|
| 1265 |
+
num_levels,
|
| 1266 |
+
num_query,
|
| 1267 |
+
num_point,
|
| 1268 |
+
grad_value,
|
| 1269 |
+
grad_sampling_loc,
|
| 1270 |
+
grad_attn_weight);
|
| 1271 |
+
break;
|
| 1272 |
+
default:
|
| 1273 |
+
if (channels < 64)
|
| 1274 |
+
{
|
| 1275 |
+
ms_deformable_col2im_gpu_kernel_shm_reduce_v1<scalar_t>
|
| 1276 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1277 |
+
num_threads*3*sizeof(scalar_t), stream>>>(
|
| 1278 |
+
num_kernels,
|
| 1279 |
+
grad_col,
|
| 1280 |
+
data_value,
|
| 1281 |
+
data_spatial_shapes,
|
| 1282 |
+
data_level_start_index,
|
| 1283 |
+
data_sampling_loc,
|
| 1284 |
+
data_attn_weight,
|
| 1285 |
+
batch_size,
|
| 1286 |
+
spatial_size,
|
| 1287 |
+
num_heads,
|
| 1288 |
+
channels,
|
| 1289 |
+
num_levels,
|
| 1290 |
+
num_query,
|
| 1291 |
+
num_point,
|
| 1292 |
+
grad_value,
|
| 1293 |
+
grad_sampling_loc,
|
| 1294 |
+
grad_attn_weight);
|
| 1295 |
+
}
|
| 1296 |
+
else
|
| 1297 |
+
{
|
| 1298 |
+
ms_deformable_col2im_gpu_kernel_shm_reduce_v2<scalar_t>
|
| 1299 |
+
<<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
|
| 1300 |
+
num_threads*3*sizeof(scalar_t), stream>>>(
|
| 1301 |
+
num_kernels,
|
| 1302 |
+
grad_col,
|
| 1303 |
+
data_value,
|
| 1304 |
+
data_spatial_shapes,
|
| 1305 |
+
data_level_start_index,
|
| 1306 |
+
data_sampling_loc,
|
| 1307 |
+
data_attn_weight,
|
| 1308 |
+
batch_size,
|
| 1309 |
+
spatial_size,
|
| 1310 |
+
num_heads,
|
| 1311 |
+
channels,
|
| 1312 |
+
num_levels,
|
| 1313 |
+
num_query,
|
| 1314 |
+
num_point,
|
| 1315 |
+
grad_value,
|
| 1316 |
+
grad_sampling_loc,
|
| 1317 |
+
grad_attn_weight);
|
| 1318 |
+
}
|
| 1319 |
+
}
|
| 1320 |
+
}
|
| 1321 |
+
cudaError_t err = cudaGetLastError();
|
| 1322 |
+
if (err != cudaSuccess)
|
| 1323 |
+
{
|
| 1324 |
+
printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
|
| 1325 |
+
}
|
| 1326 |
+
|
| 1327 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/ms_deform_attn.h
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************************************
|
| 7 |
+
* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
|
| 8 |
+
**************************************************************************************************
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#pragma once
|
| 12 |
+
|
| 13 |
+
#include "cpu/ms_deform_attn_cpu.h"
|
| 14 |
+
|
| 15 |
+
#ifdef WITH_CUDA
|
| 16 |
+
#include "cuda/ms_deform_attn_cuda.h"
|
| 17 |
+
#endif
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
at::Tensor
|
| 21 |
+
ms_deform_attn_forward(
|
| 22 |
+
const at::Tensor &value,
|
| 23 |
+
const at::Tensor &spatial_shapes,
|
| 24 |
+
const at::Tensor &level_start_index,
|
| 25 |
+
const at::Tensor &sampling_loc,
|
| 26 |
+
const at::Tensor &attn_weight,
|
| 27 |
+
const int im2col_step)
|
| 28 |
+
{
|
| 29 |
+
if (value.type().is_cuda())
|
| 30 |
+
{
|
| 31 |
+
#ifdef WITH_CUDA
|
| 32 |
+
return ms_deform_attn_cuda_forward(
|
| 33 |
+
value, spatial_shapes, level_start_index, sampling_loc, attn_weight, im2col_step);
|
| 34 |
+
#else
|
| 35 |
+
AT_ERROR("Not compiled with GPU support");
|
| 36 |
+
#endif
|
| 37 |
+
}
|
| 38 |
+
AT_ERROR("Not implemented on the CPU");
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
std::vector<at::Tensor>
|
| 42 |
+
ms_deform_attn_backward(
|
| 43 |
+
const at::Tensor &value,
|
| 44 |
+
const at::Tensor &spatial_shapes,
|
| 45 |
+
const at::Tensor &level_start_index,
|
| 46 |
+
const at::Tensor &sampling_loc,
|
| 47 |
+
const at::Tensor &attn_weight,
|
| 48 |
+
const at::Tensor &grad_output,
|
| 49 |
+
const int im2col_step)
|
| 50 |
+
{
|
| 51 |
+
if (value.type().is_cuda())
|
| 52 |
+
{
|
| 53 |
+
#ifdef WITH_CUDA
|
| 54 |
+
return ms_deform_attn_cuda_backward(
|
| 55 |
+
value, spatial_shapes, level_start_index, sampling_loc, attn_weight, grad_output, im2col_step);
|
| 56 |
+
#else
|
| 57 |
+
AT_ERROR("Not compiled with GPU support");
|
| 58 |
+
#endif
|
| 59 |
+
}
|
| 60 |
+
AT_ERROR("Not implemented on the CPU");
|
| 61 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/deformable_detr/vision.cpp
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*!
|
| 2 |
+
**************************************************************************************************
|
| 3 |
+
* Deformable DETR
|
| 4 |
+
* Copyright (c) 2020 SenseTime. All Rights Reserved.
|
| 5 |
+
* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
|
| 6 |
+
**************************************************************************************************
|
| 7 |
+
* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
|
| 8 |
+
**************************************************************************************************
|
| 9 |
+
*/
|
| 10 |
+
|
| 11 |
+
#include "ms_deform_attn.h"
|
| 12 |
+
|
| 13 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 14 |
+
m.def("ms_deform_attn_forward", &ms_deform_attn_forward, "ms_deform_attn_forward");
|
| 15 |
+
m.def("ms_deform_attn_backward", &ms_deform_attn_backward, "ms_deform_attn_backward");
|
| 16 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/rwkv/wkv_cuda.cu
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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kernel_forward(
|
| 8 |
+
const int B, const int T, const int C, const F *__restrict__ const _w, const F *__restrict__ const _u,
|
| 9 |
+
const F *__restrict__ const _k, const F *__restrict__ const _v, F *__restrict__ const _y
|
| 10 |
+
) {
|
| 11 |
+
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
| 12 |
+
const int _b = idx / C;
|
| 13 |
+
const int _c = idx % C;
|
| 14 |
+
const int _offset = _b * T * C + _c;
|
| 15 |
+
|
| 16 |
+
F u = _u[_c];
|
| 17 |
+
F w = _w[_c];
|
| 18 |
+
const F *__restrict__ const k = _k + _offset;
|
| 19 |
+
const F *__restrict__ const v = _v + _offset;
|
| 20 |
+
F *__restrict__ const y = _y + _offset;
|
| 21 |
+
|
| 22 |
+
// aa and bb are running sums divided by exp(pp) (to avoid overflow)
|
| 23 |
+
F aa = 0, bb = 0, pp = MIN_VALUE;
|
| 24 |
+
for (int i = 0; i < T; i++) {
|
| 25 |
+
const int ii = i * C;
|
| 26 |
+
const F kk = k[ii];
|
| 27 |
+
const F vv = v[ii];
|
| 28 |
+
|
| 29 |
+
F ww = u + kk;
|
| 30 |
+
F p = max(pp, ww);
|
| 31 |
+
F e1 = exp(pp - p);
|
| 32 |
+
F e2 = exp(ww - p);
|
| 33 |
+
y[ii] = (e1 * aa + e2 * vv) / (e1 * bb + e2);
|
| 34 |
+
|
| 35 |
+
ww = w + pp;
|
| 36 |
+
p = max(ww, kk);
|
| 37 |
+
e1 = exp(ww - p);
|
| 38 |
+
e2 = exp(kk - p);
|
| 39 |
+
aa = e1 * aa + e2 * vv;
|
| 40 |
+
bb = e1 * bb + e2;
|
| 41 |
+
pp = p;
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
template <typename F>
|
| 46 |
+
__global__ void kernel_forward_with_state(
|
| 47 |
+
const int B, const int T, const int C, const F *__restrict__ const _w, const F *__restrict__ const _u,
|
| 48 |
+
const F *__restrict__ const _k, const F *__restrict__ const _v, F *__restrict__ const _y, F *__restrict__ const _s
|
| 49 |
+
) {
|
| 50 |
+
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
| 51 |
+
const int _b = idx / C;
|
| 52 |
+
const int _c = idx % C;
|
| 53 |
+
const int _offset_s = _b * C * 3 + _c * 3;
|
| 54 |
+
const int _offset = _b * T * C + _c;
|
| 55 |
+
|
| 56 |
+
F u = _u[_c];
|
| 57 |
+
F w = _w[_c];
|
| 58 |
+
const F *__restrict__ const k = _k + _offset;
|
| 59 |
+
const F *__restrict__ const v = _v + _offset;
|
| 60 |
+
F *__restrict__ const y = _y + _offset;
|
| 61 |
+
F *__restrict__ const s = _s + _offset_s;
|
| 62 |
+
|
| 63 |
+
// aa and bb are running sums divided by exp(pp) (to avoid overflow)
|
| 64 |
+
F aa = s[0], bb = s[1], pp = s[2];
|
| 65 |
+
for (int i = 0; i < T; i++) {
|
| 66 |
+
const int ii = i * C;
|
| 67 |
+
const F kk = k[ii];
|
| 68 |
+
const F vv = v[ii];
|
| 69 |
+
|
| 70 |
+
F ww = u + kk;
|
| 71 |
+
F p = max(pp, ww);
|
| 72 |
+
F e1 = exp(pp - p);
|
| 73 |
+
F e2 = exp(ww - p);
|
| 74 |
+
y[ii] = (e1 * aa + e2 * vv) / (e1 * bb + e2);
|
| 75 |
+
|
| 76 |
+
ww = w + pp;
|
| 77 |
+
p = max(ww, kk);
|
| 78 |
+
e1 = exp(ww - p);
|
| 79 |
+
e2 = exp(kk - p);
|
| 80 |
+
aa = e1 * aa + e2 * vv;
|
| 81 |
+
bb = e1 * bb + e2;
|
| 82 |
+
pp = p;
|
| 83 |
+
}
|
| 84 |
+
s[0] = aa;
|
| 85 |
+
s[1] = bb;
|
| 86 |
+
s[2] = pp;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
template <typename F>
|
| 90 |
+
__global__ void kernel_backward(
|
| 91 |
+
const int B, const int T, const int C, const F *__restrict__ const _w, const F *__restrict__ const _u,
|
| 92 |
+
const F *__restrict__ const _k, const F *__restrict__ const _v, const F *__restrict__ const _y,
|
| 93 |
+
const F *__restrict__ const _gy, F *__restrict__ const _gw, F *__restrict__ const _gu, F *__restrict__ const _gk,
|
| 94 |
+
F *__restrict__ const _gv
|
| 95 |
+
) {
|
| 96 |
+
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
| 97 |
+
const int _b = idx / C;
|
| 98 |
+
const int _c = idx % C;
|
| 99 |
+
const int _offset = _b * T * C + _c;
|
| 100 |
+
|
| 101 |
+
F u = _u[_c];
|
| 102 |
+
F w = _w[_c];
|
| 103 |
+
const F *__restrict__ const k = _k + _offset;
|
| 104 |
+
const F *__restrict__ const v = _v + _offset;
|
| 105 |
+
const F *__restrict__ const y = _y + _offset;
|
| 106 |
+
const F *__restrict__ const gy = _gy + _offset;
|
| 107 |
+
F *__restrict__ const gk = _gk + _offset;
|
| 108 |
+
F *__restrict__ const gv = _gv + _offset;
|
| 109 |
+
|
| 110 |
+
F q[Tmax], r[Tmax];
|
| 111 |
+
|
| 112 |
+
F gw = 0, gu = 0, aa = 0, bb = 0, ga = 0, gb = 0, pp = MIN_VALUE;
|
| 113 |
+
for (int i = 0; i < T; i++) {
|
| 114 |
+
const int ii = i * C;
|
| 115 |
+
const F kk = k[ii];
|
| 116 |
+
const F vv = v[ii];
|
| 117 |
+
const F yy = y[ii];
|
| 118 |
+
|
| 119 |
+
F ww = u + kk;
|
| 120 |
+
F p = max(pp, ww);
|
| 121 |
+
F e1 = exp(pp - p);
|
| 122 |
+
F e2 = exp(ww - p);
|
| 123 |
+
const F qq = gy[ii] / (e1 * bb + e2);
|
| 124 |
+
gw += (ga - gb * yy) * e1 * qq;
|
| 125 |
+
gu += (vv - yy) * e2 * qq;
|
| 126 |
+
q[i] = qq;
|
| 127 |
+
r[i] = ww - p;
|
| 128 |
+
|
| 129 |
+
ww = w + pp;
|
| 130 |
+
p = max(ww, kk);
|
| 131 |
+
e1 = exp(ww - p);
|
| 132 |
+
e2 = exp(kk - p);
|
| 133 |
+
ga = e1 * (aa + ga);
|
| 134 |
+
gb = e1 * (bb + gb);
|
| 135 |
+
aa = e1 * aa + e2 * vv;
|
| 136 |
+
bb = e1 * bb + e2;
|
| 137 |
+
pp = p;
|
| 138 |
+
}
|
| 139 |
+
const int _offsetBC = _b * C + _c;
|
| 140 |
+
_gw[_offsetBC] = gw * _w[_c]; // multiply by w because of w -> -exp(w) in python forward()
|
| 141 |
+
_gu[_offsetBC] = gu;
|
| 142 |
+
|
| 143 |
+
aa = 0, bb = 0, pp = MIN_VALUE;
|
| 144 |
+
for (int i = T - 1; i >= 0; i--) {
|
| 145 |
+
const int ii = i * C;
|
| 146 |
+
const F kk = k[ii];
|
| 147 |
+
const F vv = v[ii];
|
| 148 |
+
const F yy = y[ii];
|
| 149 |
+
const F qq = q[i];
|
| 150 |
+
const F rr = r[i];
|
| 151 |
+
|
| 152 |
+
F e1 = qq * exp(rr);
|
| 153 |
+
F e2 = exp(kk + pp);
|
| 154 |
+
gk[ii] = e1 * (vv - yy) + e2 * (aa * vv + bb);
|
| 155 |
+
gv[ii] = e1 + e2 * aa;
|
| 156 |
+
|
| 157 |
+
const F ww = w + pp;
|
| 158 |
+
const F www = rr - u - kk;
|
| 159 |
+
const F p = max(ww, www);
|
| 160 |
+
e1 = exp(ww - p);
|
| 161 |
+
e2 = qq * exp(www - p);
|
| 162 |
+
aa = e1 * aa + e2;
|
| 163 |
+
bb = e1 * bb - e2 * yy;
|
| 164 |
+
pp = p;
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
void cuda_forward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y) {
|
| 169 |
+
dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
|
| 170 |
+
assert(B * C % threadsPerBlock.x == 0);
|
| 171 |
+
dim3 numBlocks(B * C / threadsPerBlock.x);
|
| 172 |
+
kernel_forward<<<numBlocks, threadsPerBlock>>>(B, T, C, w, u, k, v, y);
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
void cuda_forward_with_state(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *s) {
|
| 176 |
+
dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
|
| 177 |
+
assert(B * C % threadsPerBlock.x == 0);
|
| 178 |
+
dim3 numBlocks(B * C / threadsPerBlock.x);
|
| 179 |
+
kernel_forward_with_state<<<numBlocks, threadsPerBlock>>>(B, T, C, w, u, k, v, y, s);
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
void cuda_backward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *gy, float *gw, float *gu, float *gk, float *gv) {
|
| 183 |
+
dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
|
| 184 |
+
assert(B * C % threadsPerBlock.x == 0);
|
| 185 |
+
dim3 numBlocks(B * C / threadsPerBlock.x);
|
| 186 |
+
kernel_backward<<<numBlocks, threadsPerBlock>>>(B, T, C, w, u, k, v, y, gy, gw, gu, gk, gv);
|
| 187 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/rwkv/wkv_cuda_bf16.cu
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <stdio.h>
|
| 2 |
+
#include <assert.h>
|
| 3 |
+
#include "ATen/ATen.h"
|
| 4 |
+
#define MIN_VALUE (-1e38)
|
| 5 |
+
typedef at::BFloat16 bf16;
|
| 6 |
+
|
| 7 |
+
__global__ void kernel_forward_bf16(
|
| 8 |
+
const int B, const int T, const int C, const float *__restrict__ const _w, const bf16 *__restrict__ const _u,
|
| 9 |
+
const bf16 *__restrict__ const _k, const bf16 *__restrict__ const _v, bf16 *__restrict__ const _y
|
| 10 |
+
) {
|
| 11 |
+
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
| 12 |
+
const int _b = idx / C;
|
| 13 |
+
const int _c = idx % C;
|
| 14 |
+
const int _offset = _b * T * C + _c;
|
| 15 |
+
|
| 16 |
+
float u = float(_u[_c]);
|
| 17 |
+
float w = _w[_c];
|
| 18 |
+
const bf16 *__restrict__ const k = _k + _offset;
|
| 19 |
+
const bf16 *__restrict__ const v = _v + _offset;
|
| 20 |
+
bf16 *__restrict__ const y = _y + _offset;
|
| 21 |
+
|
| 22 |
+
// aa and bb are running sums divided by exp(pp) (to avoid overflow)
|
| 23 |
+
float aa = 0, bb = 0, pp = MIN_VALUE;
|
| 24 |
+
for (int i = 0; i < T; i++) {
|
| 25 |
+
const int ii = i * C;
|
| 26 |
+
const float kk = float(k[ii]);
|
| 27 |
+
const float vv = float(v[ii]);
|
| 28 |
+
|
| 29 |
+
float ww = u + kk;
|
| 30 |
+
float p = max(pp, ww);
|
| 31 |
+
float e1 = exp(pp - p);
|
| 32 |
+
float e2 = exp(ww - p);
|
| 33 |
+
y[ii] = bf16((e1 * aa + e2 * vv) / (e1 * bb + e2));
|
| 34 |
+
|
| 35 |
+
ww = w + pp;
|
| 36 |
+
p = max(ww, kk);
|
| 37 |
+
e1 = exp(ww - p);
|
| 38 |
+
e2 = exp(kk - p);
|
| 39 |
+
aa = e1 * aa + e2 * vv;
|
| 40 |
+
bb = e1 * bb + e2;
|
| 41 |
+
pp = p;
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
__global__ void kernel_forward_with_state_bf16(
|
| 46 |
+
const int B, const int T, const int C, const float *__restrict__ const _w, const bf16 *__restrict__ const _u,
|
| 47 |
+
const bf16 *__restrict__ const _k, const bf16 *__restrict__ const _v, bf16 *__restrict__ const _y,
|
| 48 |
+
float *__restrict__ const _s
|
| 49 |
+
) {
|
| 50 |
+
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
| 51 |
+
const int _b = idx / C;
|
| 52 |
+
const int _c = idx % C;
|
| 53 |
+
const int _offset_s = _b * C * 3 + _c * 3;
|
| 54 |
+
const int _offset = _b * T * C + _c;
|
| 55 |
+
|
| 56 |
+
float u = float(_u[_c]);
|
| 57 |
+
float w = _w[_c];
|
| 58 |
+
const bf16 *__restrict__ const k = _k + _offset;
|
| 59 |
+
const bf16 *__restrict__ const v = _v + _offset;
|
| 60 |
+
bf16 *__restrict__ const y = _y + _offset;
|
| 61 |
+
float *__restrict__ const s = _s + _offset_s;
|
| 62 |
+
|
| 63 |
+
// aa and bb are running sums divided by exp(pp) (to avoid overflow)
|
| 64 |
+
float aa = s[0], bb = s[1], pp = s[2];
|
| 65 |
+
for (int i = 0; i < T; i++) {
|
| 66 |
+
const int ii = i * C;
|
| 67 |
+
const float kk = float(k[ii]);
|
| 68 |
+
const float vv = float(v[ii]);
|
| 69 |
+
|
| 70 |
+
float ww = u + kk;
|
| 71 |
+
float p = max(pp, ww);
|
| 72 |
+
float e1 = exp(pp - p);
|
| 73 |
+
float e2 = exp(ww - p);
|
| 74 |
+
y[ii] = bf16(e1 * aa + e2 * vv) / (e1 * bb + e2);
|
| 75 |
+
|
| 76 |
+
ww = w + pp;
|
| 77 |
+
p = max(ww, kk);
|
| 78 |
+
e1 = exp(ww - p);
|
| 79 |
+
e2 = exp(kk - p);
|
| 80 |
+
aa = e1 * aa + e2 * vv;
|
| 81 |
+
bb = e1 * bb + e2;
|
| 82 |
+
pp = p;
|
| 83 |
+
}
|
| 84 |
+
s[0] = aa;
|
| 85 |
+
s[1] = bb;
|
| 86 |
+
s[2] = pp;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
__global__ void kernel_backward_bf16(
|
| 90 |
+
const int B, const int T, const int C, const float *__restrict__ const _w, const bf16 *__restrict__ const _u,
|
| 91 |
+
const bf16 *__restrict__ const _k, const bf16 *__restrict__ const _v, const bf16 *__restrict__ const _y,
|
| 92 |
+
const bf16 *__restrict__ const _gy, bf16 *__restrict__ const _gw, bf16 *__restrict__ const _gu,
|
| 93 |
+
bf16 *__restrict__ const _gk, bf16 *__restrict__ const _gv
|
| 94 |
+
) {
|
| 95 |
+
const int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
| 96 |
+
const int _b = idx / C;
|
| 97 |
+
const int _c = idx % C;
|
| 98 |
+
const int _offset = _b * T * C + _c;
|
| 99 |
+
|
| 100 |
+
float u = float(_u[_c]);
|
| 101 |
+
float w = _w[_c];
|
| 102 |
+
const bf16 *__restrict__ const k = _k + _offset;
|
| 103 |
+
const bf16 *__restrict__ const v = _v + _offset;
|
| 104 |
+
const bf16 *__restrict__ const y = _y + _offset;
|
| 105 |
+
const bf16 *__restrict__ const gy = _gy + _offset;
|
| 106 |
+
bf16 *__restrict__ const gk = _gk + _offset;
|
| 107 |
+
bf16 *__restrict__ const gv = _gv + _offset;
|
| 108 |
+
|
| 109 |
+
float q[Tmax], r[Tmax];
|
| 110 |
+
|
| 111 |
+
float gw = 0, gu = 0, aa = 0, bb = 0, ga = 0, gb = 0, pp = MIN_VALUE;
|
| 112 |
+
for (int i = 0; i < T; i++) {
|
| 113 |
+
const int ii = i * C;
|
| 114 |
+
const float kk = float(k[ii]);
|
| 115 |
+
const float vv = float(v[ii]);
|
| 116 |
+
const float yy = float(y[ii]);
|
| 117 |
+
|
| 118 |
+
float ww = u + kk;
|
| 119 |
+
float p = max(pp, ww);
|
| 120 |
+
float e1 = exp(pp - p);
|
| 121 |
+
float e2 = exp(ww - p);
|
| 122 |
+
const float qq = float(gy[ii]) / (e1 * bb + e2);
|
| 123 |
+
gw += (ga - gb * yy) * e1 * qq;
|
| 124 |
+
gu += (vv - yy) * e2 * qq;
|
| 125 |
+
q[i] = qq;
|
| 126 |
+
r[i] = ww - p;
|
| 127 |
+
|
| 128 |
+
ww = w + pp;
|
| 129 |
+
p = max(ww, kk);
|
| 130 |
+
e1 = exp(ww - p);
|
| 131 |
+
e2 = exp(kk - p);
|
| 132 |
+
ga = e1 * (aa + ga);
|
| 133 |
+
gb = e1 * (bb + gb);
|
| 134 |
+
aa = e1 * aa + e2 * vv;
|
| 135 |
+
bb = e1 * bb + e2;
|
| 136 |
+
pp = p;
|
| 137 |
+
}
|
| 138 |
+
const int _offsetBC = _b * C + _c;
|
| 139 |
+
_gw[_offsetBC] = bf16(gw * _w[_c]); // multiply by w because of w -> -exp(w) in python forward()
|
| 140 |
+
_gu[_offsetBC] = bf16(gu);
|
| 141 |
+
|
| 142 |
+
aa = 0, bb = 0, pp = MIN_VALUE;
|
| 143 |
+
for (int i = T - 1; i >= 0; i--) {
|
| 144 |
+
const int ii = i * C;
|
| 145 |
+
const float kk = float(k[ii]);
|
| 146 |
+
const float vv = float(v[ii]);
|
| 147 |
+
const float yy = float(y[ii]);
|
| 148 |
+
const float qq = q[i];
|
| 149 |
+
const float rr = r[i];
|
| 150 |
+
|
| 151 |
+
float e1 = qq * exp(rr);
|
| 152 |
+
float e2 = exp(kk + pp);
|
| 153 |
+
gk[ii] = bf16(e1 * (vv - yy) + e2 * (aa * vv + bb));
|
| 154 |
+
gv[ii] = bf16(e1 + e2 * aa);
|
| 155 |
+
|
| 156 |
+
const float ww = w + pp;
|
| 157 |
+
const float www = rr - u - kk;
|
| 158 |
+
const float p = max(ww, www);
|
| 159 |
+
e1 = exp(ww - p);
|
| 160 |
+
e2 = qq * exp(www - p);
|
| 161 |
+
aa = e1 * aa + e2;
|
| 162 |
+
bb = e1 * bb - e2 * yy;
|
| 163 |
+
pp = p;
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
void cuda_forward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y) {
|
| 168 |
+
dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
|
| 169 |
+
assert(B * C % threadsPerBlock.x == 0);
|
| 170 |
+
dim3 numBlocks(B * C / threadsPerBlock.x);
|
| 171 |
+
kernel_forward_bf16<<<numBlocks, threadsPerBlock>>>(B, T, C, w, u, k, v, y);
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
void cuda_forward_with_state_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, float *s) {
|
| 175 |
+
dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
|
| 176 |
+
assert(B * C % threadsPerBlock.x == 0);
|
| 177 |
+
dim3 numBlocks(B * C / threadsPerBlock.x);
|
| 178 |
+
kernel_forward_with_state_bf16<<<numBlocks, threadsPerBlock>>>(B, T, C, w, u, k, v, y, s);
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
void cuda_backward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, bf16 *gy, bf16 *gw, bf16 *gu, bf16 *gk, bf16 *gv) {
|
| 182 |
+
dim3 threadsPerBlock( min(C, 32) ); // requires --maxrregcount 60 for optimal performance
|
| 183 |
+
assert(B * C % threadsPerBlock.x == 0);
|
| 184 |
+
dim3 numBlocks(B * C / threadsPerBlock.x);
|
| 185 |
+
kernel_backward_bf16<<<numBlocks, threadsPerBlock>>>(B, T, C, w, u, k, v, y, gy, gw, gu, gk, gv);
|
| 186 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/rwkv/wkv_op.cpp
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <torch/extension.h>
|
| 2 |
+
#include "ATen/ATen.h"
|
| 3 |
+
typedef at::BFloat16 bf16;
|
| 4 |
+
|
| 5 |
+
void cuda_forward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y);
|
| 6 |
+
void cuda_forward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y);
|
| 7 |
+
void cuda_forward_with_state(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *s);
|
| 8 |
+
void cuda_forward_with_state_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, float *s);
|
| 9 |
+
void cuda_backward(int B, int T, int C, float *w, float *u, float *k, float *v, float *y, float *gy, float *gw, float *gu, float *gk, float *gv);
|
| 10 |
+
void cuda_backward_bf16(int B, int T, int C, float *w, bf16 *u, bf16 *k, bf16 *v, bf16 *y, bf16 *gy, bf16 *gw, bf16 *gu, bf16 *gk, bf16 *gv);
|
| 11 |
+
|
| 12 |
+
void forward(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y) {
|
| 13 |
+
const int B = k.size(0);
|
| 14 |
+
const int T = k.size(1);
|
| 15 |
+
const int C = k.size(2);
|
| 16 |
+
cuda_forward(B, T, C, w.data_ptr<float>(), u.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), y.data_ptr<float>());
|
| 17 |
+
}
|
| 18 |
+
void forward_bf16(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y) {
|
| 19 |
+
const int B = k.size(0);
|
| 20 |
+
const int T = k.size(1);
|
| 21 |
+
const int C = k.size(2);
|
| 22 |
+
cuda_forward_bf16(B, T, C, w.data_ptr<float>(), u.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), y.data_ptr<bf16>());
|
| 23 |
+
}
|
| 24 |
+
void forward_with_state(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &s) {
|
| 25 |
+
const int B = k.size(0);
|
| 26 |
+
const int T = k.size(1);
|
| 27 |
+
const int C = k.size(2);
|
| 28 |
+
cuda_forward_with_state(B, T, C, w.data_ptr<float>(), u.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), y.data_ptr<float>(), s.data_ptr<float>());
|
| 29 |
+
}
|
| 30 |
+
void forward_with_state_bf16(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &s) {
|
| 31 |
+
const int B = k.size(0);
|
| 32 |
+
const int T = k.size(1);
|
| 33 |
+
const int C = k.size(2);
|
| 34 |
+
cuda_forward_with_state_bf16(B, T, C, w.data_ptr<float>(), u.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), y.data_ptr<bf16>(), s.data_ptr<float>());
|
| 35 |
+
}
|
| 36 |
+
void backward(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &gy, torch::Tensor &gw, torch::Tensor &gu, torch::Tensor &gk, torch::Tensor &gv) {
|
| 37 |
+
const int B = k.size(0);
|
| 38 |
+
const int T = k.size(1);
|
| 39 |
+
const int C = k.size(2);
|
| 40 |
+
cuda_backward(B, T, C, w.data_ptr<float>(), u.data_ptr<float>(), k.data_ptr<float>(), v.data_ptr<float>(), y.data_ptr<float>(), gy.data_ptr<float>(), gw.data_ptr<float>(), gu.data_ptr<float>(), gk.data_ptr<float>(), gv.data_ptr<float>());
|
| 41 |
+
}
|
| 42 |
+
void backward_bf16(torch::Tensor &w, torch::Tensor &u, torch::Tensor &k, torch::Tensor &v, torch::Tensor &y, torch::Tensor &gy, torch::Tensor &gw, torch::Tensor &gu, torch::Tensor &gk, torch::Tensor &gv) {
|
| 43 |
+
const int B = k.size(0);
|
| 44 |
+
const int T = k.size(1);
|
| 45 |
+
const int C = k.size(2);
|
| 46 |
+
cuda_backward_bf16(B, T, C, w.data_ptr<float>(), u.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), y.data_ptr<bf16>(),
|
| 47 |
+
gy.data_ptr<bf16>(), gw.data_ptr<bf16>(), gu.data_ptr<bf16>(), gk.data_ptr<bf16>(), gv.data_ptr<bf16>());
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 51 |
+
m.def("forward", &forward, "wkv forward");
|
| 52 |
+
m.def("forward_bf16", &forward_bf16, "wkv forward bf16");
|
| 53 |
+
m.def("forward_with_state", &forward_with_state, "wkv forward with state");
|
| 54 |
+
m.def("forward_with_state_bf16", &forward_with_state_bf16, "wkv forward with state bf16");
|
| 55 |
+
m.def("backward", &backward, "wkv backward");
|
| 56 |
+
m.def("backward_bf16", &backward_bf16, "wkv backward bf16");
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
TORCH_LIBRARY(wkv, m) {
|
| 60 |
+
m.def("forward", forward);
|
| 61 |
+
m.def("forward_bf16", forward_bf16);
|
| 62 |
+
m.def("forward_with_state", forward_with_state);
|
| 63 |
+
m.def("forward_with_state_bf16", forward_with_state_bf16);
|
| 64 |
+
m.def("backward", backward);
|
| 65 |
+
m.def("backward_bf16", backward_bf16);
|
| 66 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/transformers/kernels/yoso/common.h
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
#define min(a, b) ((a)<(b)?(a):(b))
|
| 3 |
+
#define max(a, b) ((a)>(b)?(a):(b))
|
| 4 |
+
#define ceil_divide(a, b) ((a)/(b)+((a)%(b)!=0))
|
| 5 |
+
#define select(cond, a, b) ((cond)?(a):(b))
|
| 6 |
+
#define PI 3.141592
|
| 7 |
+
#define EPSILON 1e-8
|
| 8 |
+
#define MAX_VAL 1e12
|
| 9 |
+
#define MIN_VAL -1e12
|
| 10 |
+
#define EMPTY_VALUE -1
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.58 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-310.pyc
ADDED
|
Binary file (7.71 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/modeling_flax_gptj.cpython-310.pyc
ADDED
|
Binary file (21 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-310.pyc
ADDED
|
Binary file (32.7 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/__pycache__/modeling_tf_gptj.cpython-310.pyc
ADDED
|
Binary file (33.7 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/transformers/models/gptj/modeling_flax_gptj.py
ADDED
|
@@ -0,0 +1,718 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The EleutherAI and The HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from functools import partial
|
| 17 |
+
from typing import Optional, Tuple
|
| 18 |
+
|
| 19 |
+
import flax.linen as nn
|
| 20 |
+
import jax
|
| 21 |
+
import jax.numpy as jnp
|
| 22 |
+
import numpy as np
|
| 23 |
+
from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
|
| 24 |
+
from flax.linen import combine_masks, make_causal_mask
|
| 25 |
+
from flax.linen.attention import dot_product_attention_weights
|
| 26 |
+
from flax.traverse_util import flatten_dict, unflatten_dict
|
| 27 |
+
from jax import lax
|
| 28 |
+
|
| 29 |
+
from ...modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutput
|
| 30 |
+
from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring
|
| 31 |
+
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
|
| 32 |
+
from .configuration_gptj import GPTJConfig
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
_CHECKPOINT_FOR_DOC = "gptj"
|
| 38 |
+
_CONFIG_FOR_DOC = "GPTJConfig"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
GPTJ_START_DOCSTRING = r"""
|
| 42 |
+
|
| 43 |
+
This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 44 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 45 |
+
etc.)
|
| 46 |
+
|
| 47 |
+
This model is also a Flax Linen
|
| 48 |
+
[flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
|
| 49 |
+
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
|
| 50 |
+
|
| 51 |
+
Finally, this model supports inherent JAX features such as:
|
| 52 |
+
|
| 53 |
+
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
|
| 54 |
+
- [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
|
| 55 |
+
- [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
|
| 56 |
+
- [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
|
| 57 |
+
|
| 58 |
+
Parameters:
|
| 59 |
+
config ([`GPTJConfig`]): Model configuration class with all the parameters of the model.
|
| 60 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 61 |
+
configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 62 |
+
dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
|
| 63 |
+
The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
|
| 64 |
+
`jax.numpy.bfloat16` (on TPUs).
|
| 65 |
+
|
| 66 |
+
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
|
| 67 |
+
specified all the computation will be performed with the given `dtype`.
|
| 68 |
+
|
| 69 |
+
**Note that this only specifies the dtype of the computation and does not influence the dtype of model
|
| 70 |
+
parameters.**
|
| 71 |
+
|
| 72 |
+
If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
|
| 73 |
+
[`~FlaxPreTrainedModel.to_bf16`].
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
GPTJ_INPUTS_DOCSTRING = r"""
|
| 77 |
+
Args:
|
| 78 |
+
input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
|
| 79 |
+
`input_ids_length` = `sequence_length`. Indices of input sequence tokens in the vocabulary.
|
| 80 |
+
|
| 81 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 82 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 83 |
+
|
| 84 |
+
[What are input IDs?](../glossary#input-ids)
|
| 85 |
+
attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 86 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 87 |
+
|
| 88 |
+
- 1 for tokens that are **not masked**,
|
| 89 |
+
- 0 for tokens that are **masked**.
|
| 90 |
+
|
| 91 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 92 |
+
position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
|
| 93 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 94 |
+
config.max_position_embeddings - 1]`.
|
| 95 |
+
past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
|
| 96 |
+
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
|
| 97 |
+
auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
|
| 98 |
+
output_attentions (`bool`, *optional*):
|
| 99 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 100 |
+
tensors for more detail.
|
| 101 |
+
output_hidden_states (`bool`, *optional*):
|
| 102 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 103 |
+
more detail.
|
| 104 |
+
return_dict (`bool`, *optional*):
|
| 105 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def create_sinusoidal_positions(num_pos, dim):
|
| 110 |
+
inv_freq = 1.0 / (10000 ** (np.arange(0, dim, 2) / dim))
|
| 111 |
+
sinusoid_inp = np.einsum("i , j -> i j", np.arange(num_pos), inv_freq).astype("float32")
|
| 112 |
+
sin, cos = np.sin(sinusoid_inp), np.cos(sinusoid_inp)
|
| 113 |
+
|
| 114 |
+
sentinel = dim // 2 + dim % 2
|
| 115 |
+
out = np.zeros((num_pos, dim))
|
| 116 |
+
out[:, 0:sentinel] = sin
|
| 117 |
+
out[:, sentinel:] = cos
|
| 118 |
+
|
| 119 |
+
return jnp.array(out)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def rotate_every_two(tensor):
|
| 123 |
+
rotate_half_tensor = jnp.stack((-tensor[:, :, :, 1::2], tensor[:, :, :, ::2]), axis=-1)
|
| 124 |
+
rotate_half_tensor = rotate_half_tensor.reshape(rotate_half_tensor.shape[:-2] + (-1,))
|
| 125 |
+
return rotate_half_tensor
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def apply_rotary_pos_emb(tensor, sincos):
|
| 129 |
+
sin_pos, cos_pos = sincos
|
| 130 |
+
sin_pos = sin_pos[:, :, None, :].repeat(2, 3)
|
| 131 |
+
cos_pos = cos_pos[:, :, None, :].repeat(2, 3)
|
| 132 |
+
return (tensor * cos_pos) + (rotate_every_two(tensor) * sin_pos)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class FlaxGPTJAttention(nn.Module):
|
| 136 |
+
config: GPTJConfig
|
| 137 |
+
dtype: jnp.dtype = jnp.float32
|
| 138 |
+
causal: bool = True
|
| 139 |
+
is_cross_attention: bool = False
|
| 140 |
+
|
| 141 |
+
def setup(self):
|
| 142 |
+
config = self.config
|
| 143 |
+
self.embed_dim = config.hidden_size
|
| 144 |
+
self.num_heads = config.num_attention_heads
|
| 145 |
+
self.head_dim = self.embed_dim // self.num_heads
|
| 146 |
+
|
| 147 |
+
self.rotary_dim = config.rotary_dim
|
| 148 |
+
|
| 149 |
+
dense = partial(
|
| 150 |
+
nn.Dense,
|
| 151 |
+
self.embed_dim,
|
| 152 |
+
use_bias=False,
|
| 153 |
+
dtype=self.dtype,
|
| 154 |
+
kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
|
| 158 |
+
self.out_proj = dense()
|
| 159 |
+
|
| 160 |
+
self.resid_dropout = nn.Dropout(rate=config.resid_pdrop)
|
| 161 |
+
|
| 162 |
+
self.causal_mask = make_causal_mask(jnp.ones((1, config.max_position_embeddings), dtype="bool"), dtype="bool")
|
| 163 |
+
|
| 164 |
+
pos_embd_dim = self.rotary_dim or self.embed_dim
|
| 165 |
+
self.embed_positions = create_sinusoidal_positions(config.max_position_embeddings, pos_embd_dim)
|
| 166 |
+
|
| 167 |
+
def _split_heads(self, hidden_states):
|
| 168 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
|
| 169 |
+
|
| 170 |
+
def _merge_heads(self, hidden_states):
|
| 171 |
+
return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
|
| 172 |
+
|
| 173 |
+
@nn.compact
|
| 174 |
+
def _concatenate_to_cache(self, key, value, query, attention_mask):
|
| 175 |
+
"""
|
| 176 |
+
This function takes projected key, value states from a single input token and concatenates the states to cached
|
| 177 |
+
states from previous steps. This function is slighly adapted from the official Flax repository:
|
| 178 |
+
https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
|
| 179 |
+
"""
|
| 180 |
+
# detect if we're initializing by absence of existing cache data.
|
| 181 |
+
is_initialized = self.has_variable("cache", "cached_key")
|
| 182 |
+
cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
|
| 183 |
+
cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
|
| 184 |
+
cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
|
| 185 |
+
|
| 186 |
+
if is_initialized:
|
| 187 |
+
*batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
|
| 188 |
+
# update key, value caches with our new 1d spatial slices
|
| 189 |
+
cur_index = cache_index.value
|
| 190 |
+
indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
|
| 191 |
+
key = lax.dynamic_update_slice(cached_key.value, key, indices)
|
| 192 |
+
value = lax.dynamic_update_slice(cached_value.value, value, indices)
|
| 193 |
+
cached_key.value = key
|
| 194 |
+
cached_value.value = value
|
| 195 |
+
num_updated_cache_vectors = query.shape[1]
|
| 196 |
+
cache_index.value = cache_index.value + num_updated_cache_vectors
|
| 197 |
+
# causal mask for cached decoder self-attention: our single query position should only attend to those key
|
| 198 |
+
# positions that have already been generated and cached, not the remaining zero elements.
|
| 199 |
+
pad_mask = jnp.broadcast_to(
|
| 200 |
+
jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
|
| 201 |
+
tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
|
| 202 |
+
)
|
| 203 |
+
attention_mask = combine_masks(pad_mask, attention_mask)
|
| 204 |
+
return key, value, attention_mask
|
| 205 |
+
|
| 206 |
+
def __call__(
|
| 207 |
+
self,
|
| 208 |
+
hidden_states,
|
| 209 |
+
attention_mask,
|
| 210 |
+
position_ids,
|
| 211 |
+
deterministic: bool = True,
|
| 212 |
+
init_cache: bool = False,
|
| 213 |
+
output_attentions: bool = False,
|
| 214 |
+
):
|
| 215 |
+
query = self.q_proj(hidden_states)
|
| 216 |
+
key = self.k_proj(hidden_states)
|
| 217 |
+
value = self.v_proj(hidden_states)
|
| 218 |
+
|
| 219 |
+
query = self._split_heads(query)
|
| 220 |
+
key = self._split_heads(key)
|
| 221 |
+
value = self._split_heads(value)
|
| 222 |
+
|
| 223 |
+
sincos = jnp.take(self.embed_positions, position_ids, axis=0)
|
| 224 |
+
sincos = jnp.split(sincos, 2, axis=-1)
|
| 225 |
+
if self.rotary_dim is not None:
|
| 226 |
+
k_rot = key[:, :, :, : self.rotary_dim]
|
| 227 |
+
k_pass = key[:, :, :, self.rotary_dim :]
|
| 228 |
+
|
| 229 |
+
q_rot = query[:, :, :, : self.rotary_dim]
|
| 230 |
+
q_pass = query[:, :, :, self.rotary_dim :]
|
| 231 |
+
|
| 232 |
+
k_rot = apply_rotary_pos_emb(k_rot, sincos)
|
| 233 |
+
q_rot = apply_rotary_pos_emb(q_rot, sincos)
|
| 234 |
+
|
| 235 |
+
key = jnp.concatenate([k_rot, k_pass], axis=-1)
|
| 236 |
+
query = jnp.concatenate([q_rot, q_pass], axis=-1)
|
| 237 |
+
else:
|
| 238 |
+
key = apply_rotary_pos_emb(key, sincos)
|
| 239 |
+
query = apply_rotary_pos_emb(query, sincos)
|
| 240 |
+
|
| 241 |
+
query_length, key_length = query.shape[1], key.shape[1]
|
| 242 |
+
|
| 243 |
+
if self.has_variable("cache", "cached_key"):
|
| 244 |
+
mask_shift = self.variables["cache"]["cache_index"]
|
| 245 |
+
max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
|
| 246 |
+
causal_mask = lax.dynamic_slice(
|
| 247 |
+
self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
|
| 248 |
+
)
|
| 249 |
+
else:
|
| 250 |
+
causal_mask = self.causal_mask[:, :, :query_length, :key_length]
|
| 251 |
+
|
| 252 |
+
batch_size = hidden_states.shape[0]
|
| 253 |
+
causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
|
| 254 |
+
|
| 255 |
+
attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
|
| 256 |
+
attention_mask = combine_masks(attention_mask, causal_mask)
|
| 257 |
+
|
| 258 |
+
dropout_rng = None
|
| 259 |
+
if not deterministic and self.config.attn_pdrop > 0.0:
|
| 260 |
+
dropout_rng = self.make_rng("dropout")
|
| 261 |
+
|
| 262 |
+
# During fast autoregressive decoding, we feed one position at a time,
|
| 263 |
+
# and cache the keys and values step by step.
|
| 264 |
+
if self.has_variable("cache", "cached_key") or init_cache:
|
| 265 |
+
key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
|
| 266 |
+
|
| 267 |
+
# transform boolean mask into float mask
|
| 268 |
+
attention_bias = lax.select(
|
| 269 |
+
attention_mask > 0,
|
| 270 |
+
jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
|
| 271 |
+
jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# usual dot product attention
|
| 275 |
+
attn_weights = dot_product_attention_weights(
|
| 276 |
+
query,
|
| 277 |
+
key,
|
| 278 |
+
bias=attention_bias,
|
| 279 |
+
dropout_rng=dropout_rng,
|
| 280 |
+
dropout_rate=self.config.attn_pdrop,
|
| 281 |
+
deterministic=deterministic,
|
| 282 |
+
dtype=self.dtype,
|
| 283 |
+
precision=None,
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
|
| 287 |
+
attn_output = self._merge_heads(attn_output)
|
| 288 |
+
attn_output = self.out_proj(attn_output)
|
| 289 |
+
attn_output = self.resid_dropout(attn_output, deterministic=deterministic)
|
| 290 |
+
|
| 291 |
+
outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
|
| 292 |
+
return outputs
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class FlaxGPTJMLP(nn.Module):
|
| 296 |
+
config: GPTJConfig
|
| 297 |
+
intermediate_size: int
|
| 298 |
+
dtype: jnp.dtype = jnp.float32
|
| 299 |
+
|
| 300 |
+
def setup(self):
|
| 301 |
+
embed_dim = self.config.hidden_size
|
| 302 |
+
kernel_init = jax.nn.initializers.normal(self.config.initializer_range)
|
| 303 |
+
|
| 304 |
+
self.fc_in = nn.Dense(self.intermediate_size, dtype=self.dtype, kernel_init=kernel_init)
|
| 305 |
+
self.fc_out = nn.Dense(embed_dim, dtype=self.dtype, kernel_init=kernel_init)
|
| 306 |
+
|
| 307 |
+
self.act = ACT2FN[self.config.activation_function]
|
| 308 |
+
self.dropout = nn.Dropout(rate=self.config.resid_pdrop)
|
| 309 |
+
|
| 310 |
+
def __call__(self, hidden_states, deterministic: bool = True):
|
| 311 |
+
hidden_states = self.fc_in(hidden_states)
|
| 312 |
+
hidden_states = self.act(hidden_states)
|
| 313 |
+
hidden_states = self.fc_out(hidden_states)
|
| 314 |
+
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
|
| 315 |
+
return hidden_states
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class FlaxGPTJBlock(nn.Module):
|
| 319 |
+
config: GPTJConfig
|
| 320 |
+
dtype: jnp.dtype = jnp.float32
|
| 321 |
+
|
| 322 |
+
def setup(self):
|
| 323 |
+
hidden_size = self.config.hidden_size
|
| 324 |
+
inner_dim = self.config.n_inner if self.config.n_inner is not None else 4 * hidden_size
|
| 325 |
+
|
| 326 |
+
self.ln_1 = nn.LayerNorm(epsilon=self.config.layer_norm_epsilon, dtype=self.dtype)
|
| 327 |
+
self.attn = FlaxGPTJAttention(self.config, dtype=self.dtype)
|
| 328 |
+
|
| 329 |
+
self.mlp = FlaxGPTJMLP(self.config, inner_dim, dtype=self.dtype)
|
| 330 |
+
|
| 331 |
+
def __call__(
|
| 332 |
+
self,
|
| 333 |
+
hidden_states,
|
| 334 |
+
attention_mask=None,
|
| 335 |
+
position_ids=None,
|
| 336 |
+
deterministic: bool = True,
|
| 337 |
+
init_cache: bool = False,
|
| 338 |
+
output_attentions: bool = False,
|
| 339 |
+
):
|
| 340 |
+
residual = hidden_states
|
| 341 |
+
hidden_states = self.ln_1(hidden_states)
|
| 342 |
+
attn_outputs = self.attn(
|
| 343 |
+
hidden_states,
|
| 344 |
+
attention_mask=attention_mask,
|
| 345 |
+
position_ids=position_ids,
|
| 346 |
+
deterministic=deterministic,
|
| 347 |
+
init_cache=init_cache,
|
| 348 |
+
output_attentions=output_attentions,
|
| 349 |
+
)
|
| 350 |
+
attn_output = attn_outputs[0]
|
| 351 |
+
|
| 352 |
+
feed_forward_hidden_states = self.mlp(hidden_states, deterministic=deterministic)
|
| 353 |
+
# residual connection
|
| 354 |
+
hidden_states = attn_output + feed_forward_hidden_states + residual
|
| 355 |
+
|
| 356 |
+
return (hidden_states,) + attn_outputs[1:]
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class FlaxGPTJPreTrainedModel(FlaxPreTrainedModel):
|
| 360 |
+
"""
|
| 361 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 362 |
+
models.
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
config_class = GPTJConfig
|
| 366 |
+
base_model_prefix = "transformer"
|
| 367 |
+
module_class: nn.Module = None
|
| 368 |
+
|
| 369 |
+
def __init__(
|
| 370 |
+
self,
|
| 371 |
+
config: GPTJConfig,
|
| 372 |
+
input_shape: Tuple = (1, 1),
|
| 373 |
+
seed: int = 0,
|
| 374 |
+
dtype: jnp.dtype = jnp.float32,
|
| 375 |
+
_do_init: bool = True,
|
| 376 |
+
**kwargs,
|
| 377 |
+
):
|
| 378 |
+
module = self.module_class(config=config, dtype=dtype, **kwargs)
|
| 379 |
+
super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
|
| 380 |
+
|
| 381 |
+
def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
|
| 382 |
+
# init input tensors
|
| 383 |
+
input_ids = jnp.zeros(input_shape, dtype="i4")
|
| 384 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 385 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
|
| 386 |
+
params_rng, dropout_rng = jax.random.split(rng)
|
| 387 |
+
rngs = {"params": params_rng, "dropout": dropout_rng}
|
| 388 |
+
|
| 389 |
+
if self.config.add_cross_attention:
|
| 390 |
+
encoder_hidden_states = jnp.zeros(input_shape + (self.config.n_embd,))
|
| 391 |
+
encoder_attention_mask = attention_mask
|
| 392 |
+
module_init_outputs = self.module.init(
|
| 393 |
+
rngs,
|
| 394 |
+
input_ids,
|
| 395 |
+
attention_mask,
|
| 396 |
+
position_ids,
|
| 397 |
+
encoder_hidden_states,
|
| 398 |
+
encoder_attention_mask,
|
| 399 |
+
return_dict=False,
|
| 400 |
+
)
|
| 401 |
+
else:
|
| 402 |
+
module_init_outputs = self.module.init(rngs, input_ids, attention_mask, position_ids, return_dict=False)
|
| 403 |
+
|
| 404 |
+
random_params = module_init_outputs["params"]
|
| 405 |
+
|
| 406 |
+
if params is not None:
|
| 407 |
+
random_params = flatten_dict(unfreeze(random_params))
|
| 408 |
+
params = flatten_dict(unfreeze(params))
|
| 409 |
+
for missing_key in self._missing_keys:
|
| 410 |
+
params[missing_key] = random_params[missing_key]
|
| 411 |
+
self._missing_keys = set()
|
| 412 |
+
return freeze(unflatten_dict(params))
|
| 413 |
+
else:
|
| 414 |
+
return random_params
|
| 415 |
+
|
| 416 |
+
def init_cache(self, batch_size, max_length):
|
| 417 |
+
r"""
|
| 418 |
+
Args:
|
| 419 |
+
batch_size (`int`):
|
| 420 |
+
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
|
| 421 |
+
max_length (`int`):
|
| 422 |
+
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
|
| 423 |
+
cache.
|
| 424 |
+
"""
|
| 425 |
+
# init input variables to retrieve cache
|
| 426 |
+
input_ids = jnp.ones((batch_size, max_length))
|
| 427 |
+
attention_mask = jnp.ones_like(input_ids)
|
| 428 |
+
position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
|
| 429 |
+
|
| 430 |
+
init_variables = self.module.init(
|
| 431 |
+
jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
|
| 432 |
+
)
|
| 433 |
+
return init_variables["cache"]
|
| 434 |
+
|
| 435 |
+
@add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING)
|
| 436 |
+
def __call__(
|
| 437 |
+
self,
|
| 438 |
+
input_ids,
|
| 439 |
+
attention_mask=None,
|
| 440 |
+
position_ids=None,
|
| 441 |
+
params: dict = None,
|
| 442 |
+
past_key_values: dict = None,
|
| 443 |
+
dropout_rng: jax.random.PRNGKey = None,
|
| 444 |
+
train: bool = False,
|
| 445 |
+
output_attentions: Optional[bool] = None,
|
| 446 |
+
output_hidden_states: Optional[bool] = None,
|
| 447 |
+
return_dict: Optional[bool] = None,
|
| 448 |
+
):
|
| 449 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 450 |
+
output_hidden_states = (
|
| 451 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 452 |
+
)
|
| 453 |
+
return_dict = return_dict if return_dict is not None else self.config.return_dict
|
| 454 |
+
|
| 455 |
+
batch_size, sequence_length = input_ids.shape
|
| 456 |
+
|
| 457 |
+
if position_ids is None:
|
| 458 |
+
if past_key_values is not None:
|
| 459 |
+
raise ValueError("Make sure to provide `position_ids` when passing `past_key_values`.")
|
| 460 |
+
|
| 461 |
+
position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
|
| 462 |
+
|
| 463 |
+
if attention_mask is None:
|
| 464 |
+
attention_mask = jnp.ones((batch_size, sequence_length))
|
| 465 |
+
|
| 466 |
+
# Handle any PRNG if needed
|
| 467 |
+
rngs = {}
|
| 468 |
+
if dropout_rng is not None:
|
| 469 |
+
rngs["dropout"] = dropout_rng
|
| 470 |
+
|
| 471 |
+
inputs = {"params": params or self.params}
|
| 472 |
+
|
| 473 |
+
# if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be changed by FlaxGPTJAttention module
|
| 474 |
+
if past_key_values:
|
| 475 |
+
inputs["cache"] = past_key_values
|
| 476 |
+
mutable = ["cache"]
|
| 477 |
+
else:
|
| 478 |
+
mutable = False
|
| 479 |
+
|
| 480 |
+
outputs = self.module.apply(
|
| 481 |
+
inputs,
|
| 482 |
+
jnp.array(input_ids, dtype="i4"),
|
| 483 |
+
jnp.array(attention_mask, dtype="i4"),
|
| 484 |
+
jnp.array(position_ids, dtype="i4"),
|
| 485 |
+
not train,
|
| 486 |
+
False,
|
| 487 |
+
output_attentions,
|
| 488 |
+
output_hidden_states,
|
| 489 |
+
return_dict,
|
| 490 |
+
rngs=rngs,
|
| 491 |
+
mutable=mutable,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
# add updated cache to model output
|
| 495 |
+
if past_key_values is not None and return_dict:
|
| 496 |
+
outputs, past_key_values = outputs
|
| 497 |
+
outputs["past_key_values"] = unfreeze(past_key_values["cache"])
|
| 498 |
+
return outputs
|
| 499 |
+
elif past_key_values is not None and not return_dict:
|
| 500 |
+
outputs, past_key_values = outputs
|
| 501 |
+
outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
|
| 502 |
+
|
| 503 |
+
return outputs
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
class FlaxGPTJBlockCollection(nn.Module):
|
| 507 |
+
config: GPTJConfig
|
| 508 |
+
dtype: jnp.dtype = jnp.float32
|
| 509 |
+
|
| 510 |
+
def setup(self):
|
| 511 |
+
self.blocks = [
|
| 512 |
+
FlaxGPTJBlock(self.config, name=str(i), dtype=self.dtype) for i in range(self.config.num_hidden_layers)
|
| 513 |
+
]
|
| 514 |
+
|
| 515 |
+
def __call__(
|
| 516 |
+
self,
|
| 517 |
+
hidden_states,
|
| 518 |
+
attention_mask=None,
|
| 519 |
+
position_ids=None,
|
| 520 |
+
deterministic: bool = True,
|
| 521 |
+
init_cache: bool = False,
|
| 522 |
+
output_attentions: bool = False,
|
| 523 |
+
output_hidden_states: bool = False,
|
| 524 |
+
return_dict: bool = True,
|
| 525 |
+
):
|
| 526 |
+
all_attentions = () if output_attentions else None
|
| 527 |
+
all_hidden_states = () if output_hidden_states else None
|
| 528 |
+
|
| 529 |
+
for block in self.blocks:
|
| 530 |
+
if output_hidden_states:
|
| 531 |
+
all_hidden_states += (hidden_states,)
|
| 532 |
+
|
| 533 |
+
layer_outputs = block(
|
| 534 |
+
hidden_states,
|
| 535 |
+
attention_mask,
|
| 536 |
+
position_ids=position_ids,
|
| 537 |
+
deterministic=deterministic,
|
| 538 |
+
init_cache=init_cache,
|
| 539 |
+
output_attentions=output_attentions,
|
| 540 |
+
)
|
| 541 |
+
hidden_states = layer_outputs[0]
|
| 542 |
+
|
| 543 |
+
if output_attentions:
|
| 544 |
+
all_attentions += (layer_outputs[1],)
|
| 545 |
+
|
| 546 |
+
# this contains possible `None` values - `FlaxGPTJModule` will filter them out
|
| 547 |
+
outputs = (hidden_states, all_hidden_states, all_attentions)
|
| 548 |
+
|
| 549 |
+
return outputs
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class FlaxGPTJModule(nn.Module):
|
| 553 |
+
config: GPTJConfig
|
| 554 |
+
dtype: jnp.dtype = jnp.float32
|
| 555 |
+
|
| 556 |
+
def setup(self):
|
| 557 |
+
self.embed_dim = self.config.hidden_size
|
| 558 |
+
|
| 559 |
+
self.wte = nn.Embed(
|
| 560 |
+
self.config.vocab_size,
|
| 561 |
+
self.config.hidden_size,
|
| 562 |
+
embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 563 |
+
)
|
| 564 |
+
self.dropout = nn.Dropout(rate=self.config.embd_pdrop)
|
| 565 |
+
self.h = FlaxGPTJBlockCollection(self.config, dtype=self.dtype)
|
| 566 |
+
self.ln_f = nn.LayerNorm(epsilon=self.config.layer_norm_epsilon, dtype=self.dtype)
|
| 567 |
+
|
| 568 |
+
def __call__(
|
| 569 |
+
self,
|
| 570 |
+
input_ids,
|
| 571 |
+
attention_mask,
|
| 572 |
+
position_ids,
|
| 573 |
+
deterministic=True,
|
| 574 |
+
init_cache: bool = False,
|
| 575 |
+
output_attentions: bool = False,
|
| 576 |
+
output_hidden_states: bool = False,
|
| 577 |
+
return_dict: bool = True,
|
| 578 |
+
):
|
| 579 |
+
input_embeds = self.wte(input_ids.astype("i4"))
|
| 580 |
+
|
| 581 |
+
hidden_states = self.dropout(input_embeds, deterministic=deterministic)
|
| 582 |
+
|
| 583 |
+
outputs = self.h(
|
| 584 |
+
hidden_states,
|
| 585 |
+
attention_mask,
|
| 586 |
+
position_ids=position_ids,
|
| 587 |
+
deterministic=deterministic,
|
| 588 |
+
init_cache=init_cache,
|
| 589 |
+
output_attentions=output_attentions,
|
| 590 |
+
output_hidden_states=output_hidden_states,
|
| 591 |
+
return_dict=return_dict,
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
hidden_states = outputs[0]
|
| 595 |
+
hidden_states = self.ln_f(hidden_states)
|
| 596 |
+
|
| 597 |
+
if output_hidden_states:
|
| 598 |
+
all_hidden_states = outputs[1] + (hidden_states,)
|
| 599 |
+
outputs = (hidden_states, all_hidden_states) + outputs[2:]
|
| 600 |
+
else:
|
| 601 |
+
outputs = (hidden_states,) + outputs[1:]
|
| 602 |
+
|
| 603 |
+
if not return_dict:
|
| 604 |
+
return tuple(v for v in outputs if v is not None)
|
| 605 |
+
|
| 606 |
+
return FlaxBaseModelOutput(
|
| 607 |
+
last_hidden_state=hidden_states,
|
| 608 |
+
hidden_states=outputs[1],
|
| 609 |
+
attentions=outputs[-1],
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
@add_start_docstrings(
|
| 614 |
+
"The bare GPTJ Model transformer outputting raw hidden-states without any specific head on top.",
|
| 615 |
+
GPTJ_START_DOCSTRING,
|
| 616 |
+
)
|
| 617 |
+
class FlaxGPTJModel(FlaxGPTJPreTrainedModel):
|
| 618 |
+
module_class = FlaxGPTJModule
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
append_call_sample_docstring(
|
| 622 |
+
FlaxGPTJModel,
|
| 623 |
+
_CHECKPOINT_FOR_DOC,
|
| 624 |
+
FlaxCausalLMOutput,
|
| 625 |
+
_CONFIG_FOR_DOC,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
class FlaxGPTJForCausalLMModule(nn.Module):
|
| 630 |
+
config: GPTJConfig
|
| 631 |
+
dtype: jnp.dtype = jnp.float32
|
| 632 |
+
|
| 633 |
+
def setup(self):
|
| 634 |
+
self.transformer = FlaxGPTJModule(self.config, dtype=self.dtype)
|
| 635 |
+
self.lm_head = nn.Dense(
|
| 636 |
+
self.config.vocab_size,
|
| 637 |
+
dtype=self.dtype,
|
| 638 |
+
kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
def __call__(
|
| 642 |
+
self,
|
| 643 |
+
input_ids,
|
| 644 |
+
attention_mask,
|
| 645 |
+
position_ids,
|
| 646 |
+
deterministic: bool = True,
|
| 647 |
+
init_cache: bool = False,
|
| 648 |
+
output_attentions: bool = False,
|
| 649 |
+
output_hidden_states: bool = False,
|
| 650 |
+
return_dict: bool = True,
|
| 651 |
+
):
|
| 652 |
+
outputs = self.transformer(
|
| 653 |
+
input_ids,
|
| 654 |
+
attention_mask,
|
| 655 |
+
position_ids,
|
| 656 |
+
deterministic=deterministic,
|
| 657 |
+
init_cache=init_cache,
|
| 658 |
+
output_attentions=output_attentions,
|
| 659 |
+
output_hidden_states=output_hidden_states,
|
| 660 |
+
return_dict=return_dict,
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
hidden_states = outputs[0]
|
| 664 |
+
|
| 665 |
+
if self.config.tie_word_embeddings:
|
| 666 |
+
shared_kernel = self.transformer.variables["params"]["wte"]["embedding"].T
|
| 667 |
+
lm_logits = self.lm_head.apply({"params": {"kernel": shared_kernel}}, hidden_states)
|
| 668 |
+
else:
|
| 669 |
+
lm_logits = self.lm_head(hidden_states)
|
| 670 |
+
|
| 671 |
+
if not return_dict:
|
| 672 |
+
return (lm_logits,) + outputs[1:]
|
| 673 |
+
|
| 674 |
+
return FlaxCausalLMOutput(logits=lm_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
@add_start_docstrings(
|
| 678 |
+
"""
|
| 679 |
+
The GPTJ Model transformer with a language modeling head on top.
|
| 680 |
+
""",
|
| 681 |
+
GPTJ_START_DOCSTRING,
|
| 682 |
+
)
|
| 683 |
+
class FlaxGPTJForCausalLM(FlaxGPTJPreTrainedModel):
|
| 684 |
+
module_class = FlaxGPTJForCausalLMModule
|
| 685 |
+
|
| 686 |
+
def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
|
| 687 |
+
# initializing the cache
|
| 688 |
+
batch_size, seq_length = input_ids.shape
|
| 689 |
+
|
| 690 |
+
past_key_values = self.init_cache(batch_size, max_length)
|
| 691 |
+
# Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
|
| 692 |
+
# But since GPTJ uses a causal mask, those positions are masked anyways.
|
| 693 |
+
# Thus we can create a single static attention_mask here, which is more efficient for compilation
|
| 694 |
+
extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
|
| 695 |
+
if attention_mask is not None:
|
| 696 |
+
position_ids = attention_mask.cumsum(axis=-1) - 1
|
| 697 |
+
extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
|
| 698 |
+
else:
|
| 699 |
+
position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
|
| 700 |
+
|
| 701 |
+
return {
|
| 702 |
+
"past_key_values": past_key_values,
|
| 703 |
+
"attention_mask": extended_attention_mask,
|
| 704 |
+
"position_ids": position_ids,
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
def update_inputs_for_generation(self, model_outputs, model_kwargs):
|
| 708 |
+
model_kwargs["past_key_values"] = model_outputs.past_key_values
|
| 709 |
+
model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
|
| 710 |
+
return model_kwargs
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
append_call_sample_docstring(
|
| 714 |
+
FlaxGPTJForCausalLM,
|
| 715 |
+
_CHECKPOINT_F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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The EleutherAI and HuggingFace Teams. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" TF 2.0 GPT-J model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from typing import Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import tensorflow as tf
|
| 23 |
+
|
| 24 |
+
from ...activations_tf import get_tf_activation
|
| 25 |
+
from ...file_utils import (
|
| 26 |
+
add_code_sample_docstrings,
|
| 27 |
+
add_start_docstrings,
|
| 28 |
+
add_start_docstrings_to_model_forward,
|
| 29 |
+
)
|
| 30 |
+
from ...modeling_tf_outputs import (
|
| 31 |
+
TFBaseModelOutputWithPast,
|
| 32 |
+
TFCausalLMOutputWithPast,
|
| 33 |
+
TFQuestionAnsweringModelOutput,
|
| 34 |
+
TFSequenceClassifierOutputWithPast,
|
| 35 |
+
)
|
| 36 |
+
from ...modeling_tf_utils import (
|
| 37 |
+
TFCausalLanguageModelingLoss,
|
| 38 |
+
TFModelInputType,
|
| 39 |
+
TFPreTrainedModel,
|
| 40 |
+
TFQuestionAnsweringLoss,
|
| 41 |
+
TFSequenceClassificationLoss,
|
| 42 |
+
TFSharedEmbeddings,
|
| 43 |
+
get_initializer,
|
| 44 |
+
keras_serializable,
|
| 45 |
+
unpack_inputs,
|
| 46 |
+
)
|
| 47 |
+
from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
|
| 48 |
+
from ...utils import logging
|
| 49 |
+
from .configuration_gptj import GPTJConfig
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
logger = logging.get_logger(__name__)
|
| 53 |
+
|
| 54 |
+
_CHECKPOINT_FOR_DOC = "EleutherAI/gpt-j-6B"
|
| 55 |
+
_CONFIG_FOR_DOC = "GPTJConfig"
|
| 56 |
+
|
| 57 |
+
GPTJ_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 58 |
+
"EleutherAI/gpt-j-6B",
|
| 59 |
+
# See all GPT-J models at https://huggingface.co/models?filter=gptj
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def create_sinusoidal_positions(num_pos: int, dim: int) -> tf.Tensor:
|
| 64 |
+
inv_freq = tf.cast(1.0 / (10000 ** (tf.range(0, dim, 2) / dim)), tf.float32)
|
| 65 |
+
sinusoid_inp = tf.cast(tf.einsum("i , j -> i j", tf.range(num_pos, dtype=tf.float32), inv_freq), tf.float32)
|
| 66 |
+
sin, cos = tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)
|
| 67 |
+
out = tf.concat((sin, cos), axis=1)
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def rotate_every_two(x: tf.Tensor) -> tf.Tensor:
|
| 72 |
+
rotate_half_tensor = tf.stack((-x[:, :, :, 1::2], x[:, :, :, ::2]), axis=-1)
|
| 73 |
+
new_shape = shape_list(rotate_half_tensor)[:-2] + [tf.math.reduce_prod(shape_list(rotate_half_tensor)[-2:])]
|
| 74 |
+
rotate_half_tensor = tf.reshape(rotate_half_tensor, new_shape)
|
| 75 |
+
return rotate_half_tensor
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def apply_rotary_pos_emb(tensor: tf.Tensor, sincos: tf.Tensor) -> tf.Tensor:
|
| 79 |
+
sin_pos, cos_pos = sincos
|
| 80 |
+
sin_pos = tf.repeat(sin_pos[:, :, None, :], 2, 3)
|
| 81 |
+
cos_pos = tf.repeat(cos_pos[:, :, None, :], 2, 3)
|
| 82 |
+
return (tensor * cos_pos) + (rotate_every_two(tensor) * sin_pos)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TFGPTJAttention(tf.keras.layers.Layer):
|
| 86 |
+
def __init__(self, config: GPTJConfig, **kwargs):
|
| 87 |
+
super().__init__(**kwargs)
|
| 88 |
+
|
| 89 |
+
self.embed_dim = config.hidden_size
|
| 90 |
+
self.num_attention_heads = config.num_attention_heads
|
| 91 |
+
self.head_dim = self.embed_dim // self.num_attention_heads
|
| 92 |
+
if self.head_dim * self.num_attention_heads != self.embed_dim:
|
| 93 |
+
raise ValueError(
|
| 94 |
+
f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and"
|
| 95 |
+
f" `num_attention_heads`: {self.num_attention_heads})."
|
| 96 |
+
)
|
| 97 |
+
self.scale_attn = self.head_dim**0.5
|
| 98 |
+
self.rotary_dim = config.rotary_dim
|
| 99 |
+
|
| 100 |
+
self.attn_dropout = tf.keras.layers.Dropout(config.attn_pdrop)
|
| 101 |
+
self.resid_dropout = tf.keras.layers.Dropout(config.resid_pdrop)
|
| 102 |
+
|
| 103 |
+
self.q_proj = tf.keras.layers.Dense(
|
| 104 |
+
self.embed_dim,
|
| 105 |
+
use_bias=False,
|
| 106 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 107 |
+
name="q_proj",
|
| 108 |
+
)
|
| 109 |
+
self.k_proj = tf.keras.layers.Dense(
|
| 110 |
+
self.embed_dim,
|
| 111 |
+
use_bias=False,
|
| 112 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 113 |
+
name="k_proj",
|
| 114 |
+
)
|
| 115 |
+
self.v_proj = tf.keras.layers.Dense(
|
| 116 |
+
self.embed_dim,
|
| 117 |
+
use_bias=False,
|
| 118 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 119 |
+
name="v_proj",
|
| 120 |
+
)
|
| 121 |
+
self.out_proj = tf.keras.layers.Dense(
|
| 122 |
+
self.embed_dim,
|
| 123 |
+
use_bias=False,
|
| 124 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 125 |
+
name="out_proj",
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
self.max_positions = config.max_position_embeddings
|
| 129 |
+
self.lower_triangle_mask = tf.reshape(
|
| 130 |
+
tf.cast(tf.experimental.numpy.tril(tf.ones((self.max_positions, self.max_positions))), tf.int8),
|
| 131 |
+
(1, 1, self.max_positions, self.max_positions),
|
| 132 |
+
)
|
| 133 |
+
pos_embd_dim = self.rotary_dim or self.embed_dim
|
| 134 |
+
self.embed_positions = create_sinusoidal_positions(self.max_positions, pos_embd_dim)
|
| 135 |
+
|
| 136 |
+
def get_causal_mask(self, key_length, query_length) -> tf.Tensor:
|
| 137 |
+
return tf.cast(self.lower_triangle_mask[:, :, key_length - query_length : key_length, :key_length], tf.bool)
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def get_masked_bias(dtype: tf.DType) -> tf.Tensor:
|
| 141 |
+
return tf.cast(tf.constant(-1e9), dtype)
|
| 142 |
+
|
| 143 |
+
def _split_heads(self, hidden_states: tf.Tensor, rotary: bool) -> tf.Tensor:
|
| 144 |
+
"""
|
| 145 |
+
Splits hidden dim into attn_head_size and num_attention_heads
|
| 146 |
+
"""
|
| 147 |
+
new_shape = shape_list(hidden_states)[:-1] + [self.num_attention_heads, self.head_dim]
|
| 148 |
+
hidden_states = tf.reshape(hidden_states, new_shape)
|
| 149 |
+
if rotary:
|
| 150 |
+
return hidden_states
|
| 151 |
+
if len(shape_list(hidden_states)) == 4:
|
| 152 |
+
return tf.transpose(hidden_states, (0, 2, 1, 3)) # (batch, head, seq_length, head_features)
|
| 153 |
+
if len(shape_list(hidden_states)) == 5:
|
| 154 |
+
return tf.transpose(hidden_states, (0, 1, 3, 2, 4)) # (batch, blocks, head, block_length, head_features)
|
| 155 |
+
raise ValueError(f"Input tensor rank should be one of [4, 5], but is: {len(shape_list(hidden_states))}")
|
| 156 |
+
|
| 157 |
+
def _merge_heads(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 158 |
+
"""
|
| 159 |
+
Merges attn_head_size dim and num_attn_heads dim into hidden dim
|
| 160 |
+
"""
|
| 161 |
+
if len(shape_list(hidden_states)) == 4:
|
| 162 |
+
hidden_states = tf.transpose(hidden_states, (0, 2, 1, 3))
|
| 163 |
+
elif len(shape_list(hidden_states)) == 5:
|
| 164 |
+
hidden_states = tf.transpose(hidden_states, (0, 1, 3, 2, 4))
|
| 165 |
+
else:
|
| 166 |
+
raise ValueError(f"Input tensor rank should be one of [4, 5], but is: {len(shape_list(hidden_states))}")
|
| 167 |
+
new_shape = shape_list(hidden_states)[:-2] + [self.num_attention_heads * self.head_dim]
|
| 168 |
+
return tf.reshape(hidden_states, new_shape)
|
| 169 |
+
|
| 170 |
+
def _attn(
|
| 171 |
+
self,
|
| 172 |
+
query: tf.Tensor,
|
| 173 |
+
key: tf.Tensor,
|
| 174 |
+
value: tf.Tensor,
|
| 175 |
+
attention_mask: tf.Tensor | None = None,
|
| 176 |
+
head_mask: tf.Tensor | None = None,
|
| 177 |
+
) -> Tuple[tf.Tensor, tf.Tensor]:
|
| 178 |
+
# compute causal mask from causal mask buffer
|
| 179 |
+
query_length, key_length = shape_list(query)[-2], shape_list(key)[-2]
|
| 180 |
+
causal_mask = self.get_causal_mask(key_length, query_length)
|
| 181 |
+
|
| 182 |
+
# Keep the attention weights computation in fp32 to avoid overflow issues
|
| 183 |
+
query = tf.cast(query, tf.float32)
|
| 184 |
+
key = tf.cast(key, tf.float32)
|
| 185 |
+
|
| 186 |
+
attn_weights = tf.matmul(query, key, transpose_b=True)
|
| 187 |
+
attn_weights = tf.where(causal_mask, attn_weights, self.get_masked_bias(attn_weights.dtype))
|
| 188 |
+
|
| 189 |
+
attn_weights = attn_weights / self.scale_attn
|
| 190 |
+
|
| 191 |
+
if attention_mask is not None:
|
| 192 |
+
# Apply the attention mask
|
| 193 |
+
attn_weights = attn_weights + attention_mask
|
| 194 |
+
|
| 195 |
+
attn_weights = stable_softmax(attn_weights, axis=-1)
|
| 196 |
+
attn_weights = tf.cast(attn_weights, value.dtype)
|
| 197 |
+
attn_weights = self.attn_dropout(attn_weights)
|
| 198 |
+
|
| 199 |
+
# Mask heads if we want to
|
| 200 |
+
if head_mask is not None:
|
| 201 |
+
attn_weights = attn_weights * head_mask
|
| 202 |
+
|
| 203 |
+
attn_output = tf.matmul(attn_weights, value)
|
| 204 |
+
|
| 205 |
+
return attn_output, attn_weights
|
| 206 |
+
|
| 207 |
+
def call(
|
| 208 |
+
self,
|
| 209 |
+
hidden_states: tf.Tensor,
|
| 210 |
+
layer_past: Optional[Tuple[tf.Tensor, tf.Tensor]] = None,
|
| 211 |
+
attention_mask: tf.Tensor | None = None,
|
| 212 |
+
position_ids: tf.Tensor | None = None,
|
| 213 |
+
head_mask: tf.Tensor | None = None,
|
| 214 |
+
use_cache: bool = False,
|
| 215 |
+
output_attentions: bool = False,
|
| 216 |
+
):
|
| 217 |
+
query = self.q_proj(hidden_states)
|
| 218 |
+
key = self.k_proj(hidden_states)
|
| 219 |
+
value = self.v_proj(hidden_states)
|
| 220 |
+
|
| 221 |
+
query = self._split_heads(query, True)
|
| 222 |
+
key = self._split_heads(key, True)
|
| 223 |
+
value = self._split_heads(value, False)
|
| 224 |
+
|
| 225 |
+
sincos = tf.cast(tf.gather(self.embed_positions, position_ids, axis=0), hidden_states.dtype)
|
| 226 |
+
sincos = tf.split(sincos, 2, axis=-1)
|
| 227 |
+
if self.rotary_dim is not None:
|
| 228 |
+
k_rot = key[:, :, :, : self.rotary_dim]
|
| 229 |
+
k_pass = key[:, :, :, self.rotary_dim :]
|
| 230 |
+
|
| 231 |
+
q_rot = query[:, :, :, : self.rotary_dim]
|
| 232 |
+
q_pass = query[:, :, :, self.rotary_dim :]
|
| 233 |
+
|
| 234 |
+
k_rot = apply_rotary_pos_emb(k_rot, sincos)
|
| 235 |
+
q_rot = apply_rotary_pos_emb(q_rot, sincos)
|
| 236 |
+
|
| 237 |
+
key = tf.concat((k_rot, k_pass), axis=-1)
|
| 238 |
+
query = tf.concat((q_rot, q_pass), axis=-1)
|
| 239 |
+
else:
|
| 240 |
+
key = apply_rotary_pos_emb(key, sincos)
|
| 241 |
+
query = apply_rotary_pos_emb(query, sincos)
|
| 242 |
+
|
| 243 |
+
key = tf.transpose(key, (0, 2, 1, 3))
|
| 244 |
+
query = tf.transpose(query, (0, 2, 1, 3))
|
| 245 |
+
|
| 246 |
+
if layer_past is not None:
|
| 247 |
+
past_key = layer_past[0]
|
| 248 |
+
past_value = layer_past[1]
|
| 249 |
+
key = tf.concat((past_key, key), axis=-2)
|
| 250 |
+
value = tf.concat((past_value, value), axis=-2)
|
| 251 |
+
|
| 252 |
+
if use_cache is True:
|
| 253 |
+
present = (key, value)
|
| 254 |
+
else:
|
| 255 |
+
present = None
|
| 256 |
+
|
| 257 |
+
# compute self-attention: V x Softmax(QK^T)
|
| 258 |
+
attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
|
| 259 |
+
|
| 260 |
+
attn_output = self._merge_heads(attn_output)
|
| 261 |
+
attn_output = self.out_proj(attn_output)
|
| 262 |
+
attn_output = self.resid_dropout(attn_output)
|
| 263 |
+
|
| 264 |
+
outputs = (attn_output, present)
|
| 265 |
+
if output_attentions:
|
| 266 |
+
outputs += (attn_weights,)
|
| 267 |
+
|
| 268 |
+
return outputs # a, present, (attentions)
|
| 269 |
+
|
| 270 |
+
def build(self, input_shape=None):
|
| 271 |
+
if self.built:
|
| 272 |
+
return
|
| 273 |
+
self.built = True
|
| 274 |
+
if getattr(self, "q_proj", None) is not None:
|
| 275 |
+
with tf.name_scope(self.q_proj.name):
|
| 276 |
+
self.q_proj.build([None, None, self.embed_dim])
|
| 277 |
+
if getattr(self, "k_proj", None) is not None:
|
| 278 |
+
with tf.name_scope(self.k_proj.name):
|
| 279 |
+
self.k_proj.build([None, None, self.embed_dim])
|
| 280 |
+
if getattr(self, "v_proj", None) is not None:
|
| 281 |
+
with tf.name_scope(self.v_proj.name):
|
| 282 |
+
self.v_proj.build([None, None, self.embed_dim])
|
| 283 |
+
if getattr(self, "out_proj", None) is not None:
|
| 284 |
+
with tf.name_scope(self.out_proj.name):
|
| 285 |
+
self.out_proj.build([None, None, self.embed_dim])
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class TFGPTJMLP(tf.keras.layers.Layer):
|
| 289 |
+
def __init__(self, intermediate_size: int, config: GPTJConfig, **kwargs):
|
| 290 |
+
super().__init__(**kwargs)
|
| 291 |
+
embed_dim = config.n_embd
|
| 292 |
+
|
| 293 |
+
self.fc_in = tf.keras.layers.Dense(
|
| 294 |
+
intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="fc_in"
|
| 295 |
+
)
|
| 296 |
+
self.fc_out = tf.keras.layers.Dense(
|
| 297 |
+
embed_dim, kernel_initializer=get_initializer(config.initializer_range), name="fc_out"
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
self.act = get_tf_activation(config.activation_function)
|
| 301 |
+
self.dropout = tf.keras.layers.Dropout(config.embd_pdrop)
|
| 302 |
+
self.embed_dim = config.n_embd
|
| 303 |
+
self.intermediate_size = intermediate_size
|
| 304 |
+
|
| 305 |
+
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
|
| 306 |
+
hidden_states = self.fc_in(hidden_states)
|
| 307 |
+
hidden_states = self.act(hidden_states)
|
| 308 |
+
hidden_states = self.fc_out(hidden_states)
|
| 309 |
+
hidden_states = self.dropout(hidden_states)
|
| 310 |
+
return hidden_states
|
| 311 |
+
|
| 312 |
+
def build(self, input_shape=None):
|
| 313 |
+
if self.built:
|
| 314 |
+
return
|
| 315 |
+
self.built = True
|
| 316 |
+
if getattr(self, "fc_in", None) is not None:
|
| 317 |
+
with tf.name_scope(self.fc_in.name):
|
| 318 |
+
self.fc_in.build([None, None, self.embed_dim])
|
| 319 |
+
if getattr(self, "fc_out", None) is not None:
|
| 320 |
+
with tf.name_scope(self.fc_out.name):
|
| 321 |
+
self.fc_out.build([None, None, self.intermediate_size])
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class TFGPTJBlock(tf.keras.layers.Layer):
|
| 325 |
+
def __init__(self, config: GPTJConfig, **kwargs):
|
| 326 |
+
super().__init__(**kwargs)
|
| 327 |
+
inner_dim = config.n_inner if config.n_inner is not None else 4 * config.n_embd
|
| 328 |
+
self.ln_1 = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_epsilon, name="ln_1")
|
| 329 |
+
self.attn = TFGPTJAttention(config, name="attn")
|
| 330 |
+
self.mlp = TFGPTJMLP(inner_dim, config, name="mlp")
|
| 331 |
+
self.config = config
|
| 332 |
+
|
| 333 |
+
def call(
|
| 334 |
+
self,
|
| 335 |
+
hidden_states: tf.Tensor,
|
| 336 |
+
layer_past: tf.Tensor | None = None,
|
| 337 |
+
attention_mask: tf.Tensor | None = None,
|
| 338 |
+
position_ids: tf.Tensor | None = None,
|
| 339 |
+
head_mask: tf.Tensor | None = None,
|
| 340 |
+
use_cache: bool = False,
|
| 341 |
+
output_attentions: bool = False,
|
| 342 |
+
):
|
| 343 |
+
residual = hidden_states
|
| 344 |
+
hidden_states = self.ln_1(hidden_states)
|
| 345 |
+
attn_outputs = self.attn(
|
| 346 |
+
hidden_states=hidden_states,
|
| 347 |
+
layer_past=layer_past,
|
| 348 |
+
attention_mask=attention_mask,
|
| 349 |
+
position_ids=position_ids,
|
| 350 |
+
head_mask=head_mask,
|
| 351 |
+
use_cache=use_cache,
|
| 352 |
+
output_attentions=output_attentions,
|
| 353 |
+
) # attn_outputs: attn_output, present, (attentions)
|
| 354 |
+
attn_output = attn_outputs[0]
|
| 355 |
+
outputs = attn_outputs[1:]
|
| 356 |
+
|
| 357 |
+
feed_forward_hidden_states = self.mlp(hidden_states)
|
| 358 |
+
hidden_states = attn_output + feed_forward_hidden_states + residual
|
| 359 |
+
|
| 360 |
+
if use_cache:
|
| 361 |
+
outputs = (hidden_states,) + outputs
|
| 362 |
+
else:
|
| 363 |
+
outputs = (hidden_states,) + outputs[1:]
|
| 364 |
+
return outputs # hidden_states, present, (attentions)
|
| 365 |
+
|
| 366 |
+
def build(self, input_shape=None):
|
| 367 |
+
if self.built:
|
| 368 |
+
return
|
| 369 |
+
self.built = True
|
| 370 |
+
if getattr(self, "ln_1", None) is not None:
|
| 371 |
+
with tf.name_scope(self.ln_1.name):
|
| 372 |
+
self.ln_1.build([None, None, self.config.n_embd])
|
| 373 |
+
if getattr(self, "attn", None) is not None:
|
| 374 |
+
with tf.name_scope(self.attn.name):
|
| 375 |
+
self.attn.build(None)
|
| 376 |
+
if getattr(self, "mlp", None) is not None:
|
| 377 |
+
with tf.name_scope(self.mlp.name):
|
| 378 |
+
self.mlp.build(None)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@keras_serializable
|
| 382 |
+
class TFGPTJMainLayer(tf.keras.layers.Layer):
|
| 383 |
+
config_class = GPTJConfig
|
| 384 |
+
|
| 385 |
+
def __init__(self, config: GPTJConfig, *inputs, **kwargs):
|
| 386 |
+
super().__init__(*inputs, **kwargs)
|
| 387 |
+
|
| 388 |
+
self.config = config
|
| 389 |
+
self.output_attentions = config.output_attentions
|
| 390 |
+
self.output_hidden_states = config.output_hidden_states
|
| 391 |
+
self.use_cache = config.use_cache
|
| 392 |
+
self.return_dict = config.use_return_dict
|
| 393 |
+
|
| 394 |
+
self.num_hidden_layers = config.n_layer
|
| 395 |
+
self.n_embd = config.n_embd
|
| 396 |
+
self.n_positions = config.n_positions
|
| 397 |
+
self.initializer_range = config.initializer_range
|
| 398 |
+
|
| 399 |
+
self.wte = TFSharedEmbeddings(
|
| 400 |
+
config.vocab_size, config.hidden_size, initializer_range=config.initializer_range, name="wte"
|
| 401 |
+
)
|
| 402 |
+
self.drop = tf.keras.layers.Dropout(config.embd_pdrop)
|
| 403 |
+
self.h = [TFGPTJBlock(config, name=f"h_._{i}") for i in range(config.n_layer)]
|
| 404 |
+
self.ln_f = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_epsilon, name="ln_f")
|
| 405 |
+
self.embed_dim = config.n_embd
|
| 406 |
+
|
| 407 |
+
def get_input_embeddings(self):
|
| 408 |
+
return self.wte
|
| 409 |
+
|
| 410 |
+
def set_input_embeddings(self, value: tf.Tensor):
|
| 411 |
+
self.wte.weight = value
|
| 412 |
+
self.wte.vocab_size = shape_list(value)[0]
|
| 413 |
+
|
| 414 |
+
def _prune_heads(self, heads_to_prune):
|
| 415 |
+
"""
|
| 416 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
|
| 417 |
+
"""
|
| 418 |
+
raise NotImplementedError
|
| 419 |
+
|
| 420 |
+
@unpack_inputs
|
| 421 |
+
def call(
|
| 422 |
+
self,
|
| 423 |
+
input_ids=None,
|
| 424 |
+
past_key_values=None,
|
| 425 |
+
attention_mask=None,
|
| 426 |
+
token_type_ids=None,
|
| 427 |
+
position_ids=None,
|
| 428 |
+
head_mask=None,
|
| 429 |
+
inputs_embeds=None,
|
| 430 |
+
use_cache=None,
|
| 431 |
+
output_attentions=None,
|
| 432 |
+
output_hidden_states=None,
|
| 433 |
+
return_dict=None,
|
| 434 |
+
training=False,
|
| 435 |
+
) -> Union[TFBaseModelOutputWithPast, Tuple[tf.Tensor]]:
|
| 436 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 437 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 438 |
+
elif input_ids is not None:
|
| 439 |
+
input_shape = shape_list(input_ids)
|
| 440 |
+
input_ids = tf.reshape(input_ids, [-1, input_shape[-1]])
|
| 441 |
+
elif inputs_embeds is not None:
|
| 442 |
+
input_shape = shape_list(inputs_embeds)[:-1]
|
| 443 |
+
else:
|
| 444 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 445 |
+
|
| 446 |
+
if past_key_values is None:
|
| 447 |
+
past_length = 0
|
| 448 |
+
past_key_values = [None] * len(self.h)
|
| 449 |
+
else:
|
| 450 |
+
past_length = shape_list(past_key_values[0][0])[-2]
|
| 451 |
+
|
| 452 |
+
if position_ids is None:
|
| 453 |
+
position_ids = tf.expand_dims(tf.range(past_length, input_shape[-1] + past_length), axis=0)
|
| 454 |
+
|
| 455 |
+
if attention_mask is not None:
|
| 456 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 457 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 458 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 459 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 460 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 461 |
+
attention_mask_shape = shape_list(attention_mask)
|
| 462 |
+
attention_mask = tf.reshape(attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1]))
|
| 463 |
+
|
| 464 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 465 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 466 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 467 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 468 |
+
# effectively the same as removing these entirely.
|
| 469 |
+
one_cst = tf.constant(1.0)
|
| 470 |
+
attention_mask = tf.cast(attention_mask, dtype=one_cst.dtype)
|
| 471 |
+
attention_mask = tf.multiply(tf.subtract(one_cst, attention_mask), tf.constant(-10000.0))
|
| 472 |
+
|
| 473 |
+
# Prepare head mask if needed
|
| 474 |
+
# 1.0 in head_mask indicate we keep the head
|
| 475 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 476 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 477 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 478 |
+
if head_mask is not None:
|
| 479 |
+
raise NotImplementedError
|
| 480 |
+
else:
|
| 481 |
+
head_mask = [None] * self.num_hidden_layers
|
| 482 |
+
# head_mask = tf.constant([0] * self.num_hidden_layers)
|
| 483 |
+
|
| 484 |
+
position_ids = tf.reshape(position_ids, [-1, shape_list(position_ids)[-1]])
|
| 485 |
+
|
| 486 |
+
if inputs_embeds is None:
|
| 487 |
+
check_embeddings_within_bounds(input_ids, self.wte.vocab_size)
|
| 488 |
+
inputs_embeds = self.wte(input_ids, mode="embedding")
|
| 489 |
+
|
| 490 |
+
if token_type_ids is not None:
|
| 491 |
+
token_type_ids = tf.reshape(token_type_ids, [-1, shape_list(token_type_ids)[-1]])
|
| 492 |
+
token_type_embeds = self.wte(token_type_ids, mode="embedding")
|
| 493 |
+
else:
|
| 494 |
+
token_type_embeds = tf.constant(0.0)
|
| 495 |
+
|
| 496 |
+
token_type_embeds = tf.cast(token_type_embeds, dtype=inputs_embeds.dtype)
|
| 497 |
+
hidden_states = inputs_embeds + token_type_embeds
|
| 498 |
+
hidden_states = self.drop(hidden_states, training=training)
|
| 499 |
+
|
| 500 |
+
output_shape = input_shape + [shape_list(hidden_states)[-1]]
|
| 501 |
+
|
| 502 |
+
presents = () if use_cache else None
|
| 503 |
+
all_attentions = () if output_attentions else None
|
| 504 |
+
all_hidden_states = () if output_hidden_states else None
|
| 505 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
| 506 |
+
if output_hidden_states:
|
| 507 |
+
all_hidden_states = all_hidden_states + (tf.reshape(hidden_states, output_shape),)
|
| 508 |
+
|
| 509 |
+
outputs = block(
|
| 510 |
+
hidden_states=hidden_states,
|
| 511 |
+
layer_past=layer_past,
|
| 512 |
+
attention_mask=attention_mask,
|
| 513 |
+
position_ids=position_ids,
|
| 514 |
+
head_mask=head_mask[i],
|
| 515 |
+
use_cache=use_cache,
|
| 516 |
+
output_attentions=output_attentions,
|
| 517 |
+
training=training,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
hidden_states = outputs[0]
|
| 521 |
+
if use_cache:
|
| 522 |
+
presents = presents + (outputs[1],)
|
| 523 |
+
|
| 524 |
+
if output_attentions:
|
| 525 |
+
all_attentions = all_attentions + (outputs[2 if use_cache else 1],)
|
| 526 |
+
|
| 527 |
+
hidden_states = self.ln_f(hidden_states)
|
| 528 |
+
|
| 529 |
+
hidden_states = tf.reshape(hidden_states, output_shape)
|
| 530 |
+
# Add last hidden state
|
| 531 |
+
if output_hidden_states:
|
| 532 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 533 |
+
|
| 534 |
+
if output_attentions:
|
| 535 |
+
# let the number of heads free (-1) so we can extract attention even after head pruning
|
| 536 |
+
attention_output_shape = input_shape[:-1] + [-1] + shape_list(all_attentions[0])[-2:]
|
| 537 |
+
all_attentions = tuple(tf.reshape(t, attention_output_shape) for t in all_attentions)
|
| 538 |
+
|
| 539 |
+
if not return_dict:
|
| 540 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
|
| 541 |
+
|
| 542 |
+
return TFBaseModelOutputWithPast(
|
| 543 |
+
last_hidden_state=hidden_states,
|
| 544 |
+
past_key_values=presents,
|
| 545 |
+
hidden_states=all_hidden_states,
|
| 546 |
+
attentions=all_attentions,
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
def build(self, input_shape=None):
|
| 550 |
+
if self.built:
|
| 551 |
+
return
|
| 552 |
+
self.built = True
|
| 553 |
+
if getattr(self, "wte", None) is not None:
|
| 554 |
+
with tf.name_scope(self.wte.name):
|
| 555 |
+
self.wte.build(None)
|
| 556 |
+
if getattr(self, "ln_f", None) is not None:
|
| 557 |
+
with tf.name_scope(self.ln_f.name):
|
| 558 |
+
self.ln_f.build([None, None, self.embed_dim])
|
| 559 |
+
if getattr(self, "h", None) is not None:
|
| 560 |
+
for layer in self.h:
|
| 561 |
+
with tf.name_scope(layer.name):
|
| 562 |
+
layer.build(None)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
class TFGPTJPreTrainedModel(TFPreTrainedModel):
|
| 566 |
+
"""
|
| 567 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 568 |
+
models.
|
| 569 |
+
"""
|
| 570 |
+
|
| 571 |
+
config_class = GPTJConfig
|
| 572 |
+
base_model_prefix = "transformer"
|
| 573 |
+
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
|
| 574 |
+
_keys_to_ignore_on_load_unexpected = [r"h.\d+.attn.bias"]
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
GPTJ_START_DOCSTRING = r"""
|
| 578 |
+
|
| 579 |
+
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 580 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 581 |
+
etc.)
|
| 582 |
+
|
| 583 |
+
This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
|
| 584 |
+
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
|
| 585 |
+
behavior.
|
| 586 |
+
|
| 587 |
+
<Tip>
|
| 588 |
+
|
| 589 |
+
TensorFlow models and layers in `transformers` accept two formats as input:
|
| 590 |
+
|
| 591 |
+
- having all inputs as keyword arguments (like PyTorch models), or
|
| 592 |
+
- having all inputs as a list, tuple or dict in the first positional argument.
|
| 593 |
+
|
| 594 |
+
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
|
| 595 |
+
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
|
| 596 |
+
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
|
| 597 |
+
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
|
| 598 |
+
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
|
| 599 |
+
positional argument:
|
| 600 |
+
|
| 601 |
+
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
|
| 602 |
+
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
|
| 603 |
+
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
|
| 604 |
+
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
|
| 605 |
+
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
|
| 606 |
+
|
| 607 |
+
Note that when creating models and layers with
|
| 608 |
+
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
|
| 609 |
+
about any of this, as you can just pass inputs like you would to any other Python function!
|
| 610 |
+
|
| 611 |
+
</Tip>
|
| 612 |
+
|
| 613 |
+
Parameters:
|
| 614 |
+
config ([`GPTJConfig`]): Model configuration class with all the parameters of the model.
|
| 615 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 616 |
+
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
|
| 617 |
+
"""
|
| 618 |
+
|
| 619 |
+
GPTJ_INPUTS_DOCSTRING = r"""
|
| 620 |
+
Args:
|
| 621 |
+
input_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, input_ids_length)`):
|
| 622 |
+
`input_ids_length` = `sequence_length` if `past` is `None` else `past[0].shape[-2]` (`sequence_length` of
|
| 623 |
+
input past key value states). Indices of input sequence tokens in the vocabulary.
|
| 624 |
+
|
| 625 |
+
If `past` is used, only input IDs that do not have their past calculated should be passed as `input_ids`.
|
| 626 |
+
|
| 627 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
|
| 628 |
+
[`PreTrainedTokenizer.encode`] for details.
|
| 629 |
+
|
| 630 |
+
[What are input IDs?](../glossary#input-ids)
|
| 631 |
+
past_key_values (`List[tf.Tensor]` of length `config.n_layers`):
|
| 632 |
+
Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
|
| 633 |
+
`past` output below). Can be used to speed up sequential decoding. The token ids which have their past
|
| 634 |
+
given to this model should not be passed as input ids as they have already been computed.
|
| 635 |
+
attention_mask (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
|
| 636 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 637 |
+
|
| 638 |
+
- 1 for tokens that are **not masked**,
|
| 639 |
+
- 0 for tokens that are **masked**.
|
| 640 |
+
|
| 641 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 642 |
+
token_type_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
|
| 643 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
| 644 |
+
1]`:
|
| 645 |
+
|
| 646 |
+
- 0 corresponds to a *sentence A* token,
|
| 647 |
+
- 1 corresponds to a *sentence B* token.
|
| 648 |
+
|
| 649 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
| 650 |
+
position_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
|
| 651 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 652 |
+
config.max_position_embeddings - 1]`.
|
| 653 |
+
|
| 654 |
+
[What are position IDs?](../glossary#position-ids)
|
| 655 |
+
head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 656 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 657 |
+
|
| 658 |
+
- 1 indicates the head is **not masked**,
|
| 659 |
+
- 0 indicates the head is **masked**.
|
| 660 |
+
|
| 661 |
+
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 662 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 663 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 664 |
+
model's internal embedding lookup matrix.
|
| 665 |
+
output_attentions (`bool`, *optional*):
|
| 666 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 667 |
+
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
|
| 668 |
+
config will be used instead.
|
| 669 |
+
output_hidden_states (`bool`, *optional*):
|
| 670 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 671 |
+
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
|
| 672 |
+
used instead.
|
| 673 |
+
return_dict (`bool`, *optional*):
|
| 674 |
+
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. This argument can be used
|
| 675 |
+
in eager mode, in graph mode the value will always be set to True.
|
| 676 |
+
training (`bool`, *optional*, defaults to `False`):
|
| 677 |
+
Whether or not to use the model in training mode (some modules like dropout modules have different
|
| 678 |
+
behaviors between training and evaluation).
|
| 679 |
+
"""
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
@add_start_docstrings(
|
| 683 |
+
"The bare GPT-J Model transformer outputting raw hidden-states without any specific head on top.",
|
| 684 |
+
GPTJ_START_DOCSTRING,
|
| 685 |
+
)
|
| 686 |
+
class TFGPTJModel(TFGPTJPreTrainedModel):
|
| 687 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 688 |
+
super().__init__(config, *inputs, **kwargs)
|
| 689 |
+
self.transformer = TFGPTJMainLayer(config, name="transformer")
|
| 690 |
+
|
| 691 |
+
@unpack_inputs
|
| 692 |
+
@add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING)
|
| 693 |
+
@add_code_sample_docstrings(
|
| 694 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 695 |
+
output_type=TFBaseModelOutputWithPast,
|
| 696 |
+
config_class=_CONFIG_FOR_DOC,
|
| 697 |
+
)
|
| 698 |
+
def call(
|
| 699 |
+
self,
|
| 700 |
+
input_ids: TFModelInputType | None = None,
|
| 701 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 702 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 703 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 704 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 705 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 706 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 707 |
+
use_cache: Optional[bool] = None,
|
| 708 |
+
output_attentions: Optional[bool] = None,
|
| 709 |
+
output_hidden_states: Optional[bool] = None,
|
| 710 |
+
return_dict: Optional[bool] = None,
|
| 711 |
+
training: Optional[bool] = False,
|
| 712 |
+
) -> Union[TFBaseModelOutputWithPast, Tuple[tf.Tensor]]:
|
| 713 |
+
r"""
|
| 714 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 715 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 716 |
+
`past`). Set to `False` during training, `True` during generation
|
| 717 |
+
"""
|
| 718 |
+
|
| 719 |
+
outputs = self.transformer(
|
| 720 |
+
input_ids=input_ids,
|
| 721 |
+
past_key_values=past_key_values,
|
| 722 |
+
attention_mask=attention_mask,
|
| 723 |
+
token_type_ids=token_type_ids,
|
| 724 |
+
position_ids=position_ids,
|
| 725 |
+
head_mask=head_mask,
|
| 726 |
+
inputs_embeds=inputs_embeds,
|
| 727 |
+
use_cache=use_cache,
|
| 728 |
+
output_attentions=output_attentions,
|
| 729 |
+
output_hidden_states=output_hidden_states,
|
| 730 |
+
return_dict=return_dict,
|
| 731 |
+
training=training,
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
return outputs
|
| 735 |
+
|
| 736 |
+
def build(self, input_shape=None):
|
| 737 |
+
if self.built:
|
| 738 |
+
return
|
| 739 |
+
self.built = True
|
| 740 |
+
if getattr(self, "transformer", None) is not None:
|
| 741 |
+
with tf.name_scope(self.transformer.name):
|
| 742 |
+
self.transformer.build(None)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
@add_start_docstrings(
|
| 746 |
+
"""
|
| 747 |
+
The GPT-J Model transformer with a language modeling head on top.
|
| 748 |
+
""",
|
| 749 |
+
GPTJ_START_DOCSTRING,
|
| 750 |
+
)
|
| 751 |
+
class TFGPTJForCausalLM(TFGPTJPreTrainedModel, TFCausalLanguageModelingLoss):
|
| 752 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 753 |
+
super().__init__(config, *inputs, **kwargs)
|
| 754 |
+
self.transformer = TFGPTJMainLayer(config, name="transformer")
|
| 755 |
+
self.lm_head = tf.keras.layers.Dense(
|
| 756 |
+
config.vocab_size, kernel_initializer=get_initializer(config.initializer_range), name="lm_head"
|
| 757 |
+
)
|
| 758 |
+
self.config = config
|
| 759 |
+
|
| 760 |
+
def get_output_embeddings(self):
|
| 761 |
+
return self.lm_head
|
| 762 |
+
|
| 763 |
+
def set_output_embeddings(self, new_embeddings):
|
| 764 |
+
self.lm_head = new_embeddings
|
| 765 |
+
|
| 766 |
+
def prepare_inputs_for_generation(self, inputs, past_key_values=None, use_cache=None, **kwargs):
|
| 767 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
| 768 |
+
# only last token for inputs_ids if past is defined in kwargs
|
| 769 |
+
if past_key_values:
|
| 770 |
+
inputs = tf.expand_dims(inputs[:, -1], -1)
|
| 771 |
+
if token_type_ids is not None:
|
| 772 |
+
token_type_ids = tf.expand_dims(token_type_ids[:, -1], -1)
|
| 773 |
+
|
| 774 |
+
position_ids = kwargs.get("position_ids", None)
|
| 775 |
+
attention_mask = kwargs.get("attention_mask", None)
|
| 776 |
+
|
| 777 |
+
if attention_mask is not None and position_ids is None:
|
| 778 |
+
position_ids = tf.math.cumsum(attention_mask, axis=-1, exclusive=True)
|
| 779 |
+
if past_key_values:
|
| 780 |
+
position_ids = tf.expand_dims(position_ids[:, -1], -1)
|
| 781 |
+
|
| 782 |
+
return {
|
| 783 |
+
"input_ids": inputs,
|
| 784 |
+
"attention_mask": attention_mask,
|
| 785 |
+
"position_ids": position_ids,
|
| 786 |
+
"past_key_values": past_key_values,
|
| 787 |
+
"use_cache": use_cache,
|
| 788 |
+
"token_type_ids": token_type_ids,
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
@unpack_inputs
|
| 792 |
+
@add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 793 |
+
@add_code_sample_docstrings(
|
| 794 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 795 |
+
output_type=TFCausalLMOutputWithPast,
|
| 796 |
+
config_class=_CONFIG_FOR_DOC,
|
| 797 |
+
)
|
| 798 |
+
def call(
|
| 799 |
+
self,
|
| 800 |
+
input_ids: TFModelInputType | None = None,
|
| 801 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 802 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 803 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 804 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 805 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 806 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 807 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 808 |
+
use_cache: Optional[bool] = None,
|
| 809 |
+
output_attentions: Optional[bool] = None,
|
| 810 |
+
output_hidden_states: Optional[bool] = None,
|
| 811 |
+
return_dict: Optional[bool] = None,
|
| 812 |
+
training: Optional[bool] = False,
|
| 813 |
+
) -> Union[TFCausalLMOutputWithPast, Tuple[tf.Tensor]]:
|
| 814 |
+
r"""
|
| 815 |
+
labels (`np.ndarray` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 816 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 817 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 818 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 819 |
+
"""
|
| 820 |
+
|
| 821 |
+
transformer_outputs = self.transformer(
|
| 822 |
+
input_ids=input_ids,
|
| 823 |
+
past_key_values=past_key_values,
|
| 824 |
+
attention_mask=attention_mask,
|
| 825 |
+
token_type_ids=token_type_ids,
|
| 826 |
+
position_ids=position_ids,
|
| 827 |
+
head_mask=head_mask,
|
| 828 |
+
inputs_embeds=inputs_embeds,
|
| 829 |
+
use_cache=use_cache,
|
| 830 |
+
output_attentions=output_attentions,
|
| 831 |
+
output_hidden_states=output_hidden_states,
|
| 832 |
+
return_dict=return_dict,
|
| 833 |
+
training=training,
|
| 834 |
+
)
|
| 835 |
+
hidden_states = transformer_outputs[0]
|
| 836 |
+
lm_logits = self.lm_head(hidden_states)
|
| 837 |
+
|
| 838 |
+
loss = None
|
| 839 |
+
if labels is not None:
|
| 840 |
+
# shift labels to the left and cut last logit token
|
| 841 |
+
shifted_logits = lm_logits[:, :-1]
|
| 842 |
+
labels = labels[:, 1:]
|
| 843 |
+
loss = self.hf_compute_loss(labels, shifted_logits)
|
| 844 |
+
|
| 845 |
+
if not return_dict:
|
| 846 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
| 847 |
+
return ((loss,) + output) if loss is not None else output
|
| 848 |
+
|
| 849 |
+
return TFCausalLMOutputWithPast(
|
| 850 |
+
loss=loss,
|
| 851 |
+
logits=lm_logits,
|
| 852 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 853 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 854 |
+
attentions=transformer_outputs.attentions,
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
def build(self, input_shape=None):
|
| 858 |
+
if self.built:
|
| 859 |
+
return
|
| 860 |
+
self.built = True
|
| 861 |
+
if getattr(self, "transformer", None) is not None:
|
| 862 |
+
with tf.name_scope(self.transformer.name):
|
| 863 |
+
self.transformer.build(None)
|
| 864 |
+
if getattr(self, "lm_head", None) is not None:
|
| 865 |
+
with tf.name_scope(self.lm_head.name):
|
| 866 |
+
self.lm_head.build([None, None, self.config.n_embd])
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
@add_start_docstrings(
|
| 870 |
+
"""
|
| 871 |
+
The GPT-J Model transformer with a sequence classification head on top (linear layer).
|
| 872 |
+
|
| 873 |
+
[`GPTJForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
| 874 |
+
(e.g. GPT, GPT-2, GPT-Neo) do.
|
| 875 |
+
|
| 876 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
| 877 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
| 878 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
| 879 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
| 880 |
+
each row of the batch).
|
| 881 |
+
""",
|
| 882 |
+
GPTJ_START_DOCSTRING,
|
| 883 |
+
)
|
| 884 |
+
class TFGPTJForSequenceClassification(TFGPTJPreTrainedModel, TFSequenceClassificationLoss):
|
| 885 |
+
_keys_to_ignore_on_load_missing = [r"h.\d+.attn.masked_bias", r"h.\d+.attn.bias", r"lm_head.weight"]
|
| 886 |
+
|
| 887 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 888 |
+
super().__init__(config, *inputs, **kwargs)
|
| 889 |
+
self.num_labels = config.num_labels
|
| 890 |
+
self.transformer = TFGPTJMainLayer(config, name="transformer")
|
| 891 |
+
self.score = tf.keras.layers.Dense(
|
| 892 |
+
self.num_labels,
|
| 893 |
+
use_bias=False,
|
| 894 |
+
kernel_initializer=get_initializer(config.initializer_range),
|
| 895 |
+
name="score",
|
| 896 |
+
)
|
| 897 |
+
self.config = config
|
| 898 |
+
|
| 899 |
+
@unpack_inputs
|
| 900 |
+
@add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 901 |
+
@add_code_sample_docstrings(
|
| 902 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 903 |
+
output_type=TFSequenceClassifierOutputWithPast,
|
| 904 |
+
config_class=_CONFIG_FOR_DOC,
|
| 905 |
+
)
|
| 906 |
+
def call(
|
| 907 |
+
self,
|
| 908 |
+
input_ids: TFModelInputType | None = None,
|
| 909 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 910 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 911 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 912 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 913 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 914 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 915 |
+
labels: np.ndarray | tf.Tensor | None = None,
|
| 916 |
+
use_cache: Optional[bool] = None,
|
| 917 |
+
output_attentions: Optional[bool] = None,
|
| 918 |
+
output_hidden_states: Optional[bool] = None,
|
| 919 |
+
return_dict: Optional[bool] = None,
|
| 920 |
+
training: Optional[bool] = False,
|
| 921 |
+
) -> Union[TFSequenceClassifierOutputWithPast, Tuple[tf.Tensor]]:
|
| 922 |
+
r"""
|
| 923 |
+
labels (`np.ndarray` or `tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 924 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 925 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 926 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 927 |
+
"""
|
| 928 |
+
|
| 929 |
+
transformer_outputs = self.transformer(
|
| 930 |
+
input_ids=input_ids,
|
| 931 |
+
past_key_values=past_key_values,
|
| 932 |
+
attention_mask=attention_mask,
|
| 933 |
+
token_type_ids=token_type_ids,
|
| 934 |
+
position_ids=position_ids,
|
| 935 |
+
head_mask=head_mask,
|
| 936 |
+
inputs_embeds=inputs_embeds,
|
| 937 |
+
use_cache=use_cache,
|
| 938 |
+
output_attentions=output_attentions,
|
| 939 |
+
output_hidden_states=output_hidden_states,
|
| 940 |
+
return_dict=return_dict,
|
| 941 |
+
training=training,
|
| 942 |
+
)
|
| 943 |
+
hidden_states = transformer_outputs[0]
|
| 944 |
+
logits = self.score(hidden_states)
|
| 945 |
+
logits_shape = shape_list(logits)
|
| 946 |
+
in_logits = None
|
| 947 |
+
if self.config.pad_token_id is None:
|
| 948 |
+
sequence_lengths = -1
|
| 949 |
+
else:
|
| 950 |
+
if input_ids is not None:
|
| 951 |
+
sequence_lengths = (
|
| 952 |
+
tf.argmax(tf.cast(tf.math.equal(input_ids, self.config.pad_token_id), input_ids.dtype), axis=-1)
|
| 953 |
+
- 1
|
| 954 |
+
)
|
| 955 |
+
sequence_lengths = tf.where(
|
| 956 |
+
sequence_lengths >= 0,
|
| 957 |
+
sequence_lengths,
|
| 958 |
+
tf.cast(shape_list(input_ids[-1]), sequence_lengths.dtype) - 1,
|
| 959 |
+
)
|
| 960 |
+
in_logits = tf.gather(logits, sequence_lengths, batch_dims=1, axis=1)
|
| 961 |
+
else:
|
| 962 |
+
sequence_lengths = -1
|
| 963 |
+
logger.warning(
|
| 964 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
| 965 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
| 966 |
+
)
|
| 967 |
+
loss = None
|
| 968 |
+
|
| 969 |
+
if labels is not None:
|
| 970 |
+
if self.config.pad_token_id is None and logits_shape[0] != 1:
|
| 971 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 972 |
+
|
| 973 |
+
if not tf.is_tensor(sequence_lengths):
|
| 974 |
+
in_logits = logits[0 : logits_shape[0], sequence_lengths]
|
| 975 |
+
|
| 976 |
+
loss = self.hf_compute_loss(tf.reshape(labels, [-1]), tf.reshape(in_logits, [-1, self.num_labels]))
|
| 977 |
+
pooled_logits = in_logits if in_logits is not None else logits
|
| 978 |
+
|
| 979 |
+
if not return_dict:
|
| 980 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 981 |
+
return ((loss,) + output) if loss is not None else output
|
| 982 |
+
|
| 983 |
+
return TFSequenceClassifierOutputWithPast(
|
| 984 |
+
loss=loss,
|
| 985 |
+
logits=pooled_logits,
|
| 986 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 987 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 988 |
+
attentions=transformer_outputs.attentions,
|
| 989 |
+
)
|
| 990 |
+
|
| 991 |
+
def build(self, input_shape=None):
|
| 992 |
+
if self.built:
|
| 993 |
+
return
|
| 994 |
+
self.built = True
|
| 995 |
+
if getattr(self, "transformer", None) is not None:
|
| 996 |
+
with tf.name_scope(self.transformer.name):
|
| 997 |
+
self.transformer.build(None)
|
| 998 |
+
if getattr(self, "score", None) is not None:
|
| 999 |
+
with tf.name_scope(self.score.name):
|
| 1000 |
+
self.score.build([None, None, self.config.n_embd])
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
@add_start_docstrings(
|
| 1004 |
+
"""
|
| 1005 |
+
The GPT-J Model transformer with a span classification head on top for extractive question-answering tasks like
|
| 1006 |
+
SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
| 1007 |
+
""",
|
| 1008 |
+
GPTJ_START_DOCSTRING,
|
| 1009 |
+
)
|
| 1010 |
+
class TFGPTJForQuestionAnswering(TFGPTJPreTrainedModel, TFQuestionAnsweringLoss):
|
| 1011 |
+
_keys_to_ignore_on_load_missing = [r"h.\d+.attn.masked_bias", r"h.\d+.attn.bias", r"lm_head.weight"]
|
| 1012 |
+
|
| 1013 |
+
def __init__(self, config, *inputs, **kwargs):
|
| 1014 |
+
super().__init__(config, *inputs, **kwargs)
|
| 1015 |
+
self.num_labels = config.num_labels
|
| 1016 |
+
self.transformer = TFGPTJMainLayer(config, name="transformer")
|
| 1017 |
+
self.qa_outputs = tf.keras.layers.Dense(
|
| 1018 |
+
self.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
|
| 1019 |
+
)
|
| 1020 |
+
self.config = config
|
| 1021 |
+
|
| 1022 |
+
@unpack_inputs
|
| 1023 |
+
@add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
| 1024 |
+
@add_code_sample_docstrings(
|
| 1025 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1026 |
+
output_type=TFQuestionAnsweringModelOutput,
|
| 1027 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1028 |
+
)
|
| 1029 |
+
def call(
|
| 1030 |
+
self,
|
| 1031 |
+
input_ids: TFModelInputType | None = None,
|
| 1032 |
+
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
|
| 1033 |
+
attention_mask: np.ndarray | tf.Tensor | None = None,
|
| 1034 |
+
token_type_ids: np.ndarray | tf.Tensor | None = None,
|
| 1035 |
+
position_ids: np.ndarray | tf.Tensor | None = None,
|
| 1036 |
+
head_mask: np.ndarray | tf.Tensor | None = None,
|
| 1037 |
+
inputs_embeds: np.ndarray | tf.Tensor | None = None,
|
| 1038 |
+
start_positions: np.ndarray | tf.Tensor | None = None,
|
| 1039 |
+
end_positions: np.ndarray | tf.Tensor | None = None,
|
| 1040 |
+
output_attentions: Optional[bool] = None,
|
| 1041 |
+
output_hidden_states: Optional[bool] = None,
|
| 1042 |
+
return_dict: Optional[bool] = None,
|
| 1043 |
+
training: Optional[bool] = False,
|
| 1044 |
+
) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
|
| 1045 |
+
r"""
|
| 1046 |
+
start_positions (`np.ndarray` or `tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1047 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1048 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1049 |
+
are not taken into account for computing the loss.
|
| 1050 |
+
end_positions (`np.ndarray` or `tf.Tensor` of shape `(batch_size,)`, *optional*):
|
| 1051 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1052 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1053 |
+
are not taken into account for computing the loss.
|
| 1054 |
+
"""
|
| 1055 |
+
|
| 1056 |
+
transformer_outputs = self.transformer(
|
| 1057 |
+
input_ids=input_ids,
|
| 1058 |
+
past_key_values=past_key_values,
|
| 1059 |
+
attention_mask=attention_mask,
|
| 1060 |
+
token_type_ids=token_type_ids,
|
| 1061 |
+
position_ids=position_ids,
|
| 1062 |
+
head_mask=head_mask,
|
| 1063 |
+
inputs_embeds=inputs_embeds,
|
| 1064 |
+
output_attentions=output_attentions,
|
| 1065 |
+
output_hidden_states=output_hidden_states,
|
| 1066 |
+
return_dict=return_dict,
|
| 1067 |
+
training=training,
|
| 1068 |
+
)
|
| 1069 |
+
sequence_output = transformer_outputs[0]
|
| 1070 |
+
|
| 1071 |
+
logits = self.qa_outputs(sequence_output)
|
| 1072 |
+
start_logits, end_logits = tf.split(logits, 2, axis=-1)
|
| 1073 |
+
start_logits = tf.squeeze(start_logits, axis=-1)
|
| 1074 |
+
end_logits = tf.squeeze(end_logits, axis=-1)
|
| 1075 |
+
|
| 1076 |
+
loss = None
|
| 1077 |
+
if start_positions is not None and end_positions is not None:
|
| 1078 |
+
labels = {"start_position": start_positions}
|
| 1079 |
+
labels["end_position"] = end_positions
|
| 1080 |
+
loss = self.hf_compute_loss(labels, (start_logits, end_logits))
|
| 1081 |
+
|
| 1082 |
+
if not return_dict:
|
| 1083 |
+
output = (start_logits, end_logits) + transformer_outputs[2:]
|
| 1084 |
+
return ((loss,) + output) if loss is not None else output
|
| 1085 |
+
|
| 1086 |
+
return TFQuestionAnsweringModelOutput(
|
| 1087 |
+
loss=loss,
|
| 1088 |
+
start_logits=start_logits,
|
| 1089 |
+
end_logits=end_logits,
|
| 1090 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1091 |
+
attentions=transformer_outputs.attentions,
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
def build(self, input_shape=None):
|
| 1095 |
+
if self.built:
|
| 1096 |
+
return
|
| 1097 |
+
self.built = True
|
| 1098 |
+
if getattr(self, "transformer", None) is not None:
|
| 1099 |
+
with tf.name_scope(self.transformer.name):
|
| 1100 |
+
self.transformer.build(None)
|
| 1101 |
+
if getattr(self, "qa_outputs", None) is not None:
|
| 1102 |
+
with tf.name_scope(self.qa_outputs.name):
|
| 1103 |
+
self.qa_outputs.build([None, None, self.config.hidden_size])
|
evalkit_internvl/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bf0565a0e0a8fb02fcc72e9eea70bf885cecbd76847fe95e0bac778cf109e423
|
| 3 |
+
size 102033
|
evalkit_internvl/lib/python3.10/site-packages/transformers/utils/dummy_detectron2_objects.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is autogenerated by the command `make fix-copies`, do not edit.
|
| 2 |
+
from ..utils import requires_backends
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
LAYOUTLM_V2_PRETRAINED_MODEL_ARCHIVE_LIST = None
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class LayoutLMv2Model:
|
| 9 |
+
def __init__(self, *args, **kwargs):
|
| 10 |
+
requires_backends(self, ["detectron2"])
|
| 11 |
+
|
| 12 |
+
@classmethod
|
| 13 |
+
def from_pretrained(cls, *args, **kwargs):
|
| 14 |
+
requires_backends(cls, ["detectron2"])
|
evalkit_internvl/lib/python3.10/site-packages/transformers/utils/model_parallel_utils.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from math import ceil
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def assert_device_map(device_map, num_blocks):
|
| 20 |
+
blocks = list(range(0, num_blocks))
|
| 21 |
+
|
| 22 |
+
device_map_blocks = [item for sublist in list(device_map.values()) for item in sublist]
|
| 23 |
+
|
| 24 |
+
# Duplicate check
|
| 25 |
+
duplicate_blocks = []
|
| 26 |
+
for i in device_map_blocks:
|
| 27 |
+
if device_map_blocks.count(i) > 1 and i not in duplicate_blocks:
|
| 28 |
+
duplicate_blocks.append(i)
|
| 29 |
+
# Missing blocks
|
| 30 |
+
missing_blocks = [i for i in blocks if i not in device_map_blocks]
|
| 31 |
+
extra_blocks = [i for i in device_map_blocks if i not in blocks]
|
| 32 |
+
|
| 33 |
+
if len(duplicate_blocks) != 0:
|
| 34 |
+
raise ValueError(
|
| 35 |
+
"Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
|
| 36 |
+
" These attention blocks were specified more than once: " + str(duplicate_blocks)
|
| 37 |
+
)
|
| 38 |
+
if len(missing_blocks) != 0:
|
| 39 |
+
raise ValueError(
|
| 40 |
+
"There are attention blocks for this model that are not specified in the device_map. Add these attention "
|
| 41 |
+
"blocks to a device on the device_map: " + str(missing_blocks)
|
| 42 |
+
)
|
| 43 |
+
if len(extra_blocks) != 0:
|
| 44 |
+
raise ValueError(
|
| 45 |
+
"The device_map contains more attention blocks than this model has. Remove these from the device_map:"
|
| 46 |
+
+ str(extra_blocks)
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_device_map(n_layers, devices):
|
| 51 |
+
"""Returns a dictionary of layers distributed evenly across all devices."""
|
| 52 |
+
layers = list(range(n_layers))
|
| 53 |
+
n_blocks = int(ceil(n_layers / len(devices)))
|
| 54 |
+
layers_list = [layers[i : i + n_blocks] for i in range(0, n_layers, n_blocks)]
|
| 55 |
+
|
| 56 |
+
return dict(zip(devices, layers_list))
|
evalkit_internvl/lib/python3.10/site-packages/transformers/utils/sentencepiece_model_pb2.py
ADDED
|
@@ -0,0 +1,1511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
| 2 |
+
# source: sentencepiece_model.proto
|
| 3 |
+
|
| 4 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 5 |
+
#
|
| 6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 7 |
+
# you may not use this file except in compliance with the License.
|
| 8 |
+
# You may obtain a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 15 |
+
# See the License for the specific language governing permissions and
|
| 16 |
+
# limitations under the License.
|
| 17 |
+
from google.protobuf import descriptor as _descriptor
|
| 18 |
+
from google.protobuf import message as _message
|
| 19 |
+
from google.protobuf import reflection as _reflection
|
| 20 |
+
from google.protobuf import symbol_database as _symbol_database
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# @@protoc_insertion_point(imports)
|
| 24 |
+
|
| 25 |
+
_sym_db = _symbol_database.Default()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
DESCRIPTOR = _descriptor.FileDescriptor(
|
| 29 |
+
name="sentencepiece_model.proto",
|
| 30 |
+
package="sentencepiece",
|
| 31 |
+
syntax="proto2",
|
| 32 |
+
serialized_options=b"H\003",
|
| 33 |
+
create_key=_descriptor._internal_create_key,
|
| 34 |
+
serialized_pb=(
|
| 35 |
+
b'\n\x19sentencepiece_model.proto\x12\rsentencepiece"\xa1\n\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01'
|
| 36 |
+
b" \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02"
|
| 37 |
+
b" \x01(\t\x12\x41\n\nmodel_type\x18\x03"
|
| 38 |
+
b" \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04"
|
| 39 |
+
b" \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12"
|
| 40 |
+
b' \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12"\n\x12\x63haracter_coverage\x18\n'
|
| 41 |
+
b" \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b"
|
| 42 |
+
b" \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12"
|
| 43 |
+
b' \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12"\n\x16training_sentence_size\x18\r'
|
| 44 |
+
b" \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e"
|
| 45 |
+
b" \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f"
|
| 46 |
+
b" \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12"
|
| 47 |
+
b" \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10"
|
| 48 |
+
b" \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11"
|
| 49 |
+
b" \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14"
|
| 50 |
+
b" \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15"
|
| 51 |
+
b" \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17"
|
| 52 |
+
b" \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16"
|
| 53 |
+
b" \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18"
|
| 54 |
+
b" \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19"
|
| 55 |
+
b" \x01(\x08:\x05\x66\x61lse\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e"
|
| 56 |
+
b" \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$"
|
| 57 |
+
b" \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18"
|
| 58 |
+
b' \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18"'
|
| 59 |
+
b" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18)"
|
| 60 |
+
b" \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+"
|
| 61 |
+
b" \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18."
|
| 62 |
+
b" \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30"
|
| 63 |
+
b" \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87"
|
| 64 |
+
b" \x12+\n\x1ctrain_extremely_large_corpus\x18\x31"
|
| 65 |
+
b' \x01(\x08:\x05\x66\x61lse"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01'
|
| 66 |
+
b" \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03"
|
| 67 |
+
b" \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12"
|
| 68 |
+
b" \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06"
|
| 69 |
+
b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01'
|
| 70 |
+
b' \x03(\x0b\x32".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01'
|
| 71 |
+
b" \x01(\t\x12\x10\n\x08\x65xpected\x18\x02"
|
| 72 |
+
b' \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01'
|
| 73 |
+
b" \x03(\x0b\x32'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02"
|
| 74 |
+
b" \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03"
|
| 75 |
+
b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04"
|
| 76 |
+
b" \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05"
|
| 77 |
+
b" \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01"
|
| 78 |
+
b" \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03"
|
| 79 |
+
b' \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03'
|
| 80 |
+
),
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
_TRAINERSPEC_MODELTYPE = _descriptor.EnumDescriptor(
|
| 85 |
+
name="ModelType",
|
| 86 |
+
full_name="sentencepiece.TrainerSpec.ModelType",
|
| 87 |
+
filename=None,
|
| 88 |
+
file=DESCRIPTOR,
|
| 89 |
+
create_key=_descriptor._internal_create_key,
|
| 90 |
+
values=[
|
| 91 |
+
_descriptor.EnumValueDescriptor(
|
| 92 |
+
name="UNIGRAM",
|
| 93 |
+
index=0,
|
| 94 |
+
number=1,
|
| 95 |
+
serialized_options=None,
|
| 96 |
+
type=None,
|
| 97 |
+
create_key=_descriptor._internal_create_key,
|
| 98 |
+
),
|
| 99 |
+
_descriptor.EnumValueDescriptor(
|
| 100 |
+
name="BPE",
|
| 101 |
+
index=1,
|
| 102 |
+
number=2,
|
| 103 |
+
serialized_options=None,
|
| 104 |
+
type=None,
|
| 105 |
+
create_key=_descriptor._internal_create_key,
|
| 106 |
+
),
|
| 107 |
+
_descriptor.EnumValueDescriptor(
|
| 108 |
+
name="WORD",
|
| 109 |
+
index=2,
|
| 110 |
+
number=3,
|
| 111 |
+
serialized_options=None,
|
| 112 |
+
type=None,
|
| 113 |
+
create_key=_descriptor._internal_create_key,
|
| 114 |
+
),
|
| 115 |
+
_descriptor.EnumValueDescriptor(
|
| 116 |
+
name="CHAR",
|
| 117 |
+
index=3,
|
| 118 |
+
number=4,
|
| 119 |
+
serialized_options=None,
|
| 120 |
+
type=None,
|
| 121 |
+
create_key=_descriptor._internal_create_key,
|
| 122 |
+
),
|
| 123 |
+
],
|
| 124 |
+
containing_type=None,
|
| 125 |
+
serialized_options=None,
|
| 126 |
+
serialized_start=1294,
|
| 127 |
+
serialized_end=1347,
|
| 128 |
+
)
|
| 129 |
+
_sym_db.RegisterEnumDescriptor(_TRAINERSPEC_MODELTYPE)
|
| 130 |
+
|
| 131 |
+
_MODELPROTO_SENTENCEPIECE_TYPE = _descriptor.EnumDescriptor(
|
| 132 |
+
name="Type",
|
| 133 |
+
full_name="sentencepiece.ModelProto.SentencePiece.Type",
|
| 134 |
+
filename=None,
|
| 135 |
+
file=DESCRIPTOR,
|
| 136 |
+
create_key=_descriptor._internal_create_key,
|
| 137 |
+
values=[
|
| 138 |
+
_descriptor.EnumValueDescriptor(
|
| 139 |
+
name="NORMAL",
|
| 140 |
+
index=0,
|
| 141 |
+
number=1,
|
| 142 |
+
serialized_options=None,
|
| 143 |
+
type=None,
|
| 144 |
+
create_key=_descriptor._internal_create_key,
|
| 145 |
+
),
|
| 146 |
+
_descriptor.EnumValueDescriptor(
|
| 147 |
+
name="UNKNOWN",
|
| 148 |
+
index=1,
|
| 149 |
+
number=2,
|
| 150 |
+
serialized_options=None,
|
| 151 |
+
type=None,
|
| 152 |
+
create_key=_descriptor._internal_create_key,
|
| 153 |
+
),
|
| 154 |
+
_descriptor.EnumValueDescriptor(
|
| 155 |
+
name="CONTROL",
|
| 156 |
+
index=2,
|
| 157 |
+
number=3,
|
| 158 |
+
serialized_options=None,
|
| 159 |
+
type=None,
|
| 160 |
+
create_key=_descriptor._internal_create_key,
|
| 161 |
+
),
|
| 162 |
+
_descriptor.EnumValueDescriptor(
|
| 163 |
+
name="USER_DEFINED",
|
| 164 |
+
index=3,
|
| 165 |
+
number=4,
|
| 166 |
+
serialized_options=None,
|
| 167 |
+
type=None,
|
| 168 |
+
create_key=_descriptor._internal_create_key,
|
| 169 |
+
),
|
| 170 |
+
_descriptor.EnumValueDescriptor(
|
| 171 |
+
name="BYTE",
|
| 172 |
+
index=4,
|
| 173 |
+
number=6,
|
| 174 |
+
serialized_options=None,
|
| 175 |
+
type=None,
|
| 176 |
+
create_key=_descriptor._internal_create_key,
|
| 177 |
+
),
|
| 178 |
+
_descriptor.EnumValueDescriptor(
|
| 179 |
+
name="UNUSED",
|
| 180 |
+
index=5,
|
| 181 |
+
number=5,
|
| 182 |
+
serialized_options=None,
|
| 183 |
+
type=None,
|
| 184 |
+
create_key=_descriptor._internal_create_key,
|
| 185 |
+
),
|
| 186 |
+
],
|
| 187 |
+
containing_type=None,
|
| 188 |
+
serialized_options=None,
|
| 189 |
+
serialized_start=2100,
|
| 190 |
+
serialized_end=2184,
|
| 191 |
+
)
|
| 192 |
+
_sym_db.RegisterEnumDescriptor(_MODELPROTO_SENTENCEPIECE_TYPE)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
_TRAINERSPEC = _descriptor.Descriptor(
|
| 196 |
+
name="TrainerSpec",
|
| 197 |
+
full_name="sentencepiece.TrainerSpec",
|
| 198 |
+
filename=None,
|
| 199 |
+
file=DESCRIPTOR,
|
| 200 |
+
containing_type=None,
|
| 201 |
+
create_key=_descriptor._internal_create_key,
|
| 202 |
+
fields=[
|
| 203 |
+
_descriptor.FieldDescriptor(
|
| 204 |
+
name="input",
|
| 205 |
+
full_name="sentencepiece.TrainerSpec.input",
|
| 206 |
+
index=0,
|
| 207 |
+
number=1,
|
| 208 |
+
type=9,
|
| 209 |
+
cpp_type=9,
|
| 210 |
+
label=3,
|
| 211 |
+
has_default_value=False,
|
| 212 |
+
default_value=[],
|
| 213 |
+
message_type=None,
|
| 214 |
+
enum_type=None,
|
| 215 |
+
containing_type=None,
|
| 216 |
+
is_extension=False,
|
| 217 |
+
extension_scope=None,
|
| 218 |
+
serialized_options=None,
|
| 219 |
+
file=DESCRIPTOR,
|
| 220 |
+
create_key=_descriptor._internal_create_key,
|
| 221 |
+
),
|
| 222 |
+
_descriptor.FieldDescriptor(
|
| 223 |
+
name="input_format",
|
| 224 |
+
full_name="sentencepiece.TrainerSpec.input_format",
|
| 225 |
+
index=1,
|
| 226 |
+
number=7,
|
| 227 |
+
type=9,
|
| 228 |
+
cpp_type=9,
|
| 229 |
+
label=1,
|
| 230 |
+
has_default_value=False,
|
| 231 |
+
default_value=b"".decode("utf-8"),
|
| 232 |
+
message_type=None,
|
| 233 |
+
enum_type=None,
|
| 234 |
+
containing_type=None,
|
| 235 |
+
is_extension=False,
|
| 236 |
+
extension_scope=None,
|
| 237 |
+
serialized_options=None,
|
| 238 |
+
file=DESCRIPTOR,
|
| 239 |
+
create_key=_descriptor._internal_create_key,
|
| 240 |
+
),
|
| 241 |
+
_descriptor.FieldDescriptor(
|
| 242 |
+
name="model_prefix",
|
| 243 |
+
full_name="sentencepiece.TrainerSpec.model_prefix",
|
| 244 |
+
index=2,
|
| 245 |
+
number=2,
|
| 246 |
+
type=9,
|
| 247 |
+
cpp_type=9,
|
| 248 |
+
label=1,
|
| 249 |
+
has_default_value=False,
|
| 250 |
+
default_value=b"".decode("utf-8"),
|
| 251 |
+
message_type=None,
|
| 252 |
+
enum_type=None,
|
| 253 |
+
containing_type=None,
|
| 254 |
+
is_extension=False,
|
| 255 |
+
extension_scope=None,
|
| 256 |
+
serialized_options=None,
|
| 257 |
+
file=DESCRIPTOR,
|
| 258 |
+
create_key=_descriptor._internal_create_key,
|
| 259 |
+
),
|
| 260 |
+
_descriptor.FieldDescriptor(
|
| 261 |
+
name="model_type",
|
| 262 |
+
full_name="sentencepiece.TrainerSpec.model_type",
|
| 263 |
+
index=3,
|
| 264 |
+
number=3,
|
| 265 |
+
type=14,
|
| 266 |
+
cpp_type=8,
|
| 267 |
+
label=1,
|
| 268 |
+
has_default_value=True,
|
| 269 |
+
default_value=1,
|
| 270 |
+
message_type=None,
|
| 271 |
+
enum_type=None,
|
| 272 |
+
containing_type=None,
|
| 273 |
+
is_extension=False,
|
| 274 |
+
extension_scope=None,
|
| 275 |
+
serialized_options=None,
|
| 276 |
+
file=DESCRIPTOR,
|
| 277 |
+
create_key=_descriptor._internal_create_key,
|
| 278 |
+
),
|
| 279 |
+
_descriptor.FieldDescriptor(
|
| 280 |
+
name="vocab_size",
|
| 281 |
+
full_name="sentencepiece.TrainerSpec.vocab_size",
|
| 282 |
+
index=4,
|
| 283 |
+
number=4,
|
| 284 |
+
type=5,
|
| 285 |
+
cpp_type=1,
|
| 286 |
+
label=1,
|
| 287 |
+
has_default_value=True,
|
| 288 |
+
default_value=8000,
|
| 289 |
+
message_type=None,
|
| 290 |
+
enum_type=None,
|
| 291 |
+
containing_type=None,
|
| 292 |
+
is_extension=False,
|
| 293 |
+
extension_scope=None,
|
| 294 |
+
serialized_options=None,
|
| 295 |
+
file=DESCRIPTOR,
|
| 296 |
+
create_key=_descriptor._internal_create_key,
|
| 297 |
+
),
|
| 298 |
+
_descriptor.FieldDescriptor(
|
| 299 |
+
name="accept_language",
|
| 300 |
+
full_name="sentencepiece.TrainerSpec.accept_language",
|
| 301 |
+
index=5,
|
| 302 |
+
number=5,
|
| 303 |
+
type=9,
|
| 304 |
+
cpp_type=9,
|
| 305 |
+
label=3,
|
| 306 |
+
has_default_value=False,
|
| 307 |
+
default_value=[],
|
| 308 |
+
message_type=None,
|
| 309 |
+
enum_type=None,
|
| 310 |
+
containing_type=None,
|
| 311 |
+
is_extension=False,
|
| 312 |
+
extension_scope=None,
|
| 313 |
+
serialized_options=None,
|
| 314 |
+
file=DESCRIPTOR,
|
| 315 |
+
create_key=_descriptor._internal_create_key,
|
| 316 |
+
),
|
| 317 |
+
_descriptor.FieldDescriptor(
|
| 318 |
+
name="self_test_sample_size",
|
| 319 |
+
full_name="sentencepiece.TrainerSpec.self_test_sample_size",
|
| 320 |
+
index=6,
|
| 321 |
+
number=6,
|
| 322 |
+
type=5,
|
| 323 |
+
cpp_type=1,
|
| 324 |
+
label=1,
|
| 325 |
+
has_default_value=True,
|
| 326 |
+
default_value=0,
|
| 327 |
+
message_type=None,
|
| 328 |
+
enum_type=None,
|
| 329 |
+
containing_type=None,
|
| 330 |
+
is_extension=False,
|
| 331 |
+
extension_scope=None,
|
| 332 |
+
serialized_options=None,
|
| 333 |
+
file=DESCRIPTOR,
|
| 334 |
+
create_key=_descriptor._internal_create_key,
|
| 335 |
+
),
|
| 336 |
+
_descriptor.FieldDescriptor(
|
| 337 |
+
name="character_coverage",
|
| 338 |
+
full_name="sentencepiece.TrainerSpec.character_coverage",
|
| 339 |
+
index=7,
|
| 340 |
+
number=10,
|
| 341 |
+
type=2,
|
| 342 |
+
cpp_type=6,
|
| 343 |
+
label=1,
|
| 344 |
+
has_default_value=True,
|
| 345 |
+
default_value=float(0.9995),
|
| 346 |
+
message_type=None,
|
| 347 |
+
enum_type=None,
|
| 348 |
+
containing_type=None,
|
| 349 |
+
is_extension=False,
|
| 350 |
+
extension_scope=None,
|
| 351 |
+
serialized_options=None,
|
| 352 |
+
file=DESCRIPTOR,
|
| 353 |
+
create_key=_descriptor._internal_create_key,
|
| 354 |
+
),
|
| 355 |
+
_descriptor.FieldDescriptor(
|
| 356 |
+
name="input_sentence_size",
|
| 357 |
+
full_name="sentencepiece.TrainerSpec.input_sentence_size",
|
| 358 |
+
index=8,
|
| 359 |
+
number=11,
|
| 360 |
+
type=4,
|
| 361 |
+
cpp_type=4,
|
| 362 |
+
label=1,
|
| 363 |
+
has_default_value=True,
|
| 364 |
+
default_value=0,
|
| 365 |
+
message_type=None,
|
| 366 |
+
enum_type=None,
|
| 367 |
+
containing_type=None,
|
| 368 |
+
is_extension=False,
|
| 369 |
+
extension_scope=None,
|
| 370 |
+
serialized_options=None,
|
| 371 |
+
file=DESCRIPTOR,
|
| 372 |
+
create_key=_descriptor._internal_create_key,
|
| 373 |
+
),
|
| 374 |
+
_descriptor.FieldDescriptor(
|
| 375 |
+
name="shuffle_input_sentence",
|
| 376 |
+
full_name="sentencepiece.TrainerSpec.shuffle_input_sentence",
|
| 377 |
+
index=9,
|
| 378 |
+
number=19,
|
| 379 |
+
type=8,
|
| 380 |
+
cpp_type=7,
|
| 381 |
+
label=1,
|
| 382 |
+
has_default_value=True,
|
| 383 |
+
default_value=True,
|
| 384 |
+
message_type=None,
|
| 385 |
+
enum_type=None,
|
| 386 |
+
containing_type=None,
|
| 387 |
+
is_extension=False,
|
| 388 |
+
extension_scope=None,
|
| 389 |
+
serialized_options=None,
|
| 390 |
+
file=DESCRIPTOR,
|
| 391 |
+
create_key=_descriptor._internal_create_key,
|
| 392 |
+
),
|
| 393 |
+
_descriptor.FieldDescriptor(
|
| 394 |
+
name="mining_sentence_size",
|
| 395 |
+
full_name="sentencepiece.TrainerSpec.mining_sentence_size",
|
| 396 |
+
index=10,
|
| 397 |
+
number=12,
|
| 398 |
+
type=5,
|
| 399 |
+
cpp_type=1,
|
| 400 |
+
label=1,
|
| 401 |
+
has_default_value=False,
|
| 402 |
+
default_value=0,
|
| 403 |
+
message_type=None,
|
| 404 |
+
enum_type=None,
|
| 405 |
+
containing_type=None,
|
| 406 |
+
is_extension=False,
|
| 407 |
+
extension_scope=None,
|
| 408 |
+
serialized_options=b"\030\001",
|
| 409 |
+
file=DESCRIPTOR,
|
| 410 |
+
create_key=_descriptor._internal_create_key,
|
| 411 |
+
),
|
| 412 |
+
_descriptor.FieldDescriptor(
|
| 413 |
+
name="training_sentence_size",
|
| 414 |
+
full_name="sentencepiece.TrainerSpec.training_sentence_size",
|
| 415 |
+
index=11,
|
| 416 |
+
number=13,
|
| 417 |
+
type=5,
|
| 418 |
+
cpp_type=1,
|
| 419 |
+
label=1,
|
| 420 |
+
has_default_value=False,
|
| 421 |
+
default_value=0,
|
| 422 |
+
message_type=None,
|
| 423 |
+
enum_type=None,
|
| 424 |
+
containing_type=None,
|
| 425 |
+
is_extension=False,
|
| 426 |
+
extension_scope=None,
|
| 427 |
+
serialized_options=b"\030\001",
|
| 428 |
+
file=DESCRIPTOR,
|
| 429 |
+
create_key=_descriptor._internal_create_key,
|
| 430 |
+
),
|
| 431 |
+
_descriptor.FieldDescriptor(
|
| 432 |
+
name="seed_sentencepiece_size",
|
| 433 |
+
full_name="sentencepiece.TrainerSpec.seed_sentencepiece_size",
|
| 434 |
+
index=12,
|
| 435 |
+
number=14,
|
| 436 |
+
type=5,
|
| 437 |
+
cpp_type=1,
|
| 438 |
+
label=1,
|
| 439 |
+
has_default_value=True,
|
| 440 |
+
default_value=1000000,
|
| 441 |
+
message_type=None,
|
| 442 |
+
enum_type=None,
|
| 443 |
+
containing_type=None,
|
| 444 |
+
is_extension=False,
|
| 445 |
+
extension_scope=None,
|
| 446 |
+
serialized_options=None,
|
| 447 |
+
file=DESCRIPTOR,
|
| 448 |
+
create_key=_descriptor._internal_create_key,
|
| 449 |
+
),
|
| 450 |
+
_descriptor.FieldDescriptor(
|
| 451 |
+
name="shrinking_factor",
|
| 452 |
+
full_name="sentencepiece.TrainerSpec.shrinking_factor",
|
| 453 |
+
index=13,
|
| 454 |
+
number=15,
|
| 455 |
+
type=2,
|
| 456 |
+
cpp_type=6,
|
| 457 |
+
label=1,
|
| 458 |
+
has_default_value=True,
|
| 459 |
+
default_value=float(0.75),
|
| 460 |
+
message_type=None,
|
| 461 |
+
enum_type=None,
|
| 462 |
+
containing_type=None,
|
| 463 |
+
is_extension=False,
|
| 464 |
+
extension_scope=None,
|
| 465 |
+
serialized_options=None,
|
| 466 |
+
file=DESCRIPTOR,
|
| 467 |
+
create_key=_descriptor._internal_create_key,
|
| 468 |
+
),
|
| 469 |
+
_descriptor.FieldDescriptor(
|
| 470 |
+
name="max_sentence_length",
|
| 471 |
+
full_name="sentencepiece.TrainerSpec.max_sentence_length",
|
| 472 |
+
index=14,
|
| 473 |
+
number=18,
|
| 474 |
+
type=5,
|
| 475 |
+
cpp_type=1,
|
| 476 |
+
label=1,
|
| 477 |
+
has_default_value=True,
|
| 478 |
+
default_value=4192,
|
| 479 |
+
message_type=None,
|
| 480 |
+
enum_type=None,
|
| 481 |
+
containing_type=None,
|
| 482 |
+
is_extension=False,
|
| 483 |
+
extension_scope=None,
|
| 484 |
+
serialized_options=None,
|
| 485 |
+
file=DESCRIPTOR,
|
| 486 |
+
create_key=_descriptor._internal_create_key,
|
| 487 |
+
),
|
| 488 |
+
_descriptor.FieldDescriptor(
|
| 489 |
+
name="num_threads",
|
| 490 |
+
full_name="sentencepiece.TrainerSpec.num_threads",
|
| 491 |
+
index=15,
|
| 492 |
+
number=16,
|
| 493 |
+
type=5,
|
| 494 |
+
cpp_type=1,
|
| 495 |
+
label=1,
|
| 496 |
+
has_default_value=True,
|
| 497 |
+
default_value=16,
|
| 498 |
+
message_type=None,
|
| 499 |
+
enum_type=None,
|
| 500 |
+
containing_type=None,
|
| 501 |
+
is_extension=False,
|
| 502 |
+
extension_scope=None,
|
| 503 |
+
serialized_options=None,
|
| 504 |
+
file=DESCRIPTOR,
|
| 505 |
+
create_key=_descriptor._internal_create_key,
|
| 506 |
+
),
|
| 507 |
+
_descriptor.FieldDescriptor(
|
| 508 |
+
name="num_sub_iterations",
|
| 509 |
+
full_name="sentencepiece.TrainerSpec.num_sub_iterations",
|
| 510 |
+
index=16,
|
| 511 |
+
number=17,
|
| 512 |
+
type=5,
|
| 513 |
+
cpp_type=1,
|
| 514 |
+
label=1,
|
| 515 |
+
has_default_value=True,
|
| 516 |
+
default_value=2,
|
| 517 |
+
message_type=None,
|
| 518 |
+
enum_type=None,
|
| 519 |
+
containing_type=None,
|
| 520 |
+
is_extension=False,
|
| 521 |
+
extension_scope=None,
|
| 522 |
+
serialized_options=None,
|
| 523 |
+
file=DESCRIPTOR,
|
| 524 |
+
create_key=_descriptor._internal_create_key,
|
| 525 |
+
),
|
| 526 |
+
_descriptor.FieldDescriptor(
|
| 527 |
+
name="max_sentencepiece_length",
|
| 528 |
+
full_name="sentencepiece.TrainerSpec.max_sentencepiece_length",
|
| 529 |
+
index=17,
|
| 530 |
+
number=20,
|
| 531 |
+
type=5,
|
| 532 |
+
cpp_type=1,
|
| 533 |
+
label=1,
|
| 534 |
+
has_default_value=True,
|
| 535 |
+
default_value=16,
|
| 536 |
+
message_type=None,
|
| 537 |
+
enum_type=None,
|
| 538 |
+
containing_type=None,
|
| 539 |
+
is_extension=False,
|
| 540 |
+
extension_scope=None,
|
| 541 |
+
serialized_options=None,
|
| 542 |
+
file=DESCRIPTOR,
|
| 543 |
+
create_key=_descriptor._internal_create_key,
|
| 544 |
+
),
|
| 545 |
+
_descriptor.FieldDescriptor(
|
| 546 |
+
name="split_by_unicode_script",
|
| 547 |
+
full_name="sentencepiece.TrainerSpec.split_by_unicode_script",
|
| 548 |
+
index=18,
|
| 549 |
+
number=21,
|
| 550 |
+
type=8,
|
| 551 |
+
cpp_type=7,
|
| 552 |
+
label=1,
|
| 553 |
+
has_default_value=True,
|
| 554 |
+
default_value=True,
|
| 555 |
+
message_type=None,
|
| 556 |
+
enum_type=None,
|
| 557 |
+
containing_type=None,
|
| 558 |
+
is_extension=False,
|
| 559 |
+
extension_scope=None,
|
| 560 |
+
serialized_options=None,
|
| 561 |
+
file=DESCRIPTOR,
|
| 562 |
+
create_key=_descriptor._internal_create_key,
|
| 563 |
+
),
|
| 564 |
+
_descriptor.FieldDescriptor(
|
| 565 |
+
name="split_by_number",
|
| 566 |
+
full_name="sentencepiece.TrainerSpec.split_by_number",
|
| 567 |
+
index=19,
|
| 568 |
+
number=23,
|
| 569 |
+
type=8,
|
| 570 |
+
cpp_type=7,
|
| 571 |
+
label=1,
|
| 572 |
+
has_default_value=True,
|
| 573 |
+
default_value=True,
|
| 574 |
+
message_type=None,
|
| 575 |
+
enum_type=None,
|
| 576 |
+
containing_type=None,
|
| 577 |
+
is_extension=False,
|
| 578 |
+
extension_scope=None,
|
| 579 |
+
serialized_options=None,
|
| 580 |
+
file=DESCRIPTOR,
|
| 581 |
+
create_key=_descriptor._internal_create_key,
|
| 582 |
+
),
|
| 583 |
+
_descriptor.FieldDescriptor(
|
| 584 |
+
name="split_by_whitespace",
|
| 585 |
+
full_name="sentencepiece.TrainerSpec.split_by_whitespace",
|
| 586 |
+
index=20,
|
| 587 |
+
number=22,
|
| 588 |
+
type=8,
|
| 589 |
+
cpp_type=7,
|
| 590 |
+
label=1,
|
| 591 |
+
has_default_value=True,
|
| 592 |
+
default_value=True,
|
| 593 |
+
message_type=None,
|
| 594 |
+
enum_type=None,
|
| 595 |
+
containing_type=None,
|
| 596 |
+
is_extension=False,
|
| 597 |
+
extension_scope=None,
|
| 598 |
+
serialized_options=None,
|
| 599 |
+
file=DESCRIPTOR,
|
| 600 |
+
create_key=_descriptor._internal_create_key,
|
| 601 |
+
),
|
| 602 |
+
_descriptor.FieldDescriptor(
|
| 603 |
+
name="treat_whitespace_as_suffix",
|
| 604 |
+
full_name="sentencepiece.TrainerSpec.treat_whitespace_as_suffix",
|
| 605 |
+
index=21,
|
| 606 |
+
number=24,
|
| 607 |
+
type=8,
|
| 608 |
+
cpp_type=7,
|
| 609 |
+
label=1,
|
| 610 |
+
has_default_value=True,
|
| 611 |
+
default_value=False,
|
| 612 |
+
message_type=None,
|
| 613 |
+
enum_type=None,
|
| 614 |
+
containing_type=None,
|
| 615 |
+
is_extension=False,
|
| 616 |
+
extension_scope=None,
|
| 617 |
+
serialized_options=None,
|
| 618 |
+
file=DESCRIPTOR,
|
| 619 |
+
create_key=_descriptor._internal_create_key,
|
| 620 |
+
),
|
| 621 |
+
_descriptor.FieldDescriptor(
|
| 622 |
+
name="split_digits",
|
| 623 |
+
full_name="sentencepiece.TrainerSpec.split_digits",
|
| 624 |
+
index=22,
|
| 625 |
+
number=25,
|
| 626 |
+
type=8,
|
| 627 |
+
cpp_type=7,
|
| 628 |
+
label=1,
|
| 629 |
+
has_default_value=True,
|
| 630 |
+
default_value=False,
|
| 631 |
+
message_type=None,
|
| 632 |
+
enum_type=None,
|
| 633 |
+
containing_type=None,
|
| 634 |
+
is_extension=False,
|
| 635 |
+
extension_scope=None,
|
| 636 |
+
serialized_options=None,
|
| 637 |
+
file=DESCRIPTOR,
|
| 638 |
+
create_key=_descriptor._internal_create_key,
|
| 639 |
+
),
|
| 640 |
+
_descriptor.FieldDescriptor(
|
| 641 |
+
name="control_symbols",
|
| 642 |
+
full_name="sentencepiece.TrainerSpec.control_symbols",
|
| 643 |
+
index=23,
|
| 644 |
+
number=30,
|
| 645 |
+
type=9,
|
| 646 |
+
cpp_type=9,
|
| 647 |
+
label=3,
|
| 648 |
+
has_default_value=False,
|
| 649 |
+
default_value=[],
|
| 650 |
+
message_type=None,
|
| 651 |
+
enum_type=None,
|
| 652 |
+
containing_type=None,
|
| 653 |
+
is_extension=False,
|
| 654 |
+
extension_scope=None,
|
| 655 |
+
serialized_options=None,
|
| 656 |
+
file=DESCRIPTOR,
|
| 657 |
+
create_key=_descriptor._internal_create_key,
|
| 658 |
+
),
|
| 659 |
+
_descriptor.FieldDescriptor(
|
| 660 |
+
name="user_defined_symbols",
|
| 661 |
+
full_name="sentencepiece.TrainerSpec.user_defined_symbols",
|
| 662 |
+
index=24,
|
| 663 |
+
number=31,
|
| 664 |
+
type=9,
|
| 665 |
+
cpp_type=9,
|
| 666 |
+
label=3,
|
| 667 |
+
has_default_value=False,
|
| 668 |
+
default_value=[],
|
| 669 |
+
message_type=None,
|
| 670 |
+
enum_type=None,
|
| 671 |
+
containing_type=None,
|
| 672 |
+
is_extension=False,
|
| 673 |
+
extension_scope=None,
|
| 674 |
+
serialized_options=None,
|
| 675 |
+
file=DESCRIPTOR,
|
| 676 |
+
create_key=_descriptor._internal_create_key,
|
| 677 |
+
),
|
| 678 |
+
_descriptor.FieldDescriptor(
|
| 679 |
+
name="required_chars",
|
| 680 |
+
full_name="sentencepiece.TrainerSpec.required_chars",
|
| 681 |
+
index=25,
|
| 682 |
+
number=36,
|
| 683 |
+
type=9,
|
| 684 |
+
cpp_type=9,
|
| 685 |
+
label=1,
|
| 686 |
+
has_default_value=False,
|
| 687 |
+
default_value=b"".decode("utf-8"),
|
| 688 |
+
message_type=None,
|
| 689 |
+
enum_type=None,
|
| 690 |
+
containing_type=None,
|
| 691 |
+
is_extension=False,
|
| 692 |
+
extension_scope=None,
|
| 693 |
+
serialized_options=None,
|
| 694 |
+
file=DESCRIPTOR,
|
| 695 |
+
create_key=_descriptor._internal_create_key,
|
| 696 |
+
),
|
| 697 |
+
_descriptor.FieldDescriptor(
|
| 698 |
+
name="byte_fallback",
|
| 699 |
+
full_name="sentencepiece.TrainerSpec.byte_fallback",
|
| 700 |
+
index=26,
|
| 701 |
+
number=35,
|
| 702 |
+
type=8,
|
| 703 |
+
cpp_type=7,
|
| 704 |
+
label=1,
|
| 705 |
+
has_default_value=True,
|
| 706 |
+
default_value=False,
|
| 707 |
+
message_type=None,
|
| 708 |
+
enum_type=None,
|
| 709 |
+
containing_type=None,
|
| 710 |
+
is_extension=False,
|
| 711 |
+
extension_scope=None,
|
| 712 |
+
serialized_options=None,
|
| 713 |
+
file=DESCRIPTOR,
|
| 714 |
+
create_key=_descriptor._internal_create_key,
|
| 715 |
+
),
|
| 716 |
+
_descriptor.FieldDescriptor(
|
| 717 |
+
name="vocabulary_output_piece_score",
|
| 718 |
+
full_name="sentencepiece.TrainerSpec.vocabulary_output_piece_score",
|
| 719 |
+
index=27,
|
| 720 |
+
number=32,
|
| 721 |
+
type=8,
|
| 722 |
+
cpp_type=7,
|
| 723 |
+
label=1,
|
| 724 |
+
has_default_value=True,
|
| 725 |
+
default_value=True,
|
| 726 |
+
message_type=None,
|
| 727 |
+
enum_type=None,
|
| 728 |
+
containing_type=None,
|
| 729 |
+
is_extension=False,
|
| 730 |
+
extension_scope=None,
|
| 731 |
+
serialized_options=None,
|
| 732 |
+
file=DESCRIPTOR,
|
| 733 |
+
create_key=_descriptor._internal_create_key,
|
| 734 |
+
),
|
| 735 |
+
_descriptor.FieldDescriptor(
|
| 736 |
+
name="hard_vocab_limit",
|
| 737 |
+
full_name="sentencepiece.TrainerSpec.hard_vocab_limit",
|
| 738 |
+
index=28,
|
| 739 |
+
number=33,
|
| 740 |
+
type=8,
|
| 741 |
+
cpp_type=7,
|
| 742 |
+
label=1,
|
| 743 |
+
has_default_value=True,
|
| 744 |
+
default_value=True,
|
| 745 |
+
message_type=None,
|
| 746 |
+
enum_type=None,
|
| 747 |
+
containing_type=None,
|
| 748 |
+
is_extension=False,
|
| 749 |
+
extension_scope=None,
|
| 750 |
+
serialized_options=None,
|
| 751 |
+
file=DESCRIPTOR,
|
| 752 |
+
create_key=_descriptor._internal_create_key,
|
| 753 |
+
),
|
| 754 |
+
_descriptor.FieldDescriptor(
|
| 755 |
+
name="use_all_vocab",
|
| 756 |
+
full_name="sentencepiece.TrainerSpec.use_all_vocab",
|
| 757 |
+
index=29,
|
| 758 |
+
number=34,
|
| 759 |
+
type=8,
|
| 760 |
+
cpp_type=7,
|
| 761 |
+
label=1,
|
| 762 |
+
has_default_value=True,
|
| 763 |
+
default_value=False,
|
| 764 |
+
message_type=None,
|
| 765 |
+
enum_type=None,
|
| 766 |
+
containing_type=None,
|
| 767 |
+
is_extension=False,
|
| 768 |
+
extension_scope=None,
|
| 769 |
+
serialized_options=None,
|
| 770 |
+
file=DESCRIPTOR,
|
| 771 |
+
create_key=_descriptor._internal_create_key,
|
| 772 |
+
),
|
| 773 |
+
_descriptor.FieldDescriptor(
|
| 774 |
+
name="unk_id",
|
| 775 |
+
full_name="sentencepiece.TrainerSpec.unk_id",
|
| 776 |
+
index=30,
|
| 777 |
+
number=40,
|
| 778 |
+
type=5,
|
| 779 |
+
cpp_type=1,
|
| 780 |
+
label=1,
|
| 781 |
+
has_default_value=True,
|
| 782 |
+
default_value=0,
|
| 783 |
+
message_type=None,
|
| 784 |
+
enum_type=None,
|
| 785 |
+
containing_type=None,
|
| 786 |
+
is_extension=False,
|
| 787 |
+
extension_scope=None,
|
| 788 |
+
serialized_options=None,
|
| 789 |
+
file=DESCRIPTOR,
|
| 790 |
+
create_key=_descriptor._internal_create_key,
|
| 791 |
+
),
|
| 792 |
+
_descriptor.FieldDescriptor(
|
| 793 |
+
name="bos_id",
|
| 794 |
+
full_name="sentencepiece.TrainerSpec.bos_id",
|
| 795 |
+
index=31,
|
| 796 |
+
number=41,
|
| 797 |
+
type=5,
|
| 798 |
+
cpp_type=1,
|
| 799 |
+
label=1,
|
| 800 |
+
has_default_value=True,
|
| 801 |
+
default_value=1,
|
| 802 |
+
message_type=None,
|
| 803 |
+
enum_type=None,
|
| 804 |
+
containing_type=None,
|
| 805 |
+
is_extension=False,
|
| 806 |
+
extension_scope=None,
|
| 807 |
+
serialized_options=None,
|
| 808 |
+
file=DESCRIPTOR,
|
| 809 |
+
create_key=_descriptor._internal_create_key,
|
| 810 |
+
),
|
| 811 |
+
_descriptor.FieldDescriptor(
|
| 812 |
+
name="eos_id",
|
| 813 |
+
full_name="sentencepiece.TrainerSpec.eos_id",
|
| 814 |
+
index=32,
|
| 815 |
+
number=42,
|
| 816 |
+
type=5,
|
| 817 |
+
cpp_type=1,
|
| 818 |
+
label=1,
|
| 819 |
+
has_default_value=True,
|
| 820 |
+
default_value=2,
|
| 821 |
+
message_type=None,
|
| 822 |
+
enum_type=None,
|
| 823 |
+
containing_type=None,
|
| 824 |
+
is_extension=False,
|
| 825 |
+
extension_scope=None,
|
| 826 |
+
serialized_options=None,
|
| 827 |
+
file=DESCRIPTOR,
|
| 828 |
+
create_key=_descriptor._internal_create_key,
|
| 829 |
+
),
|
| 830 |
+
_descriptor.FieldDescriptor(
|
| 831 |
+
name="pad_id",
|
| 832 |
+
full_name="sentencepiece.TrainerSpec.pad_id",
|
| 833 |
+
index=33,
|
| 834 |
+
number=43,
|
| 835 |
+
type=5,
|
| 836 |
+
cpp_type=1,
|
| 837 |
+
label=1,
|
| 838 |
+
has_default_value=True,
|
| 839 |
+
default_value=-1,
|
| 840 |
+
message_type=None,
|
| 841 |
+
enum_type=None,
|
| 842 |
+
containing_type=None,
|
| 843 |
+
is_extension=False,
|
| 844 |
+
extension_scope=None,
|
| 845 |
+
serialized_options=None,
|
| 846 |
+
file=DESCRIPTOR,
|
| 847 |
+
create_key=_descriptor._internal_create_key,
|
| 848 |
+
),
|
| 849 |
+
_descriptor.FieldDescriptor(
|
| 850 |
+
name="unk_piece",
|
| 851 |
+
full_name="sentencepiece.TrainerSpec.unk_piece",
|
| 852 |
+
index=34,
|
| 853 |
+
number=45,
|
| 854 |
+
type=9,
|
| 855 |
+
cpp_type=9,
|
| 856 |
+
label=1,
|
| 857 |
+
has_default_value=True,
|
| 858 |
+
default_value=b"<unk>".decode("utf-8"),
|
| 859 |
+
message_type=None,
|
| 860 |
+
enum_type=None,
|
| 861 |
+
containing_type=None,
|
| 862 |
+
is_extension=False,
|
| 863 |
+
extension_scope=None,
|
| 864 |
+
serialized_options=None,
|
| 865 |
+
file=DESCRIPTOR,
|
| 866 |
+
create_key=_descriptor._internal_create_key,
|
| 867 |
+
),
|
| 868 |
+
_descriptor.FieldDescriptor(
|
| 869 |
+
name="bos_piece",
|
| 870 |
+
full_name="sentencepiece.TrainerSpec.bos_piece",
|
| 871 |
+
index=35,
|
| 872 |
+
number=46,
|
| 873 |
+
type=9,
|
| 874 |
+
cpp_type=9,
|
| 875 |
+
label=1,
|
| 876 |
+
has_default_value=True,
|
| 877 |
+
default_value=b"<s>".decode("utf-8"),
|
| 878 |
+
message_type=None,
|
| 879 |
+
enum_type=None,
|
| 880 |
+
containing_type=None,
|
| 881 |
+
is_extension=False,
|
| 882 |
+
extension_scope=None,
|
| 883 |
+
serialized_options=None,
|
| 884 |
+
file=DESCRIPTOR,
|
| 885 |
+
create_key=_descriptor._internal_create_key,
|
| 886 |
+
),
|
| 887 |
+
_descriptor.FieldDescriptor(
|
| 888 |
+
name="eos_piece",
|
| 889 |
+
full_name="sentencepiece.TrainerSpec.eos_piece",
|
| 890 |
+
index=36,
|
| 891 |
+
number=47,
|
| 892 |
+
type=9,
|
| 893 |
+
cpp_type=9,
|
| 894 |
+
label=1,
|
| 895 |
+
has_default_value=True,
|
| 896 |
+
default_value=b"</s>".decode("utf-8"),
|
| 897 |
+
message_type=None,
|
| 898 |
+
enum_type=None,
|
| 899 |
+
containing_type=None,
|
| 900 |
+
is_extension=False,
|
| 901 |
+
extension_scope=None,
|
| 902 |
+
serialized_options=None,
|
| 903 |
+
file=DESCRIPTOR,
|
| 904 |
+
create_key=_descriptor._internal_create_key,
|
| 905 |
+
),
|
| 906 |
+
_descriptor.FieldDescriptor(
|
| 907 |
+
name="pad_piece",
|
| 908 |
+
full_name="sentencepiece.TrainerSpec.pad_piece",
|
| 909 |
+
index=37,
|
| 910 |
+
number=48,
|
| 911 |
+
type=9,
|
| 912 |
+
cpp_type=9,
|
| 913 |
+
label=1,
|
| 914 |
+
has_default_value=True,
|
| 915 |
+
default_value=b"<pad>".decode("utf-8"),
|
| 916 |
+
message_type=None,
|
| 917 |
+
enum_type=None,
|
| 918 |
+
containing_type=None,
|
| 919 |
+
is_extension=False,
|
| 920 |
+
extension_scope=None,
|
| 921 |
+
serialized_options=None,
|
| 922 |
+
file=DESCRIPTOR,
|
| 923 |
+
create_key=_descriptor._internal_create_key,
|
| 924 |
+
),
|
| 925 |
+
_descriptor.FieldDescriptor(
|
| 926 |
+
name="unk_surface",
|
| 927 |
+
full_name="sentencepiece.TrainerSpec.unk_surface",
|
| 928 |
+
index=38,
|
| 929 |
+
number=44,
|
| 930 |
+
type=9,
|
| 931 |
+
cpp_type=9,
|
| 932 |
+
label=1,
|
| 933 |
+
has_default_value=True,
|
| 934 |
+
default_value=b" \342\201\207 ".decode("utf-8"),
|
| 935 |
+
message_type=None,
|
| 936 |
+
enum_type=None,
|
| 937 |
+
containing_type=None,
|
| 938 |
+
is_extension=False,
|
| 939 |
+
extension_scope=None,
|
| 940 |
+
serialized_options=None,
|
| 941 |
+
file=DESCRIPTOR,
|
| 942 |
+
create_key=_descriptor._internal_create_key,
|
| 943 |
+
),
|
| 944 |
+
_descriptor.FieldDescriptor(
|
| 945 |
+
name="train_extremely_large_corpus",
|
| 946 |
+
full_name="sentencepiece.TrainerSpec.train_extremely_large_corpus",
|
| 947 |
+
index=39,
|
| 948 |
+
number=49,
|
| 949 |
+
type=8,
|
| 950 |
+
cpp_type=7,
|
| 951 |
+
label=1,
|
| 952 |
+
has_default_value=True,
|
| 953 |
+
default_value=False,
|
| 954 |
+
message_type=None,
|
| 955 |
+
enum_type=None,
|
| 956 |
+
containing_type=None,
|
| 957 |
+
is_extension=False,
|
| 958 |
+
extension_scope=None,
|
| 959 |
+
serialized_options=None,
|
| 960 |
+
file=DESCRIPTOR,
|
| 961 |
+
create_key=_descriptor._internal_create_key,
|
| 962 |
+
),
|
| 963 |
+
],
|
| 964 |
+
extensions=[],
|
| 965 |
+
nested_types=[],
|
| 966 |
+
enum_types=[
|
| 967 |
+
_TRAINERSPEC_MODELTYPE,
|
| 968 |
+
],
|
| 969 |
+
serialized_options=None,
|
| 970 |
+
is_extendable=True,
|
| 971 |
+
syntax="proto2",
|
| 972 |
+
extension_ranges=[
|
| 973 |
+
(200, 536870912),
|
| 974 |
+
],
|
| 975 |
+
oneofs=[],
|
| 976 |
+
serialized_start=45,
|
| 977 |
+
serialized_end=1358,
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
_NORMALIZERSPEC = _descriptor.Descriptor(
|
| 982 |
+
name="NormalizerSpec",
|
| 983 |
+
full_name="sentencepiece.NormalizerSpec",
|
| 984 |
+
filename=None,
|
| 985 |
+
file=DESCRIPTOR,
|
| 986 |
+
containing_type=None,
|
| 987 |
+
create_key=_descriptor._internal_create_key,
|
| 988 |
+
fields=[
|
| 989 |
+
_descriptor.FieldDescriptor(
|
| 990 |
+
name="name",
|
| 991 |
+
full_name="sentencepiece.NormalizerSpec.name",
|
| 992 |
+
index=0,
|
| 993 |
+
number=1,
|
| 994 |
+
type=9,
|
| 995 |
+
cpp_type=9,
|
| 996 |
+
label=1,
|
| 997 |
+
has_default_value=False,
|
| 998 |
+
default_value=b"".decode("utf-8"),
|
| 999 |
+
message_type=None,
|
| 1000 |
+
enum_type=None,
|
| 1001 |
+
containing_type=None,
|
| 1002 |
+
is_extension=False,
|
| 1003 |
+
extension_scope=None,
|
| 1004 |
+
serialized_options=None,
|
| 1005 |
+
file=DESCRIPTOR,
|
| 1006 |
+
create_key=_descriptor._internal_create_key,
|
| 1007 |
+
),
|
| 1008 |
+
_descriptor.FieldDescriptor(
|
| 1009 |
+
name="precompiled_charsmap",
|
| 1010 |
+
full_name="sentencepiece.NormalizerSpec.precompiled_charsmap",
|
| 1011 |
+
index=1,
|
| 1012 |
+
number=2,
|
| 1013 |
+
type=12,
|
| 1014 |
+
cpp_type=9,
|
| 1015 |
+
label=1,
|
| 1016 |
+
has_default_value=False,
|
| 1017 |
+
default_value=b"",
|
| 1018 |
+
message_type=None,
|
| 1019 |
+
enum_type=None,
|
| 1020 |
+
containing_type=None,
|
| 1021 |
+
is_extension=False,
|
| 1022 |
+
extension_scope=None,
|
| 1023 |
+
serialized_options=None,
|
| 1024 |
+
file=DESCRIPTOR,
|
| 1025 |
+
create_key=_descriptor._internal_create_key,
|
| 1026 |
+
),
|
| 1027 |
+
_descriptor.FieldDescriptor(
|
| 1028 |
+
name="add_dummy_prefix",
|
| 1029 |
+
full_name="sentencepiece.NormalizerSpec.add_dummy_prefix",
|
| 1030 |
+
index=2,
|
| 1031 |
+
number=3,
|
| 1032 |
+
type=8,
|
| 1033 |
+
cpp_type=7,
|
| 1034 |
+
label=1,
|
| 1035 |
+
has_default_value=True,
|
| 1036 |
+
default_value=True,
|
| 1037 |
+
message_type=None,
|
| 1038 |
+
enum_type=None,
|
| 1039 |
+
containing_type=None,
|
| 1040 |
+
is_extension=False,
|
| 1041 |
+
extension_scope=None,
|
| 1042 |
+
serialized_options=None,
|
| 1043 |
+
file=DESCRIPTOR,
|
| 1044 |
+
create_key=_descriptor._internal_create_key,
|
| 1045 |
+
),
|
| 1046 |
+
_descriptor.FieldDescriptor(
|
| 1047 |
+
name="remove_extra_whitespaces",
|
| 1048 |
+
full_name="sentencepiece.NormalizerSpec.remove_extra_whitespaces",
|
| 1049 |
+
index=3,
|
| 1050 |
+
number=4,
|
| 1051 |
+
type=8,
|
| 1052 |
+
cpp_type=7,
|
| 1053 |
+
label=1,
|
| 1054 |
+
has_default_value=True,
|
| 1055 |
+
default_value=True,
|
| 1056 |
+
message_type=None,
|
| 1057 |
+
enum_type=None,
|
| 1058 |
+
containing_type=None,
|
| 1059 |
+
is_extension=False,
|
| 1060 |
+
extension_scope=None,
|
| 1061 |
+
serialized_options=None,
|
| 1062 |
+
file=DESCRIPTOR,
|
| 1063 |
+
create_key=_descriptor._internal_create_key,
|
| 1064 |
+
),
|
| 1065 |
+
_descriptor.FieldDescriptor(
|
| 1066 |
+
name="escape_whitespaces",
|
| 1067 |
+
full_name="sentencepiece.NormalizerSpec.escape_whitespaces",
|
| 1068 |
+
index=4,
|
| 1069 |
+
number=5,
|
| 1070 |
+
type=8,
|
| 1071 |
+
cpp_type=7,
|
| 1072 |
+
label=1,
|
| 1073 |
+
has_default_value=True,
|
| 1074 |
+
default_value=True,
|
| 1075 |
+
message_type=None,
|
| 1076 |
+
enum_type=None,
|
| 1077 |
+
containing_type=None,
|
| 1078 |
+
is_extension=False,
|
| 1079 |
+
extension_scope=None,
|
| 1080 |
+
serialized_options=None,
|
| 1081 |
+
file=DESCRIPTOR,
|
| 1082 |
+
create_key=_descriptor._internal_create_key,
|
| 1083 |
+
),
|
| 1084 |
+
_descriptor.FieldDescriptor(
|
| 1085 |
+
name="normalization_rule_tsv",
|
| 1086 |
+
full_name="sentencepiece.NormalizerSpec.normalization_rule_tsv",
|
| 1087 |
+
index=5,
|
| 1088 |
+
number=6,
|
| 1089 |
+
type=9,
|
| 1090 |
+
cpp_type=9,
|
| 1091 |
+
label=1,
|
| 1092 |
+
has_default_value=False,
|
| 1093 |
+
default_value=b"".decode("utf-8"),
|
| 1094 |
+
message_type=None,
|
| 1095 |
+
enum_type=None,
|
| 1096 |
+
containing_type=None,
|
| 1097 |
+
is_extension=False,
|
| 1098 |
+
extension_scope=None,
|
| 1099 |
+
serialized_options=None,
|
| 1100 |
+
file=DESCRIPTOR,
|
| 1101 |
+
create_key=_descriptor._internal_create_key,
|
| 1102 |
+
),
|
| 1103 |
+
],
|
| 1104 |
+
extensions=[],
|
| 1105 |
+
nested_types=[],
|
| 1106 |
+
enum_types=[],
|
| 1107 |
+
serialized_options=None,
|
| 1108 |
+
is_extendable=True,
|
| 1109 |
+
syntax="proto2",
|
| 1110 |
+
extension_ranges=[
|
| 1111 |
+
(200, 536870912),
|
| 1112 |
+
],
|
| 1113 |
+
oneofs=[],
|
| 1114 |
+
serialized_start=1361,
|
| 1115 |
+
serialized_end=1570,
|
| 1116 |
+
)
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
_SELFTESTDATA_SAMPLE = _descriptor.Descriptor(
|
| 1120 |
+
name="Sample",
|
| 1121 |
+
full_name="sentencepiece.SelfTestData.Sample",
|
| 1122 |
+
filename=None,
|
| 1123 |
+
file=DESCRIPTOR,
|
| 1124 |
+
containing_type=None,
|
| 1125 |
+
create_key=_descriptor._internal_create_key,
|
| 1126 |
+
fields=[
|
| 1127 |
+
_descriptor.FieldDescriptor(
|
| 1128 |
+
name="input",
|
| 1129 |
+
full_name="sentencepiece.SelfTestData.Sample.input",
|
| 1130 |
+
index=0,
|
| 1131 |
+
number=1,
|
| 1132 |
+
type=9,
|
| 1133 |
+
cpp_type=9,
|
| 1134 |
+
label=1,
|
| 1135 |
+
has_default_value=False,
|
| 1136 |
+
default_value=b"".decode("utf-8"),
|
| 1137 |
+
message_type=None,
|
| 1138 |
+
enum_type=None,
|
| 1139 |
+
containing_type=None,
|
| 1140 |
+
is_extension=False,
|
| 1141 |
+
extension_scope=None,
|
| 1142 |
+
serialized_options=None,
|
| 1143 |
+
file=DESCRIPTOR,
|
| 1144 |
+
create_key=_descriptor._internal_create_key,
|
| 1145 |
+
),
|
| 1146 |
+
_descriptor.FieldDescriptor(
|
| 1147 |
+
name="expected",
|
| 1148 |
+
full_name="sentencepiece.SelfTestData.Sample.expected",
|
| 1149 |
+
index=1,
|
| 1150 |
+
number=2,
|
| 1151 |
+
type=9,
|
| 1152 |
+
cpp_type=9,
|
| 1153 |
+
label=1,
|
| 1154 |
+
has_default_value=False,
|
| 1155 |
+
default_value=b"".decode("utf-8"),
|
| 1156 |
+
message_type=None,
|
| 1157 |
+
enum_type=None,
|
| 1158 |
+
containing_type=None,
|
| 1159 |
+
is_extension=False,
|
| 1160 |
+
extension_scope=None,
|
| 1161 |
+
serialized_options=None,
|
| 1162 |
+
file=DESCRIPTOR,
|
| 1163 |
+
create_key=_descriptor._internal_create_key,
|
| 1164 |
+
),
|
| 1165 |
+
],
|
| 1166 |
+
extensions=[],
|
| 1167 |
+
nested_types=[],
|
| 1168 |
+
enum_types=[],
|
| 1169 |
+
serialized_options=None,
|
| 1170 |
+
is_extendable=False,
|
| 1171 |
+
syntax="proto2",
|
| 1172 |
+
extension_ranges=[],
|
| 1173 |
+
oneofs=[],
|
| 1174 |
+
serialized_start=1641,
|
| 1175 |
+
serialized_end=1682,
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
_SELFTESTDATA = _descriptor.Descriptor(
|
| 1179 |
+
name="SelfTestData",
|
| 1180 |
+
full_name="sentencepiece.SelfTestData",
|
| 1181 |
+
filename=None,
|
| 1182 |
+
file=DESCRIPTOR,
|
| 1183 |
+
containing_type=None,
|
| 1184 |
+
create_key=_descriptor._internal_create_key,
|
| 1185 |
+
fields=[
|
| 1186 |
+
_descriptor.FieldDescriptor(
|
| 1187 |
+
name="samples",
|
| 1188 |
+
full_name="sentencepiece.SelfTestData.samples",
|
| 1189 |
+
index=0,
|
| 1190 |
+
number=1,
|
| 1191 |
+
type=11,
|
| 1192 |
+
cpp_type=10,
|
| 1193 |
+
label=3,
|
| 1194 |
+
has_default_value=False,
|
| 1195 |
+
default_value=[],
|
| 1196 |
+
message_type=None,
|
| 1197 |
+
enum_type=None,
|
| 1198 |
+
containing_type=None,
|
| 1199 |
+
is_extension=False,
|
| 1200 |
+
extension_scope=None,
|
| 1201 |
+
serialized_options=None,
|
| 1202 |
+
file=DESCRIPTOR,
|
| 1203 |
+
create_key=_descriptor._internal_create_key,
|
| 1204 |
+
),
|
| 1205 |
+
],
|
| 1206 |
+
extensions=[],
|
| 1207 |
+
nested_types=[
|
| 1208 |
+
_SELFTESTDATA_SAMPLE,
|
| 1209 |
+
],
|
| 1210 |
+
enum_types=[],
|
| 1211 |
+
serialized_options=None,
|
| 1212 |
+
is_extendable=True,
|
| 1213 |
+
syntax="proto2",
|
| 1214 |
+
extension_ranges=[
|
| 1215 |
+
(200, 536870912),
|
| 1216 |
+
],
|
| 1217 |
+
oneofs=[],
|
| 1218 |
+
serialized_start=1572,
|
| 1219 |
+
serialized_end=1693,
|
| 1220 |
+
)
|
| 1221 |
+
|
| 1222 |
+
|
| 1223 |
+
_MODELPROTO_SENTENCEPIECE = _descriptor.Descriptor(
|
| 1224 |
+
name="SentencePiece",
|
| 1225 |
+
full_name="sentencepiece.ModelProto.SentencePiece",
|
| 1226 |
+
filename=None,
|
| 1227 |
+
file=DESCRIPTOR,
|
| 1228 |
+
containing_type=None,
|
| 1229 |
+
create_key=_descriptor._internal_create_key,
|
| 1230 |
+
fields=[
|
| 1231 |
+
_descriptor.FieldDescriptor(
|
| 1232 |
+
name="piece",
|
| 1233 |
+
full_name="sentencepiece.ModelProto.SentencePiece.piece",
|
| 1234 |
+
index=0,
|
| 1235 |
+
number=1,
|
| 1236 |
+
type=9,
|
| 1237 |
+
cpp_type=9,
|
| 1238 |
+
label=1,
|
| 1239 |
+
has_default_value=False,
|
| 1240 |
+
default_value=b"".decode("utf-8"),
|
| 1241 |
+
message_type=None,
|
| 1242 |
+
enum_type=None,
|
| 1243 |
+
containing_type=None,
|
| 1244 |
+
is_extension=False,
|
| 1245 |
+
extension_scope=None,
|
| 1246 |
+
serialized_options=None,
|
| 1247 |
+
file=DESCRIPTOR,
|
| 1248 |
+
create_key=_descriptor._internal_create_key,
|
| 1249 |
+
),
|
| 1250 |
+
_descriptor.FieldDescriptor(
|
| 1251 |
+
name="score",
|
| 1252 |
+
full_name="sentencepiece.ModelProto.SentencePiece.score",
|
| 1253 |
+
index=1,
|
| 1254 |
+
number=2,
|
| 1255 |
+
type=2,
|
| 1256 |
+
cpp_type=6,
|
| 1257 |
+
label=1,
|
| 1258 |
+
has_default_value=False,
|
| 1259 |
+
default_value=float(0),
|
| 1260 |
+
message_type=None,
|
| 1261 |
+
enum_type=None,
|
| 1262 |
+
containing_type=None,
|
| 1263 |
+
is_extension=False,
|
| 1264 |
+
extension_scope=None,
|
| 1265 |
+
serialized_options=None,
|
| 1266 |
+
file=DESCRIPTOR,
|
| 1267 |
+
create_key=_descriptor._internal_create_key,
|
| 1268 |
+
),
|
| 1269 |
+
_descriptor.FieldDescriptor(
|
| 1270 |
+
name="type",
|
| 1271 |
+
full_name="sentencepiece.ModelProto.SentencePiece.type",
|
| 1272 |
+
index=2,
|
| 1273 |
+
number=3,
|
| 1274 |
+
type=14,
|
| 1275 |
+
cpp_type=8,
|
| 1276 |
+
label=1,
|
| 1277 |
+
has_default_value=True,
|
| 1278 |
+
default_value=1,
|
| 1279 |
+
message_type=None,
|
| 1280 |
+
enum_type=None,
|
| 1281 |
+
containing_type=None,
|
| 1282 |
+
is_extension=False,
|
| 1283 |
+
extension_scope=None,
|
| 1284 |
+
serialized_options=None,
|
| 1285 |
+
file=DESCRIPTOR,
|
| 1286 |
+
create_key=_descriptor._internal_create_key,
|
| 1287 |
+
),
|
| 1288 |
+
],
|
| 1289 |
+
extensions=[],
|
| 1290 |
+
nested_types=[],
|
| 1291 |
+
enum_types=[
|
| 1292 |
+
_MODELPROTO_SENTENCEPIECE_TYPE,
|
| 1293 |
+
],
|
| 1294 |
+
serialized_options=None,
|
| 1295 |
+
is_extendable=True,
|
| 1296 |
+
syntax="proto2",
|
| 1297 |
+
extension_ranges=[
|
| 1298 |
+
(200, 536870912),
|
| 1299 |
+
],
|
| 1300 |
+
oneofs=[],
|
| 1301 |
+
serialized_start=1985,
|
| 1302 |
+
serialized_end=2195,
|
| 1303 |
+
)
|
| 1304 |
+
|
| 1305 |
+
_MODELPROTO = _descriptor.Descriptor(
|
| 1306 |
+
name="ModelProto",
|
| 1307 |
+
full_name="sentencepiece.ModelProto",
|
| 1308 |
+
filename=None,
|
| 1309 |
+
file=DESCRIPTOR,
|
| 1310 |
+
containing_type=None,
|
| 1311 |
+
create_key=_descriptor._internal_create_key,
|
| 1312 |
+
fields=[
|
| 1313 |
+
_descriptor.FieldDescriptor(
|
| 1314 |
+
name="pieces",
|
| 1315 |
+
full_name="sentencepiece.ModelProto.pieces",
|
| 1316 |
+
index=0,
|
| 1317 |
+
number=1,
|
| 1318 |
+
type=11,
|
| 1319 |
+
cpp_type=10,
|
| 1320 |
+
label=3,
|
| 1321 |
+
has_default_value=False,
|
| 1322 |
+
default_value=[],
|
| 1323 |
+
message_type=None,
|
| 1324 |
+
enum_type=None,
|
| 1325 |
+
containing_type=None,
|
| 1326 |
+
is_extension=False,
|
| 1327 |
+
extension_scope=None,
|
| 1328 |
+
serialized_options=None,
|
| 1329 |
+
file=DESCRIPTOR,
|
| 1330 |
+
create_key=_descriptor._internal_create_key,
|
| 1331 |
+
),
|
| 1332 |
+
_descriptor.FieldDescriptor(
|
| 1333 |
+
name="trainer_spec",
|
| 1334 |
+
full_name="sentencepiece.ModelProto.trainer_spec",
|
| 1335 |
+
index=1,
|
| 1336 |
+
number=2,
|
| 1337 |
+
type=11,
|
| 1338 |
+
cpp_type=10,
|
| 1339 |
+
label=1,
|
| 1340 |
+
has_default_value=False,
|
| 1341 |
+
default_value=None,
|
| 1342 |
+
message_type=None,
|
| 1343 |
+
enum_type=None,
|
| 1344 |
+
containing_type=None,
|
| 1345 |
+
is_extension=False,
|
| 1346 |
+
extension_scope=None,
|
| 1347 |
+
serialized_options=None,
|
| 1348 |
+
file=DESCRIPTOR,
|
| 1349 |
+
create_key=_descriptor._internal_create_key,
|
| 1350 |
+
),
|
| 1351 |
+
_descriptor.FieldDescriptor(
|
| 1352 |
+
name="normalizer_spec",
|
| 1353 |
+
full_name="sentencepiece.ModelProto.normalizer_spec",
|
| 1354 |
+
index=2,
|
| 1355 |
+
number=3,
|
| 1356 |
+
type=11,
|
| 1357 |
+
cpp_type=10,
|
| 1358 |
+
label=1,
|
| 1359 |
+
has_default_value=False,
|
| 1360 |
+
default_value=None,
|
| 1361 |
+
message_type=None,
|
| 1362 |
+
enum_type=None,
|
| 1363 |
+
containing_type=None,
|
| 1364 |
+
is_extension=False,
|
| 1365 |
+
extension_scope=None,
|
| 1366 |
+
serialized_options=None,
|
| 1367 |
+
file=DESCRIPTOR,
|
| 1368 |
+
create_key=_descriptor._internal_create_key,
|
| 1369 |
+
),
|
| 1370 |
+
_descriptor.FieldDescriptor(
|
| 1371 |
+
name="self_test_data",
|
| 1372 |
+
full_name="sentencepiece.ModelProto.self_test_data",
|
| 1373 |
+
index=3,
|
| 1374 |
+
number=4,
|
| 1375 |
+
type=11,
|
| 1376 |
+
cpp_type=10,
|
| 1377 |
+
label=1,
|
| 1378 |
+
has_default_value=False,
|
| 1379 |
+
default_value=None,
|
| 1380 |
+
message_type=None,
|
| 1381 |
+
enum_type=None,
|
| 1382 |
+
containing_type=None,
|
| 1383 |
+
is_extension=False,
|
| 1384 |
+
extension_scope=None,
|
| 1385 |
+
serialized_options=None,
|
| 1386 |
+
file=DESCRIPTOR,
|
| 1387 |
+
create_key=_descriptor._internal_create_key,
|
| 1388 |
+
),
|
| 1389 |
+
_descriptor.FieldDescriptor(
|
| 1390 |
+
name="denormalizer_spec",
|
| 1391 |
+
full_name="sentencepiece.ModelProto.denormalizer_spec",
|
| 1392 |
+
index=4,
|
| 1393 |
+
number=5,
|
| 1394 |
+
type=11,
|
| 1395 |
+
cpp_type=10,
|
| 1396 |
+
label=1,
|
| 1397 |
+
has_default_value=False,
|
| 1398 |
+
default_value=None,
|
| 1399 |
+
message_type=None,
|
| 1400 |
+
enum_type=None,
|
| 1401 |
+
containing_type=None,
|
| 1402 |
+
is_extension=False,
|
| 1403 |
+
extension_scope=None,
|
| 1404 |
+
serialized_options=None,
|
| 1405 |
+
file=DESCRIPTOR,
|
| 1406 |
+
create_key=_descriptor._internal_create_key,
|
| 1407 |
+
),
|
| 1408 |
+
],
|
| 1409 |
+
extensions=[],
|
| 1410 |
+
nested_types=[
|
| 1411 |
+
_MODELPROTO_SENTENCEPIECE,
|
| 1412 |
+
],
|
| 1413 |
+
enum_types=[],
|
| 1414 |
+
serialized_options=None,
|
| 1415 |
+
is_extendable=True,
|
| 1416 |
+
syntax="proto2",
|
| 1417 |
+
extension_ranges=[
|
| 1418 |
+
(200, 536870912),
|
| 1419 |
+
],
|
| 1420 |
+
oneofs=[],
|
| 1421 |
+
serialized_start=1696,
|
| 1422 |
+
serialized_end=2206,
|
| 1423 |
+
)
|
| 1424 |
+
|
| 1425 |
+
_TRAINERSPEC.fields_by_name["model_type"].enum_type = _TRAINERSPEC_MODELTYPE
|
| 1426 |
+
_TRAINERSPEC_MODELTYPE.containing_type = _TRAINERSPEC
|
| 1427 |
+
_SELFTESTDATA_SAMPLE.containing_type = _SELFTESTDATA
|
| 1428 |
+
_SELFTESTDATA.fields_by_name["samples"].message_type = _SELFTESTDATA_SAMPLE
|
| 1429 |
+
_MODELPROTO_SENTENCEPIECE.fields_by_name["type"].enum_type = _MODELPROTO_SENTENCEPIECE_TYPE
|
| 1430 |
+
_MODELPROTO_SENTENCEPIECE.containing_type = _MODELPROTO
|
| 1431 |
+
_MODELPROTO_SENTENCEPIECE_TYPE.containing_type = _MODELPROTO_SENTENCEPIECE
|
| 1432 |
+
_MODELPROTO.fields_by_name["pieces"].message_type = _MODELPROTO_SENTENCEPIECE
|
| 1433 |
+
_MODELPROTO.fields_by_name["trainer_spec"].message_type = _TRAINERSPEC
|
| 1434 |
+
_MODELPROTO.fields_by_name["normalizer_spec"].message_type = _NORMALIZERSPEC
|
| 1435 |
+
_MODELPROTO.fields_by_name["self_test_data"].message_type = _SELFTESTDATA
|
| 1436 |
+
_MODELPROTO.fields_by_name["denormalizer_spec"].message_type = _NORMALIZERSPEC
|
| 1437 |
+
DESCRIPTOR.message_types_by_name["TrainerSpec"] = _TRAINERSPEC
|
| 1438 |
+
DESCRIPTOR.message_types_by_name["NormalizerSpec"] = _NORMALIZERSPEC
|
| 1439 |
+
DESCRIPTOR.message_types_by_name["SelfTestData"] = _SELFTESTDATA
|
| 1440 |
+
DESCRIPTOR.message_types_by_name["ModelProto"] = _MODELPROTO
|
| 1441 |
+
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
|
| 1442 |
+
|
| 1443 |
+
TrainerSpec = _reflection.GeneratedProtocolMessageType(
|
| 1444 |
+
"TrainerSpec",
|
| 1445 |
+
(_message.Message,),
|
| 1446 |
+
{
|
| 1447 |
+
"DESCRIPTOR": _TRAINERSPEC,
|
| 1448 |
+
"__module__": "sentencepiece_model_pb2",
|
| 1449 |
+
# @@protoc_insertion_point(class_scope:sentencepiece.TrainerSpec)
|
| 1450 |
+
},
|
| 1451 |
+
)
|
| 1452 |
+
_sym_db.RegisterMessage(TrainerSpec)
|
| 1453 |
+
|
| 1454 |
+
NormalizerSpec = _reflection.GeneratedProtocolMessageType(
|
| 1455 |
+
"NormalizerSpec",
|
| 1456 |
+
(_message.Message,),
|
| 1457 |
+
{
|
| 1458 |
+
"DESCRIPTOR": _NORMALIZERSPEC,
|
| 1459 |
+
"__module__": "sentencepiece_model_pb2",
|
| 1460 |
+
# @@protoc_insertion_point(class_scope:sentencepiece.NormalizerSpec)
|
| 1461 |
+
},
|
| 1462 |
+
)
|
| 1463 |
+
_sym_db.RegisterMessage(NormalizerSpec)
|
| 1464 |
+
|
| 1465 |
+
SelfTestData = _reflection.GeneratedProtocolMessageType(
|
| 1466 |
+
"SelfTestData",
|
| 1467 |
+
(_message.Message,),
|
| 1468 |
+
{
|
| 1469 |
+
"Sample": _reflection.GeneratedProtocolMessageType(
|
| 1470 |
+
"Sample",
|
| 1471 |
+
(_message.Message,),
|
| 1472 |
+
{
|
| 1473 |
+
"DESCRIPTOR": _SELFTESTDATA_SAMPLE,
|
| 1474 |
+
"__module__": "sentencepiece_model_pb2",
|
| 1475 |
+
# @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData.Sample)
|
| 1476 |
+
},
|
| 1477 |
+
),
|
| 1478 |
+
"DESCRIPTOR": _SELFTESTDATA,
|
| 1479 |
+
"__module__": "sentencepiece_model_pb2",
|
| 1480 |
+
# @@protoc_insertion_point(class_scope:sentencepiece.SelfTestData)
|
| 1481 |
+
},
|
| 1482 |
+
)
|
| 1483 |
+
_sym_db.RegisterMessage(SelfTestData)
|
| 1484 |
+
_sym_db.RegisterMessage(SelfTestData.Sample)
|
| 1485 |
+
|
| 1486 |
+
ModelProto = _reflection.GeneratedProtocolMessageType(
|
| 1487 |
+
"ModelProto",
|
| 1488 |
+
(_message.Message,),
|
| 1489 |
+
{
|
| 1490 |
+
"SentencePiece": _reflection.GeneratedProtocolMessageType(
|
| 1491 |
+
"SentencePiece",
|
| 1492 |
+
(_message.Message,),
|
| 1493 |
+
{
|
| 1494 |
+
"DESCRIPTOR": _MODELPROTO_SENTENCEPIECE,
|
| 1495 |
+
"__module__": "sentencepiece_model_pb2",
|
| 1496 |
+
# @@protoc_insertion_point(class_scope:sentencepiece.ModelProto.SentencePiece)
|
| 1497 |
+
},
|
| 1498 |
+
),
|
| 1499 |
+
"DESCRIPTOR": _MODELPROTO,
|
| 1500 |
+
"__module__": "sentencepiece_model_pb2",
|
| 1501 |
+
# @@protoc_insertion_point(class_scope:sentencepiece.ModelProto)
|
| 1502 |
+
},
|
| 1503 |
+
)
|
| 1504 |
+
_sym_db.RegisterMessage(ModelProto)
|
| 1505 |
+
_sym_db.RegisterMessage(ModelProto.SentencePiece)
|
| 1506 |
+
|
| 1507 |
+
|
| 1508 |
+
DESCRIPTOR._options = None
|
| 1509 |
+
_TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
|
| 1510 |
+
_TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
|
| 1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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 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 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
| 21 |
+
|
| 22 |
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
| 23 |
+
from ...loaders import IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
| 24 |
+
from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel, UNetMotionModel
|
| 25 |
+
from ...models.lora import adjust_lora_scale_text_encoder
|
| 26 |
+
from ...models.unets.unet_motion_model import MotionAdapter
|
| 27 |
+
from ...schedulers import (
|
| 28 |
+
DDIMScheduler,
|
| 29 |
+
DPMSolverMultistepScheduler,
|
| 30 |
+
EulerAncestralDiscreteScheduler,
|
| 31 |
+
EulerDiscreteScheduler,
|
| 32 |
+
LMSDiscreteScheduler,
|
| 33 |
+
PNDMScheduler,
|
| 34 |
+
)
|
| 35 |
+
from ...utils import (
|
| 36 |
+
USE_PEFT_BACKEND,
|
| 37 |
+
deprecate,
|
| 38 |
+
logging,
|
| 39 |
+
replace_example_docstring,
|
| 40 |
+
scale_lora_layers,
|
| 41 |
+
unscale_lora_layers,
|
| 42 |
+
)
|
| 43 |
+
from ...utils.torch_utils import randn_tensor
|
| 44 |
+
from ..free_init_utils import FreeInitMixin
|
| 45 |
+
from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
| 46 |
+
from .pipeline_output import AnimateDiffPipelineOutput
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 50 |
+
|
| 51 |
+
EXAMPLE_DOC_STRING = """
|
| 52 |
+
Examples:
|
| 53 |
+
```py
|
| 54 |
+
>>> import torch
|
| 55 |
+
>>> from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
|
| 56 |
+
>>> from diffusers.utils import export_to_gif
|
| 57 |
+
|
| 58 |
+
>>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
|
| 59 |
+
>>> pipe = AnimateDiffPipeline.from_pretrained("frankjoshua/toonyou_beta6", motion_adapter=adapter)
|
| 60 |
+
>>> pipe.scheduler = DDIMScheduler(beta_schedule="linear", steps_offset=1, clip_sample=False)
|
| 61 |
+
>>> output = pipe(prompt="A corgi walking in the park")
|
| 62 |
+
>>> frames = output.frames[0]
|
| 63 |
+
>>> export_to_gif(frames, "animation.gif")
|
| 64 |
+
```
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def tensor2vid(video: torch.Tensor, processor: "VaeImageProcessor", output_type: str = "np"):
|
| 69 |
+
batch_size, channels, num_frames, height, width = video.shape
|
| 70 |
+
outputs = []
|
| 71 |
+
for batch_idx in range(batch_size):
|
| 72 |
+
batch_vid = video[batch_idx].permute(1, 0, 2, 3)
|
| 73 |
+
batch_output = processor.postprocess(batch_vid, output_type)
|
| 74 |
+
|
| 75 |
+
outputs.append(batch_output)
|
| 76 |
+
|
| 77 |
+
if output_type == "np":
|
| 78 |
+
outputs = np.stack(outputs)
|
| 79 |
+
|
| 80 |
+
elif output_type == "pt":
|
| 81 |
+
outputs = torch.stack(outputs)
|
| 82 |
+
|
| 83 |
+
elif not output_type == "pil":
|
| 84 |
+
raise ValueError(f"{output_type} does not exist. Please choose one of ['np', 'pt', 'pil']")
|
| 85 |
+
|
| 86 |
+
return outputs
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class AnimateDiffPipeline(
|
| 90 |
+
DiffusionPipeline,
|
| 91 |
+
StableDiffusionMixin,
|
| 92 |
+
TextualInversionLoaderMixin,
|
| 93 |
+
IPAdapterMixin,
|
| 94 |
+
LoraLoaderMixin,
|
| 95 |
+
FreeInitMixin,
|
| 96 |
+
):
|
| 97 |
+
r"""
|
| 98 |
+
Pipeline for text-to-video generation.
|
| 99 |
+
|
| 100 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 101 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 102 |
+
|
| 103 |
+
The pipeline also inherits the following loading methods:
|
| 104 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 105 |
+
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
| 106 |
+
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
| 107 |
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
vae ([`AutoencoderKL`]):
|
| 111 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 112 |
+
text_encoder ([`CLIPTextModel`]):
|
| 113 |
+
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
| 114 |
+
tokenizer (`CLIPTokenizer`):
|
| 115 |
+
A [`~transformers.CLIPTokenizer`] to tokenize text.
|
| 116 |
+
unet ([`UNet2DConditionModel`]):
|
| 117 |
+
A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
|
| 118 |
+
motion_adapter ([`MotionAdapter`]):
|
| 119 |
+
A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
|
| 120 |
+
scheduler ([`SchedulerMixin`]):
|
| 121 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 122 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
| 126 |
+
_optional_components = ["feature_extractor", "image_encoder", "motion_adapter"]
|
| 127 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 128 |
+
|
| 129 |
+
def __init__(
|
| 130 |
+
self,
|
| 131 |
+
vae: AutoencoderKL,
|
| 132 |
+
text_encoder: CLIPTextModel,
|
| 133 |
+
tokenizer: CLIPTokenizer,
|
| 134 |
+
unet: UNet2DConditionModel,
|
| 135 |
+
motion_adapter: MotionAdapter,
|
| 136 |
+
scheduler: Union[
|
| 137 |
+
DDIMScheduler,
|
| 138 |
+
PNDMScheduler,
|
| 139 |
+
LMSDiscreteScheduler,
|
| 140 |
+
EulerDiscreteScheduler,
|
| 141 |
+
EulerAncestralDiscreteScheduler,
|
| 142 |
+
DPMSolverMultistepScheduler,
|
| 143 |
+
],
|
| 144 |
+
feature_extractor: CLIPImageProcessor = None,
|
| 145 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
| 146 |
+
):
|
| 147 |
+
super().__init__()
|
| 148 |
+
if isinstance(unet, UNet2DConditionModel):
|
| 149 |
+
unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
|
| 150 |
+
|
| 151 |
+
self.register_modules(
|
| 152 |
+
vae=vae,
|
| 153 |
+
text_encoder=text_encoder,
|
| 154 |
+
tokenizer=tokenizer,
|
| 155 |
+
unet=unet,
|
| 156 |
+
motion_adapter=motion_adapter,
|
| 157 |
+
scheduler=scheduler,
|
| 158 |
+
feature_extractor=feature_extractor,
|
| 159 |
+
image_encoder=image_encoder,
|
| 160 |
+
)
|
| 161 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 162 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 163 |
+
|
| 164 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
|
| 165 |
+
def encode_prompt(
|
| 166 |
+
self,
|
| 167 |
+
prompt,
|
| 168 |
+
device,
|
| 169 |
+
num_images_per_prompt,
|
| 170 |
+
do_classifier_free_guidance,
|
| 171 |
+
negative_prompt=None,
|
| 172 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 173 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 174 |
+
lora_scale: Optional[float] = None,
|
| 175 |
+
clip_skip: Optional[int] = None,
|
| 176 |
+
):
|
| 177 |
+
r"""
|
| 178 |
+
Encodes the prompt into text encoder hidden states.
|
| 179 |
+
|
| 180 |
+
Args:
|
| 181 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 182 |
+
prompt to be encoded
|
| 183 |
+
device: (`torch.device`):
|
| 184 |
+
torch device
|
| 185 |
+
num_images_per_prompt (`int`):
|
| 186 |
+
number of images that should be generated per prompt
|
| 187 |
+
do_classifier_free_guidance (`bool`):
|
| 188 |
+
whether to use classifier free guidance or not
|
| 189 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 190 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 191 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 192 |
+
less than `1`).
|
| 193 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 194 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 195 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 196 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 197 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 198 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 199 |
+
argument.
|
| 200 |
+
lora_scale (`float`, *optional*):
|
| 201 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 202 |
+
clip_skip (`int`, *optional*):
|
| 203 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 204 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 205 |
+
"""
|
| 206 |
+
# set lora scale so that monkey patched LoRA
|
| 207 |
+
# function of text encoder can correctly access it
|
| 208 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 209 |
+
self._lora_scale = lora_scale
|
| 210 |
+
|
| 211 |
+
# dynamically adjust the LoRA scale
|
| 212 |
+
if not USE_PEFT_BACKEND:
|
| 213 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 214 |
+
else:
|
| 215 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 216 |
+
|
| 217 |
+
if prompt is not None and isinstance(prompt, str):
|
| 218 |
+
batch_size = 1
|
| 219 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 220 |
+
batch_size = len(prompt)
|
| 221 |
+
else:
|
| 222 |
+
batch_size = prompt_embeds.shape[0]
|
| 223 |
+
|
| 224 |
+
if prompt_embeds is None:
|
| 225 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 226 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 227 |
+
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 228 |
+
|
| 229 |
+
text_inputs = self.tokenizer(
|
| 230 |
+
prompt,
|
| 231 |
+
padding="max_length",
|
| 232 |
+
max_length=self.tokenizer.model_max_length,
|
| 233 |
+
truncation=True,
|
| 234 |
+
return_tensors="pt",
|
| 235 |
+
)
|
| 236 |
+
text_input_ids = text_inputs.input_ids
|
| 237 |
+
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
| 238 |
+
|
| 239 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 240 |
+
text_input_ids, untruncated_ids
|
| 241 |
+
):
|
| 242 |
+
removed_text = self.tokenizer.batch_decode(
|
| 243 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 244 |
+
)
|
| 245 |
+
logger.warning(
|
| 246 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 247 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 251 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 252 |
+
else:
|
| 253 |
+
attention_mask = None
|
| 254 |
+
|
| 255 |
+
if clip_skip is None:
|
| 256 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 257 |
+
prompt_embeds = prompt_embeds[0]
|
| 258 |
+
else:
|
| 259 |
+
prompt_embeds = self.text_encoder(
|
| 260 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 261 |
+
)
|
| 262 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 263 |
+
# all the hidden states from the encoder layers. Then index into
|
| 264 |
+
# the tuple to access the hidden states from the desired layer.
|
| 265 |
+
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
|
| 266 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 267 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 268 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 269 |
+
# layer.
|
| 270 |
+
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
|
| 271 |
+
|
| 272 |
+
if self.text_encoder is not None:
|
| 273 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 274 |
+
elif self.unet is not None:
|
| 275 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 276 |
+
else:
|
| 277 |
+
prompt_embeds_dtype = prompt_embeds.dtype
|
| 278 |
+
|
| 279 |
+
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 280 |
+
|
| 281 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 282 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 283 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 284 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 285 |
+
|
| 286 |
+
# get unconditional embeddings for classifier free guidance
|
| 287 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 288 |
+
uncond_tokens: List[str]
|
| 289 |
+
if negative_prompt is None:
|
| 290 |
+
uncond_tokens = [""] * batch_size
|
| 291 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 292 |
+
raise TypeError(
|
| 293 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 294 |
+
f" {type(prompt)}."
|
| 295 |
+
)
|
| 296 |
+
elif isinstance(negative_prompt, str):
|
| 297 |
+
uncond_tokens = [negative_prompt]
|
| 298 |
+
elif batch_size != len(negative_prompt):
|
| 299 |
+
raise ValueError(
|
| 300 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 301 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 302 |
+
" the batch size of `prompt`."
|
| 303 |
+
)
|
| 304 |
+
else:
|
| 305 |
+
uncond_tokens = negative_prompt
|
| 306 |
+
|
| 307 |
+
# textual inversion: process multi-vector tokens if necessary
|
| 308 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 309 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 310 |
+
|
| 311 |
+
max_length = prompt_embeds.shape[1]
|
| 312 |
+
uncond_input = self.tokenizer(
|
| 313 |
+
uncond_tokens,
|
| 314 |
+
padding="max_length",
|
| 315 |
+
max_length=max_length,
|
| 316 |
+
truncation=True,
|
| 317 |
+
return_tensors="pt",
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 321 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 322 |
+
else:
|
| 323 |
+
attention_mask = None
|
| 324 |
+
|
| 325 |
+
negative_prompt_embeds = self.text_encoder(
|
| 326 |
+
uncond_input.input_ids.to(device),
|
| 327 |
+
attention_mask=attention_mask,
|
| 328 |
+
)
|
| 329 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 330 |
+
|
| 331 |
+
if do_classifier_free_guidance:
|
| 332 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 333 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 334 |
+
|
| 335 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 336 |
+
|
| 337 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 338 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 339 |
+
|
| 340 |
+
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 341 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 342 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 343 |
+
|
| 344 |
+
return prompt_embeds, negative_prompt_embeds
|
| 345 |
+
|
| 346 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
| 347 |
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
| 348 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 349 |
+
|
| 350 |
+
if not isinstance(image, torch.Tensor):
|
| 351 |
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
| 352 |
+
|
| 353 |
+
image = image.to(device=device, dtype=dtype)
|
| 354 |
+
if output_hidden_states:
|
| 355 |
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
| 356 |
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
| 357 |
+
uncond_image_enc_hidden_states = self.image_encoder(
|
| 358 |
+
torch.zeros_like(image), output_hidden_states=True
|
| 359 |
+
).hidden_states[-2]
|
| 360 |
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
| 361 |
+
num_images_per_prompt, dim=0
|
| 362 |
+
)
|
| 363 |
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
| 364 |
+
else:
|
| 365 |
+
image_embeds = self.image_encoder(image).image_embeds
|
| 366 |
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
| 367 |
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
| 368 |
+
|
| 369 |
+
return image_embeds, uncond_image_embeds
|
| 370 |
+
|
| 371 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
| 372 |
+
def prepare_ip_adapter_image_embeds(
|
| 373 |
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
| 374 |
+
):
|
| 375 |
+
if ip_adapter_image_embeds is None:
|
| 376 |
+
if not isinstance(ip_adapter_image, list):
|
| 377 |
+
ip_adapter_image = [ip_adapter_image]
|
| 378 |
+
|
| 379 |
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
| 380 |
+
raise ValueError(
|
| 381 |
+
f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
image_embeds = []
|
| 385 |
+
for single_ip_adapter_image, image_proj_layer in zip(
|
| 386 |
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
| 387 |
+
):
|
| 388 |
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
| 389 |
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
| 390 |
+
single_ip_adapter_image, device, 1, output_hidden_state
|
| 391 |
+
)
|
| 392 |
+
single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
|
| 393 |
+
single_negative_image_embeds = torch.stack(
|
| 394 |
+
[single_negative_image_embeds] * num_images_per_prompt, dim=0
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
if do_classifier_free_guidance:
|
| 398 |
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
|
| 399 |
+
single_image_embeds = single_image_embeds.to(device)
|
| 400 |
+
|
| 401 |
+
image_embeds.append(single_image_embeds)
|
| 402 |
+
else:
|
| 403 |
+
repeat_dims = [1]
|
| 404 |
+
image_embeds = []
|
| 405 |
+
for single_image_embeds in ip_adapter_image_embeds:
|
| 406 |
+
if do_classifier_free_guidance:
|
| 407 |
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
| 408 |
+
single_image_embeds = single_image_embeds.repeat(
|
| 409 |
+
num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
|
| 410 |
+
)
|
| 411 |
+
single_negative_image_embeds = single_negative_image_embeds.repeat(
|
| 412 |
+
num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
|
| 413 |
+
)
|
| 414 |
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
|
| 415 |
+
else:
|
| 416 |
+
single_image_embeds = single_image_embeds.repeat(
|
| 417 |
+
num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
|
| 418 |
+
)
|
| 419 |
+
image_embeds.append(single_image_embeds)
|
| 420 |
+
|
| 421 |
+
return image_embeds
|
| 422 |
+
|
| 423 |
+
# Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
|
| 424 |
+
def decode_latents(self, latents):
|
| 425 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 426 |
+
|
| 427 |
+
batch_size, channels, num_frames, height, width = latents.shape
|
| 428 |
+
latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
|
| 429 |
+
|
| 430 |
+
image = self.vae.decode(latents).sample
|
| 431 |
+
video = image[None, :].reshape((batch_size, num_frames, -1) + image.shape[2:]).permute(0, 2, 1, 3, 4)
|
| 432 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 433 |
+
video = video.float()
|
| 434 |
+
return video
|
| 435 |
+
|
| 436 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 437 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 438 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 439 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 440 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 441 |
+
# and should be between [0, 1]
|
| 442 |
+
|
| 443 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 444 |
+
extra_step_kwargs = {}
|
| 445 |
+
if accepts_eta:
|
| 446 |
+
extra_step_kwargs["eta"] = eta
|
| 447 |
+
|
| 448 |
+
# check if the scheduler accepts generator
|
| 449 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 450 |
+
if accepts_generator:
|
| 451 |
+
extra_step_kwargs["generator"] = generator
|
| 452 |
+
return extra_step_kwargs
|
| 453 |
+
|
| 454 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
|
| 455 |
+
def check_inputs(
|
| 456 |
+
self,
|
| 457 |
+
prompt,
|
| 458 |
+
height,
|
| 459 |
+
width,
|
| 460 |
+
callback_steps,
|
| 461 |
+
negative_prompt=None,
|
| 462 |
+
prompt_embeds=None,
|
| 463 |
+
negative_prompt_embeds=None,
|
| 464 |
+
ip_adapter_image=None,
|
| 465 |
+
ip_adapter_image_embeds=None,
|
| 466 |
+
callback_on_step_end_tensor_inputs=None,
|
| 467 |
+
):
|
| 468 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 469 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 470 |
+
|
| 471 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 472 |
+
raise ValueError(
|
| 473 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 474 |
+
f" {type(callback_steps)}."
|
| 475 |
+
)
|
| 476 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 477 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 478 |
+
):
|
| 479 |
+
raise ValueError(
|
| 480 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
if prompt is not None and prompt_embeds is not None:
|
| 484 |
+
raise ValueError(
|
| 485 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 486 |
+
" only forward one of the two."
|
| 487 |
+
)
|
| 488 |
+
elif prompt is None and prompt_embeds is None:
|
| 489 |
+
raise ValueError(
|
| 490 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 491 |
+
)
|
| 492 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 493 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 494 |
+
|
| 495 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 496 |
+
raise ValueError(
|
| 497 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 498 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 502 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 503 |
+
raise ValueError(
|
| 504 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 505 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 506 |
+
f" {negative_prompt_embeds.shape}."
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
| 510 |
+
raise ValueError(
|
| 511 |
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
if ip_adapter_image_embeds is not None:
|
| 515 |
+
if not isinstance(ip_adapter_image_embeds, list):
|
| 516 |
+
raise ValueError(
|
| 517 |
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
| 518 |
+
)
|
| 519 |
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
| 520 |
+
raise ValueError(
|
| 521 |
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth.TextToVideoSDPipeline.prepare_latents
|
| 525 |
+
def prepare_latents(
|
| 526 |
+
self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
|
| 527 |
+
):
|
| 528 |
+
shape = (
|
| 529 |
+
batch_size,
|
| 530 |
+
num_channels_latents,
|
| 531 |
+
num_frames,
|
| 532 |
+
height // self.vae_scale_factor,
|
| 533 |
+
width // self.vae_scale_factor,
|
| 534 |
+
)
|
| 535 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 536 |
+
raise ValueError(
|
| 537 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 538 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
if latents is None:
|
| 542 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 543 |
+
else:
|
| 544 |
+
latents = latents.to(device)
|
| 545 |
+
|
| 546 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 547 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 548 |
+
return latents
|
| 549 |
+
|
| 550 |
+
@property
|
| 551 |
+
def guidance_scale(self):
|
| 552 |
+
return self._guidance_scale
|
| 553 |
+
|
| 554 |
+
@property
|
| 555 |
+
def clip_skip(self):
|
| 556 |
+
return self._clip_skip
|
| 557 |
+
|
| 558 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 559 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 560 |
+
# corresponds to doing no classifier free guidance.
|
| 561 |
+
@property
|
| 562 |
+
def do_classifier_free_guidance(self):
|
| 563 |
+
return self._guidance_scale > 1
|
| 564 |
+
|
| 565 |
+
@property
|
| 566 |
+
def cross_attention_kwargs(self):
|
| 567 |
+
return self._cross_attention_kwargs
|
| 568 |
+
|
| 569 |
+
@property
|
| 570 |
+
def num_timesteps(self):
|
| 571 |
+
return self._num_timesteps
|
| 572 |
+
|
| 573 |
+
@torch.no_grad()
|
| 574 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 575 |
+
def __call__(
|
| 576 |
+
self,
|
| 577 |
+
prompt: Union[str, List[str]] = None,
|
| 578 |
+
num_frames: Optional[int] = 16,
|
| 579 |
+
height: Optional[int] = None,
|
| 580 |
+
width: Optional[int] = None,
|
| 581 |
+
num_inference_steps: int = 50,
|
| 582 |
+
guidance_scale: float = 7.5,
|
| 583 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 584 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 585 |
+
eta: float = 0.0,
|
| 586 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 587 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 588 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 589 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 590 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 591 |
+
ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
|
| 592 |
+
output_type: Optional[str] = "pil",
|
| 593 |
+
return_dict: bool = True,
|
| 594 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 595 |
+
clip_skip: Optional[int] = None,
|
| 596 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 597 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 598 |
+
**kwargs,
|
| 599 |
+
):
|
| 600 |
+
r"""
|
| 601 |
+
The call function to the pipeline for generation.
|
| 602 |
+
|
| 603 |
+
Args:
|
| 604 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 605 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 606 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 607 |
+
The height in pixels of the generated video.
|
| 608 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 609 |
+
The width in pixels of the generated video.
|
| 610 |
+
num_frames (`int`, *optional*, defaults to 16):
|
| 611 |
+
The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
|
| 612 |
+
amounts to 2 seconds of video.
|
| 613 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 614 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
|
| 615 |
+
expense of slower inference.
|
| 616 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 617 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 618 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 619 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 620 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 621 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 622 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 623 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 624 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 625 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 626 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 627 |
+
generation deterministic.
|
| 628 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 629 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
|
| 630 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 631 |
+
tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
|
| 632 |
+
`(batch_size, num_channel, num_frames, height, width)`.
|
| 633 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 634 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 635 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 636 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 637 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 638 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 639 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*):
|
| 640 |
+
Optional image input to work with IP Adapters.
|
| 641 |
+
ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
|
| 642 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
|
| 643 |
+
Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
|
| 644 |
+
if `do_classifier_free_guidance` is set to `True`.
|
| 645 |
+
If not provided, embeddings are computed from the `ip_adapter_image` input argument.
|
| 646 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 647 |
+
The output format of the generated video. Choose between `torch.FloatTensor`, `PIL.Image` or
|
| 648 |
+
`np.array`.
|
| 649 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 650 |
+
Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
|
| 651 |
+
of a plain tuple.
|
| 652 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 653 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 654 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 655 |
+
clip_skip (`int`, *optional*):
|
| 656 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 657 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 658 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 659 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 660 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 661 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 662 |
+
`callback_on_step_end_tensor_inputs`.
|
| 663 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 664 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 665 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 666 |
+
`._callback_tensor_inputs` attribute of your pipeine class.
|
| 667 |
+
|
| 668 |
+
Examples:
|
| 669 |
+
|
| 670 |
+
Returns:
|
| 671 |
+
[`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] or `tuple`:
|
| 672 |
+
If `return_dict` is `True`, [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] is
|
| 673 |
+
returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
|
| 674 |
+
"""
|
| 675 |
+
|
| 676 |
+
callback = kwargs.pop("callback", None)
|
| 677 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 678 |
+
|
| 679 |
+
if callback is not None:
|
| 680 |
+
deprecate(
|
| 681 |
+
"callback",
|
| 682 |
+
"1.0.0",
|
| 683 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 684 |
+
)
|
| 685 |
+
if callback_steps is not None:
|
| 686 |
+
deprecate(
|
| 687 |
+
"callback_steps",
|
| 688 |
+
"1.0.0",
|
| 689 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
# 0. Default height and width to unet
|
| 693 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 694 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 695 |
+
|
| 696 |
+
num_videos_per_prompt = 1
|
| 697 |
+
|
| 698 |
+
# 1. Check inputs. Raise error if not correct
|
| 699 |
+
self.check_inputs(
|
| 700 |
+
prompt,
|
| 701 |
+
height,
|
| 702 |
+
width,
|
| 703 |
+
callback_steps,
|
| 704 |
+
negative_prompt,
|
| 705 |
+
prompt_embeds,
|
| 706 |
+
negative_prompt_embeds,
|
| 707 |
+
ip_adapter_image,
|
| 708 |
+
ip_adapter_image_embeds,
|
| 709 |
+
callback_on_step_end_tensor_inputs,
|
| 710 |
+
)
|
| 711 |
+
|
| 712 |
+
self._guidance_scale = guidance_scale
|
| 713 |
+
self._clip_skip = clip_skip
|
| 714 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 715 |
+
|
| 716 |
+
# 2. Define call parameters
|
| 717 |
+
if prompt is not None and isinstance(prompt, str):
|
| 718 |
+
batch_size = 1
|
| 719 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 720 |
+
batch_size = len(prompt)
|
| 721 |
+
else:
|
| 722 |
+
batch_size = prompt_embeds.shape[0]
|
| 723 |
+
|
| 724 |
+
device = self._execution_device
|
| 725 |
+
|
| 726 |
+
# 3. Encode input prompt
|
| 727 |
+
text_encoder_lora_scale = (
|
| 728 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 729 |
+
)
|
| 730 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 731 |
+
prompt,
|
| 732 |
+
device,
|
| 733 |
+
num_videos_per_prompt,
|
| 734 |
+
self.do_classifier_free_guidance,
|
| 735 |
+
negative_prompt,
|
| 736 |
+
prompt_embeds=prompt_embeds,
|
| 737 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 738 |
+
lora_scale=text_encoder_lora_scale,
|
| 739 |
+
clip_skip=self.clip_skip,
|
| 740 |
+
)
|
| 741 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 742 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 743 |
+
# to avoid doing two forward passes
|
| 744 |
+
if self.do_classifier_free_guidance:
|
| 745 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 746 |
+
|
| 747 |
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
| 748 |
+
image_embeds = self.prepare_ip_adapter_image_embeds(
|
| 749 |
+
ip_adapter_image,
|
| 750 |
+
ip_adapter_image_embeds,
|
| 751 |
+
device,
|
| 752 |
+
batch_size * num_videos_per_prompt,
|
| 753 |
+
self.do_classifier_free_guidance,
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
# 4. Prepare timesteps
|
| 757 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 758 |
+
timesteps = self.scheduler.timesteps
|
| 759 |
+
|
| 760 |
+
# 5. Prepare latent variables
|
| 761 |
+
num_channels_latents = self.unet.config.in_channels
|
| 762 |
+
latents = self.prepare_latents(
|
| 763 |
+
batch_size * num_videos_per_prompt,
|
| 764 |
+
num_channels_latents,
|
| 765 |
+
num_frames,
|
| 766 |
+
height,
|
| 767 |
+
width,
|
| 768 |
+
prompt_embeds.dtype,
|
| 769 |
+
device,
|
| 770 |
+
generator,
|
| 771 |
+
latents,
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 775 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 776 |
+
|
| 777 |
+
# 7. Add image embeds for IP-Adapter
|
| 778 |
+
added_cond_kwargs = (
|
| 779 |
+
{"image_embeds": image_embeds}
|
| 780 |
+
if ip_adapter_image is not None or ip_adapter_image_embeds is not None
|
| 781 |
+
else None
|
| 782 |
+
)
|
| 783 |
+
|
| 784 |
+
num_free_init_iters = self._free_init_num_iters if self.free_init_enabled else 1
|
| 785 |
+
for free_init_iter in range(num_free_init_iters):
|
| 786 |
+
if self.free_init_enabled:
|
| 787 |
+
latents, timesteps = self._apply_free_init(
|
| 788 |
+
latents, free_init_iter, num_inference_steps, device, latents.dtype, generator
|
| 789 |
+
)
|
| 790 |
+
|
| 791 |
+
self._num_timesteps = len(timesteps)
|
| 792 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 793 |
+
|
| 794 |
+
# 8. Denoising loop
|
| 795 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 796 |
+
for i, t in enumerate(timesteps):
|
| 797 |
+
# expand the latents if we are doing classifier free guidance
|
| 798 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 799 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 800 |
+
|
| 801 |
+
# predict the noise residual
|
| 802 |
+
noise_pred = self.unet(
|
| 803 |
+
latent_model_input,
|
| 804 |
+
t,
|
| 805 |
+
encoder_hidden_states=prompt_embeds,
|
| 806 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 807 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 808 |
+
).sample
|
| 809 |
+
|
| 810 |
+
# perform guidance
|
| 811 |
+
if self.do_classifier_free_guidance:
|
| 812 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 813 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 814 |
+
|
| 815 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 816 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
| 817 |
+
|
| 818 |
+
if callback_on_step_end is not None:
|
| 819 |
+
callback_kwargs = {}
|
| 820 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 821 |
+
callback_kwargs[k] = locals()[k]
|
| 822 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 823 |
+
|
| 824 |
+
latents = callback_outputs.pop("latents", latents)
|
| 825 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 826 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 827 |
+
|
| 828 |
+
# call the callback, if provided
|
| 829 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 830 |
+
progress_bar.update()
|
| 831 |
+
if callback is not None and i % callback_steps == 0:
|
| 832 |
+
callback(i, t, latents)
|
| 833 |
+
|
| 834 |
+
# 9. Post processing
|
| 835 |
+
if output_type == "latent":
|
| 836 |
+
video = latents
|
| 837 |
+
else:
|
| 838 |
+
video_tensor = self.decode_latents(latents)
|
| 839 |
+
video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
|
| 840 |
+
|
| 841 |
+
# 10. Offload all models
|
| 842 |
+
self.maybe_free_model_hooks()
|
| 843 |
+
|
| 844 |
+
if not return_dict:
|
| 845 |
+
return (video,)
|
| 846 |
+
|
| 847 |
+
return AnimateDiffPipelineOutput(frames=video)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ...utils import (
|
| 4 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 5 |
+
OptionalDependencyNotAvailable,
|
| 6 |
+
_LazyModule,
|
| 7 |
+
get_objects_from_module,
|
| 8 |
+
is_torch_available,
|
| 9 |
+
is_transformers_available,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_dummy_objects = {}
|
| 14 |
+
_import_structure = {}
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 18 |
+
raise OptionalDependencyNotAvailable()
|
| 19 |
+
except OptionalDependencyNotAvailable:
|
| 20 |
+
from ...utils import dummy_torch_and_transformers_objects # noqa F403
|
| 21 |
+
|
| 22 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
|
| 23 |
+
else:
|
| 24 |
+
_import_structure["pipeline_kandinsky3"] = ["Kandinsky3Pipeline"]
|
| 25 |
+
_import_structure["pipeline_kandinsky3_img2img"] = ["Kandinsky3Img2ImgPipeline"]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 29 |
+
try:
|
| 30 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 31 |
+
raise OptionalDependencyNotAvailable()
|
| 32 |
+
|
| 33 |
+
except OptionalDependencyNotAvailable:
|
| 34 |
+
from ...utils.dummy_torch_and_transformers_objects import *
|
| 35 |
+
else:
|
| 36 |
+
from .pipeline_kandinsky3 import Kandinsky3Pipeline
|
| 37 |
+
from .pipeline_kandinsky3_img2img import Kandinsky3Img2ImgPipeline
|
| 38 |
+
else:
|
| 39 |
+
import sys
|
| 40 |
+
|
| 41 |
+
sys.modules[__name__] = _LazyModule(
|
| 42 |
+
__name__,
|
| 43 |
+
globals()["__file__"],
|
| 44 |
+
_import_structure,
|
| 45 |
+
module_spec=__spec__,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
for name, value in _dummy_objects.items():
|
| 49 |
+
setattr(sys.modules[__name__], name, value)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.14 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/convert_kandinsky3_unet.cpython-310.pyc
ADDED
|
Binary file (2.66 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/pipeline_kandinsky3.cpython-310.pyc
ADDED
|
Binary file (19.1 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/__pycache__/pipeline_kandinsky3_img2img.cpython-310.pyc
ADDED
|
Binary file (21.6 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Dict, List, Optional, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import T5EncoderModel, T5Tokenizer
|
| 5 |
+
|
| 6 |
+
from ...loaders import LoraLoaderMixin
|
| 7 |
+
from ...models import Kandinsky3UNet, VQModel
|
| 8 |
+
from ...schedulers import DDPMScheduler
|
| 9 |
+
from ...utils import (
|
| 10 |
+
deprecate,
|
| 11 |
+
is_accelerate_available,
|
| 12 |
+
logging,
|
| 13 |
+
replace_example_docstring,
|
| 14 |
+
)
|
| 15 |
+
from ...utils.torch_utils import randn_tensor
|
| 16 |
+
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 20 |
+
|
| 21 |
+
EXAMPLE_DOC_STRING = """
|
| 22 |
+
Examples:
|
| 23 |
+
```py
|
| 24 |
+
>>> from diffusers import AutoPipelineForText2Image
|
| 25 |
+
>>> import torch
|
| 26 |
+
|
| 27 |
+
>>> pipe = AutoPipelineForText2Image.from_pretrained("kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16)
|
| 28 |
+
>>> pipe.enable_model_cpu_offload()
|
| 29 |
+
|
| 30 |
+
>>> prompt = "A photograph of the inside of a subway train. There are raccoons sitting on the seats. One of them is reading a newspaper. The window shows the city in the background."
|
| 31 |
+
|
| 32 |
+
>>> generator = torch.Generator(device="cpu").manual_seed(0)
|
| 33 |
+
>>> image = pipe(prompt, num_inference_steps=25, generator=generator).images[0]
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def downscale_height_and_width(height, width, scale_factor=8):
|
| 40 |
+
new_height = height // scale_factor**2
|
| 41 |
+
if height % scale_factor**2 != 0:
|
| 42 |
+
new_height += 1
|
| 43 |
+
new_width = width // scale_factor**2
|
| 44 |
+
if width % scale_factor**2 != 0:
|
| 45 |
+
new_width += 1
|
| 46 |
+
return new_height * scale_factor, new_width * scale_factor
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Kandinsky3Pipeline(DiffusionPipeline, LoraLoaderMixin):
|
| 50 |
+
model_cpu_offload_seq = "text_encoder->unet->movq"
|
| 51 |
+
_callback_tensor_inputs = [
|
| 52 |
+
"latents",
|
| 53 |
+
"prompt_embeds",
|
| 54 |
+
"negative_prompt_embeds",
|
| 55 |
+
"negative_attention_mask",
|
| 56 |
+
"attention_mask",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
tokenizer: T5Tokenizer,
|
| 62 |
+
text_encoder: T5EncoderModel,
|
| 63 |
+
unet: Kandinsky3UNet,
|
| 64 |
+
scheduler: DDPMScheduler,
|
| 65 |
+
movq: VQModel,
|
| 66 |
+
):
|
| 67 |
+
super().__init__()
|
| 68 |
+
|
| 69 |
+
self.register_modules(
|
| 70 |
+
tokenizer=tokenizer, text_encoder=text_encoder, unet=unet, scheduler=scheduler, movq=movq
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def remove_all_hooks(self):
|
| 74 |
+
if is_accelerate_available():
|
| 75 |
+
from accelerate.hooks import remove_hook_from_module
|
| 76 |
+
else:
|
| 77 |
+
raise ImportError("Please install accelerate via `pip install accelerate`")
|
| 78 |
+
|
| 79 |
+
for model in [self.text_encoder, self.unet, self.movq]:
|
| 80 |
+
if model is not None:
|
| 81 |
+
remove_hook_from_module(model, recurse=True)
|
| 82 |
+
|
| 83 |
+
self.unet_offload_hook = None
|
| 84 |
+
self.text_encoder_offload_hook = None
|
| 85 |
+
self.final_offload_hook = None
|
| 86 |
+
|
| 87 |
+
def process_embeds(self, embeddings, attention_mask, cut_context):
|
| 88 |
+
if cut_context:
|
| 89 |
+
embeddings[attention_mask == 0] = torch.zeros_like(embeddings[attention_mask == 0])
|
| 90 |
+
max_seq_length = attention_mask.sum(-1).max() + 1
|
| 91 |
+
embeddings = embeddings[:, :max_seq_length]
|
| 92 |
+
attention_mask = attention_mask[:, :max_seq_length]
|
| 93 |
+
return embeddings, attention_mask
|
| 94 |
+
|
| 95 |
+
@torch.no_grad()
|
| 96 |
+
def encode_prompt(
|
| 97 |
+
self,
|
| 98 |
+
prompt,
|
| 99 |
+
do_classifier_free_guidance=True,
|
| 100 |
+
num_images_per_prompt=1,
|
| 101 |
+
device=None,
|
| 102 |
+
negative_prompt=None,
|
| 103 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 104 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 105 |
+
_cut_context=False,
|
| 106 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 107 |
+
negative_attention_mask: Optional[torch.FloatTensor] = None,
|
| 108 |
+
):
|
| 109 |
+
r"""
|
| 110 |
+
Encodes the prompt into text encoder hidden states.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 114 |
+
prompt to be encoded
|
| 115 |
+
device: (`torch.device`, *optional*):
|
| 116 |
+
torch device to place the resulting embeddings on
|
| 117 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 118 |
+
number of images that should be generated per prompt
|
| 119 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 120 |
+
whether to use classifier free guidance or not
|
| 121 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 122 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 123 |
+
`negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
|
| 124 |
+
Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
|
| 125 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 126 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 127 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 128 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 129 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 130 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 131 |
+
argument.
|
| 132 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 133 |
+
Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
|
| 134 |
+
negative_attention_mask (`torch.FloatTensor`, *optional*):
|
| 135 |
+
Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
|
| 136 |
+
"""
|
| 137 |
+
if prompt is not None and negative_prompt is not None:
|
| 138 |
+
if type(prompt) is not type(negative_prompt):
|
| 139 |
+
raise TypeError(
|
| 140 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 141 |
+
f" {type(prompt)}."
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if device is None:
|
| 145 |
+
device = self._execution_device
|
| 146 |
+
|
| 147 |
+
if prompt is not None and isinstance(prompt, str):
|
| 148 |
+
batch_size = 1
|
| 149 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 150 |
+
batch_size = len(prompt)
|
| 151 |
+
else:
|
| 152 |
+
batch_size = prompt_embeds.shape[0]
|
| 153 |
+
|
| 154 |
+
max_length = 128
|
| 155 |
+
|
| 156 |
+
if prompt_embeds is None:
|
| 157 |
+
text_inputs = self.tokenizer(
|
| 158 |
+
prompt,
|
| 159 |
+
padding="max_length",
|
| 160 |
+
max_length=max_length,
|
| 161 |
+
truncation=True,
|
| 162 |
+
return_tensors="pt",
|
| 163 |
+
)
|
| 164 |
+
text_input_ids = text_inputs.input_ids.to(device)
|
| 165 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 166 |
+
prompt_embeds = self.text_encoder(
|
| 167 |
+
text_input_ids,
|
| 168 |
+
attention_mask=attention_mask,
|
| 169 |
+
)
|
| 170 |
+
prompt_embeds = prompt_embeds[0]
|
| 171 |
+
prompt_embeds, attention_mask = self.process_embeds(prompt_embeds, attention_mask, _cut_context)
|
| 172 |
+
prompt_embeds = prompt_embeds * attention_mask.unsqueeze(2)
|
| 173 |
+
|
| 174 |
+
if self.text_encoder is not None:
|
| 175 |
+
dtype = self.text_encoder.dtype
|
| 176 |
+
else:
|
| 177 |
+
dtype = None
|
| 178 |
+
|
| 179 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 180 |
+
|
| 181 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 182 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 183 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 184 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 185 |
+
attention_mask = attention_mask.repeat(num_images_per_prompt, 1)
|
| 186 |
+
# get unconditional embeddings for classifier free guidance
|
| 187 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 188 |
+
uncond_tokens: List[str]
|
| 189 |
+
|
| 190 |
+
if negative_prompt is None:
|
| 191 |
+
uncond_tokens = [""] * batch_size
|
| 192 |
+
elif isinstance(negative_prompt, str):
|
| 193 |
+
uncond_tokens = [negative_prompt]
|
| 194 |
+
elif batch_size != len(negative_prompt):
|
| 195 |
+
raise ValueError(
|
| 196 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 197 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 198 |
+
" the batch size of `prompt`."
|
| 199 |
+
)
|
| 200 |
+
else:
|
| 201 |
+
uncond_tokens = negative_prompt
|
| 202 |
+
if negative_prompt is not None:
|
| 203 |
+
uncond_input = self.tokenizer(
|
| 204 |
+
uncond_tokens,
|
| 205 |
+
padding="max_length",
|
| 206 |
+
max_length=128,
|
| 207 |
+
truncation=True,
|
| 208 |
+
return_attention_mask=True,
|
| 209 |
+
return_tensors="pt",
|
| 210 |
+
)
|
| 211 |
+
text_input_ids = uncond_input.input_ids.to(device)
|
| 212 |
+
negative_attention_mask = uncond_input.attention_mask.to(device)
|
| 213 |
+
|
| 214 |
+
negative_prompt_embeds = self.text_encoder(
|
| 215 |
+
text_input_ids,
|
| 216 |
+
attention_mask=negative_attention_mask,
|
| 217 |
+
)
|
| 218 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 219 |
+
negative_prompt_embeds = negative_prompt_embeds[:, : prompt_embeds.shape[1]]
|
| 220 |
+
negative_attention_mask = negative_attention_mask[:, : prompt_embeds.shape[1]]
|
| 221 |
+
negative_prompt_embeds = negative_prompt_embeds * negative_attention_mask.unsqueeze(2)
|
| 222 |
+
|
| 223 |
+
else:
|
| 224 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
| 225 |
+
negative_attention_mask = torch.zeros_like(attention_mask)
|
| 226 |
+
|
| 227 |
+
if do_classifier_free_guidance:
|
| 228 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 229 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 230 |
+
|
| 231 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
|
| 232 |
+
if negative_prompt_embeds.shape != prompt_embeds.shape:
|
| 233 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 234 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 235 |
+
negative_attention_mask = negative_attention_mask.repeat(num_images_per_prompt, 1)
|
| 236 |
+
|
| 237 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 238 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 239 |
+
# to avoid doing two forward passes
|
| 240 |
+
else:
|
| 241 |
+
negative_prompt_embeds = None
|
| 242 |
+
negative_attention_mask = None
|
| 243 |
+
return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask
|
| 244 |
+
|
| 245 |
+
def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
|
| 246 |
+
if latents is None:
|
| 247 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 248 |
+
else:
|
| 249 |
+
if latents.shape != shape:
|
| 250 |
+
raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
|
| 251 |
+
latents = latents.to(device)
|
| 252 |
+
|
| 253 |
+
latents = latents * scheduler.init_noise_sigma
|
| 254 |
+
return latents
|
| 255 |
+
|
| 256 |
+
def check_inputs(
|
| 257 |
+
self,
|
| 258 |
+
prompt,
|
| 259 |
+
callback_steps,
|
| 260 |
+
negative_prompt=None,
|
| 261 |
+
prompt_embeds=None,
|
| 262 |
+
negative_prompt_embeds=None,
|
| 263 |
+
callback_on_step_end_tensor_inputs=None,
|
| 264 |
+
attention_mask=None,
|
| 265 |
+
negative_attention_mask=None,
|
| 266 |
+
):
|
| 267 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 268 |
+
raise ValueError(
|
| 269 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 270 |
+
f" {type(callback_steps)}."
|
| 271 |
+
)
|
| 272 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 273 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 274 |
+
):
|
| 275 |
+
raise ValueError(
|
| 276 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
if prompt is not None and prompt_embeds is not None:
|
| 280 |
+
raise ValueError(
|
| 281 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 282 |
+
" only forward one of the two."
|
| 283 |
+
)
|
| 284 |
+
elif prompt is None and prompt_embeds is None:
|
| 285 |
+
raise ValueError(
|
| 286 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 287 |
+
)
|
| 288 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 289 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 290 |
+
|
| 291 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 292 |
+
raise ValueError(
|
| 293 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 294 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 298 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 299 |
+
raise ValueError(
|
| 300 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 301 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 302 |
+
f" {negative_prompt_embeds.shape}."
|
| 303 |
+
)
|
| 304 |
+
if negative_prompt_embeds is not None and negative_attention_mask is None:
|
| 305 |
+
raise ValueError("Please provide `negative_attention_mask` along with `negative_prompt_embeds`")
|
| 306 |
+
|
| 307 |
+
if negative_prompt_embeds is not None and negative_attention_mask is not None:
|
| 308 |
+
if negative_prompt_embeds.shape[:2] != negative_attention_mask.shape:
|
| 309 |
+
raise ValueError(
|
| 310 |
+
"`negative_prompt_embeds` and `negative_attention_mask` must have the same batch_size and token length when passed directly, but"
|
| 311 |
+
f" got: `negative_prompt_embeds` {negative_prompt_embeds.shape[:2]} != `negative_attention_mask`"
|
| 312 |
+
f" {negative_attention_mask.shape}."
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
if prompt_embeds is not None and attention_mask is None:
|
| 316 |
+
raise ValueError("Please provide `attention_mask` along with `prompt_embeds`")
|
| 317 |
+
|
| 318 |
+
if prompt_embeds is not None and attention_mask is not None:
|
| 319 |
+
if prompt_embeds.shape[:2] != attention_mask.shape:
|
| 320 |
+
raise ValueError(
|
| 321 |
+
"`prompt_embeds` and `attention_mask` must have the same batch_size and token length when passed directly, but"
|
| 322 |
+
f" got: `prompt_embeds` {prompt_embeds.shape[:2]} != `attention_mask`"
|
| 323 |
+
f" {attention_mask.shape}."
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
@property
|
| 327 |
+
def guidance_scale(self):
|
| 328 |
+
return self._guidance_scale
|
| 329 |
+
|
| 330 |
+
@property
|
| 331 |
+
def do_classifier_free_guidance(self):
|
| 332 |
+
return self._guidance_scale > 1
|
| 333 |
+
|
| 334 |
+
@property
|
| 335 |
+
def num_timesteps(self):
|
| 336 |
+
return self._num_timesteps
|
| 337 |
+
|
| 338 |
+
@torch.no_grad()
|
| 339 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 340 |
+
def __call__(
|
| 341 |
+
self,
|
| 342 |
+
prompt: Union[str, List[str]] = None,
|
| 343 |
+
num_inference_steps: int = 25,
|
| 344 |
+
guidance_scale: float = 3.0,
|
| 345 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 346 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 347 |
+
height: Optional[int] = 1024,
|
| 348 |
+
width: Optional[int] = 1024,
|
| 349 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 350 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 351 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 352 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 353 |
+
negative_attention_mask: Optional[torch.FloatTensor] = None,
|
| 354 |
+
output_type: Optional[str] = "pil",
|
| 355 |
+
return_dict: bool = True,
|
| 356 |
+
latents=None,
|
| 357 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 358 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 359 |
+
**kwargs,
|
| 360 |
+
):
|
| 361 |
+
"""
|
| 362 |
+
Function invoked when calling the pipeline for generation.
|
| 363 |
+
|
| 364 |
+
Args:
|
| 365 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 366 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 367 |
+
instead.
|
| 368 |
+
num_inference_steps (`int`, *optional*, defaults to 25):
|
| 369 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 370 |
+
expense of slower inference.
|
| 371 |
+
timesteps (`List[int]`, *optional*):
|
| 372 |
+
Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
|
| 373 |
+
timesteps are used. Must be in descending order.
|
| 374 |
+
guidance_scale (`float`, *optional*, defaults to 3.0):
|
| 375 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 376 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 377 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 378 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 379 |
+
usually at the expense of lower image quality.
|
| 380 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 381 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 382 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 383 |
+
less than `1`).
|
| 384 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 385 |
+
The number of images to generate per prompt.
|
| 386 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size):
|
| 387 |
+
The height in pixels of the generated image.
|
| 388 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size):
|
| 389 |
+
The width in pixels of the generated image.
|
| 390 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 391 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 392 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 393 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 394 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 395 |
+
to make generation deterministic.
|
| 396 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 397 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 398 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 399 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 400 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 401 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 402 |
+
argument.
|
| 403 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 404 |
+
Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
|
| 405 |
+
negative_attention_mask (`torch.FloatTensor`, *optional*):
|
| 406 |
+
Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
|
| 407 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 408 |
+
The output format of the generate image. Choose between
|
| 409 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 410 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 411 |
+
Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
|
| 412 |
+
callback (`Callable`, *optional*):
|
| 413 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
| 414 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 415 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 416 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
| 417 |
+
called at every step.
|
| 418 |
+
clean_caption (`bool`, *optional*, defaults to `True`):
|
| 419 |
+
Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
|
| 420 |
+
be installed. If the dependencies are not installed, the embeddings will be created from the raw
|
| 421 |
+
prompt.
|
| 422 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 423 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 424 |
+
`self.processor` in
|
| 425 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 426 |
+
|
| 427 |
+
Examples:
|
| 428 |
+
|
| 429 |
+
Returns:
|
| 430 |
+
[`~pipelines.ImagePipelineOutput`] or `tuple`
|
| 431 |
+
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
callback = kwargs.pop("callback", None)
|
| 435 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 436 |
+
|
| 437 |
+
if callback is not None:
|
| 438 |
+
deprecate(
|
| 439 |
+
"callback",
|
| 440 |
+
"1.0.0",
|
| 441 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
| 442 |
+
)
|
| 443 |
+
if callback_steps is not None:
|
| 444 |
+
deprecate(
|
| 445 |
+
"callback_steps",
|
| 446 |
+
"1.0.0",
|
| 447 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 451 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 452 |
+
):
|
| 453 |
+
raise ValueError(
|
| 454 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
cut_context = True
|
| 458 |
+
device = self._execution_device
|
| 459 |
+
|
| 460 |
+
# 1. Check inputs. Raise error if not correct
|
| 461 |
+
self.check_inputs(
|
| 462 |
+
prompt,
|
| 463 |
+
callback_steps,
|
| 464 |
+
negative_prompt,
|
| 465 |
+
prompt_embeds,
|
| 466 |
+
negative_prompt_embeds,
|
| 467 |
+
callback_on_step_end_tensor_inputs,
|
| 468 |
+
attention_mask,
|
| 469 |
+
negative_attention_mask,
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
self._guidance_scale = guidance_scale
|
| 473 |
+
|
| 474 |
+
if prompt is not None and isinstance(prompt, str):
|
| 475 |
+
batch_size = 1
|
| 476 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 477 |
+
batch_size = len(prompt)
|
| 478 |
+
else:
|
| 479 |
+
batch_size = prompt_embeds.shape[0]
|
| 480 |
+
|
| 481 |
+
# 3. Encode input prompt
|
| 482 |
+
prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask = self.encode_prompt(
|
| 483 |
+
prompt,
|
| 484 |
+
self.do_classifier_free_guidance,
|
| 485 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 486 |
+
device=device,
|
| 487 |
+
negative_prompt=negative_prompt,
|
| 488 |
+
prompt_embeds=prompt_embeds,
|
| 489 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 490 |
+
_cut_context=cut_context,
|
| 491 |
+
attention_mask=attention_mask,
|
| 492 |
+
negative_attention_mask=negative_attention_mask,
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
if self.do_classifier_free_guidance:
|
| 496 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 497 |
+
attention_mask = torch.cat([negative_attention_mask, attention_mask]).bool()
|
| 498 |
+
# 4. Prepare timesteps
|
| 499 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 500 |
+
timesteps = self.scheduler.timesteps
|
| 501 |
+
|
| 502 |
+
# 5. Prepare latents
|
| 503 |
+
height, width = downscale_height_and_width(height, width, 8)
|
| 504 |
+
|
| 505 |
+
latents = self.prepare_latents(
|
| 506 |
+
(batch_size * num_images_per_prompt, 4, height, width),
|
| 507 |
+
prompt_embeds.dtype,
|
| 508 |
+
device,
|
| 509 |
+
generator,
|
| 510 |
+
latents,
|
| 511 |
+
self.scheduler,
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
if hasattr(self, "text_encoder_offload_hook") and self.text_encoder_offload_hook is not None:
|
| 515 |
+
self.text_encoder_offload_hook.offload()
|
| 516 |
+
|
| 517 |
+
# 7. Denoising loop
|
| 518 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 519 |
+
self._num_timesteps = len(timesteps)
|
| 520 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 521 |
+
for i, t in enumerate(timesteps):
|
| 522 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 523 |
+
|
| 524 |
+
# predict the noise residual
|
| 525 |
+
noise_pred = self.unet(
|
| 526 |
+
latent_model_input,
|
| 527 |
+
t,
|
| 528 |
+
encoder_hidden_states=prompt_embeds,
|
| 529 |
+
encoder_attention_mask=attention_mask,
|
| 530 |
+
return_dict=False,
|
| 531 |
+
)[0]
|
| 532 |
+
|
| 533 |
+
if self.do_classifier_free_guidance:
|
| 534 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 535 |
+
|
| 536 |
+
noise_pred = (guidance_scale + 1.0) * noise_pred_text - guidance_scale * noise_pred_uncond
|
| 537 |
+
# noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 538 |
+
|
| 539 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 540 |
+
latents = self.scheduler.step(
|
| 541 |
+
noise_pred,
|
| 542 |
+
t,
|
| 543 |
+
latents,
|
| 544 |
+
generator=generator,
|
| 545 |
+
).prev_sample
|
| 546 |
+
|
| 547 |
+
if callback_on_step_end is not None:
|
| 548 |
+
callback_kwargs = {}
|
| 549 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 550 |
+
callback_kwargs[k] = locals()[k]
|
| 551 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 552 |
+
|
| 553 |
+
latents = callback_outputs.pop("latents", latents)
|
| 554 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 555 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 556 |
+
attention_mask = callback_outputs.pop("attention_mask", attention_mask)
|
| 557 |
+
negative_attention_mask = callback_outputs.pop("negative_attention_mask", negative_attention_mask)
|
| 558 |
+
|
| 559 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 560 |
+
progress_bar.update()
|
| 561 |
+
if callback is not None and i % callback_steps == 0:
|
| 562 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 563 |
+
callback(step_idx, t, latents)
|
| 564 |
+
|
| 565 |
+
# post-processing
|
| 566 |
+
if output_type not in ["pt", "np", "pil", "latent"]:
|
| 567 |
+
raise ValueError(
|
| 568 |
+
f"Only the output types `pt`, `pil`, `np` and `latent` are supported not output_type={output_type}"
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
if not output_type == "latent":
|
| 572 |
+
image = self.movq.decode(latents, force_not_quantize=True)["sample"]
|
| 573 |
+
|
| 574 |
+
if output_type in ["np", "pil"]:
|
| 575 |
+
image = image * 0.5 + 0.5
|
| 576 |
+
image = image.clamp(0, 1)
|
| 577 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 578 |
+
|
| 579 |
+
if output_type == "pil":
|
| 580 |
+
image = self.numpy_to_pil(image)
|
| 581 |
+
else:
|
| 582 |
+
image = latents
|
| 583 |
+
|
| 584 |
+
self.maybe_free_model_hooks()
|
| 585 |
+
|
| 586 |
+
if not return_dict:
|
| 587 |
+
return (image,)
|
| 588 |
+
|
| 589 |
+
return ImagePipelineOutput(images=image)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from typing import Callable, Dict, List, Optional, Union
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import PIL
|
| 6 |
+
import PIL.Image
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import T5EncoderModel, T5Tokenizer
|
| 9 |
+
|
| 10 |
+
from ...loaders import LoraLoaderMixin
|
| 11 |
+
from ...models import Kandinsky3UNet, VQModel
|
| 12 |
+
from ...schedulers import DDPMScheduler
|
| 13 |
+
from ...utils import (
|
| 14 |
+
deprecate,
|
| 15 |
+
is_accelerate_available,
|
| 16 |
+
logging,
|
| 17 |
+
replace_example_docstring,
|
| 18 |
+
)
|
| 19 |
+
from ...utils.torch_utils import randn_tensor
|
| 20 |
+
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 24 |
+
|
| 25 |
+
EXAMPLE_DOC_STRING = """
|
| 26 |
+
Examples:
|
| 27 |
+
```py
|
| 28 |
+
>>> from diffusers import AutoPipelineForImage2Image
|
| 29 |
+
>>> from diffusers.utils import load_image
|
| 30 |
+
>>> import torch
|
| 31 |
+
|
| 32 |
+
>>> pipe = AutoPipelineForImage2Image.from_pretrained("kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16)
|
| 33 |
+
>>> pipe.enable_model_cpu_offload()
|
| 34 |
+
|
| 35 |
+
>>> prompt = "A painting of the inside of a subway train with tiny raccoons."
|
| 36 |
+
>>> image = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinsky3/t2i.png")
|
| 37 |
+
|
| 38 |
+
>>> generator = torch.Generator(device="cpu").manual_seed(0)
|
| 39 |
+
>>> image = pipe(prompt, image=image, strength=0.75, num_inference_steps=25, generator=generator).images[0]
|
| 40 |
+
```
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def downscale_height_and_width(height, width, scale_factor=8):
|
| 45 |
+
new_height = height // scale_factor**2
|
| 46 |
+
if height % scale_factor**2 != 0:
|
| 47 |
+
new_height += 1
|
| 48 |
+
new_width = width // scale_factor**2
|
| 49 |
+
if width % scale_factor**2 != 0:
|
| 50 |
+
new_width += 1
|
| 51 |
+
return new_height * scale_factor, new_width * scale_factor
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def prepare_image(pil_image):
|
| 55 |
+
arr = np.array(pil_image.convert("RGB"))
|
| 56 |
+
arr = arr.astype(np.float32) / 127.5 - 1
|
| 57 |
+
arr = np.transpose(arr, [2, 0, 1])
|
| 58 |
+
image = torch.from_numpy(arr).unsqueeze(0)
|
| 59 |
+
return image
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Kandinsky3Img2ImgPipeline(DiffusionPipeline, LoraLoaderMixin):
|
| 63 |
+
model_cpu_offload_seq = "text_encoder->movq->unet->movq"
|
| 64 |
+
_callback_tensor_inputs = [
|
| 65 |
+
"latents",
|
| 66 |
+
"prompt_embeds",
|
| 67 |
+
"negative_prompt_embeds",
|
| 68 |
+
"negative_attention_mask",
|
| 69 |
+
"attention_mask",
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
tokenizer: T5Tokenizer,
|
| 75 |
+
text_encoder: T5EncoderModel,
|
| 76 |
+
unet: Kandinsky3UNet,
|
| 77 |
+
scheduler: DDPMScheduler,
|
| 78 |
+
movq: VQModel,
|
| 79 |
+
):
|
| 80 |
+
super().__init__()
|
| 81 |
+
|
| 82 |
+
self.register_modules(
|
| 83 |
+
tokenizer=tokenizer, text_encoder=text_encoder, unet=unet, scheduler=scheduler, movq=movq
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def get_timesteps(self, num_inference_steps, strength, device):
|
| 87 |
+
# get the original timestep using init_timestep
|
| 88 |
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
| 89 |
+
|
| 90 |
+
t_start = max(num_inference_steps - init_timestep, 0)
|
| 91 |
+
timesteps = self.scheduler.timesteps[t_start:]
|
| 92 |
+
|
| 93 |
+
return timesteps, num_inference_steps - t_start
|
| 94 |
+
|
| 95 |
+
def remove_all_hooks(self):
|
| 96 |
+
if is_accelerate_available():
|
| 97 |
+
from accelerate.hooks import remove_hook_from_module
|
| 98 |
+
else:
|
| 99 |
+
raise ImportError("Please install accelerate via `pip install accelerate`")
|
| 100 |
+
|
| 101 |
+
for model in [self.text_encoder, self.unet]:
|
| 102 |
+
if model is not None:
|
| 103 |
+
remove_hook_from_module(model, recurse=True)
|
| 104 |
+
|
| 105 |
+
self.unet_offload_hook = None
|
| 106 |
+
self.text_encoder_offload_hook = None
|
| 107 |
+
self.final_offload_hook = None
|
| 108 |
+
|
| 109 |
+
def _process_embeds(self, embeddings, attention_mask, cut_context):
|
| 110 |
+
# return embeddings, attention_mask
|
| 111 |
+
if cut_context:
|
| 112 |
+
embeddings[attention_mask == 0] = torch.zeros_like(embeddings[attention_mask == 0])
|
| 113 |
+
max_seq_length = attention_mask.sum(-1).max() + 1
|
| 114 |
+
embeddings = embeddings[:, :max_seq_length]
|
| 115 |
+
attention_mask = attention_mask[:, :max_seq_length]
|
| 116 |
+
return embeddings, attention_mask
|
| 117 |
+
|
| 118 |
+
@torch.no_grad()
|
| 119 |
+
def encode_prompt(
|
| 120 |
+
self,
|
| 121 |
+
prompt,
|
| 122 |
+
do_classifier_free_guidance=True,
|
| 123 |
+
num_images_per_prompt=1,
|
| 124 |
+
device=None,
|
| 125 |
+
negative_prompt=None,
|
| 126 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 127 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 128 |
+
_cut_context=False,
|
| 129 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 130 |
+
negative_attention_mask: Optional[torch.FloatTensor] = None,
|
| 131 |
+
):
|
| 132 |
+
r"""
|
| 133 |
+
Encodes the prompt into text encoder hidden states.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 137 |
+
prompt to be encoded
|
| 138 |
+
device: (`torch.device`, *optional*):
|
| 139 |
+
torch device to place the resulting embeddings on
|
| 140 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 141 |
+
number of images that should be generated per prompt
|
| 142 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 143 |
+
whether to use classifier free guidance or not
|
| 144 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 145 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 146 |
+
`negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
|
| 147 |
+
Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
|
| 148 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 149 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 150 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 151 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 152 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 153 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 154 |
+
argument.
|
| 155 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 156 |
+
Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
|
| 157 |
+
negative_attention_mask (`torch.FloatTensor`, *optional*):
|
| 158 |
+
Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
|
| 159 |
+
"""
|
| 160 |
+
if prompt is not None and negative_prompt is not None:
|
| 161 |
+
if type(prompt) is not type(negative_prompt):
|
| 162 |
+
raise TypeError(
|
| 163 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 164 |
+
f" {type(prompt)}."
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
if device is None:
|
| 168 |
+
device = self._execution_device
|
| 169 |
+
|
| 170 |
+
if prompt is not None and isinstance(prompt, str):
|
| 171 |
+
batch_size = 1
|
| 172 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 173 |
+
batch_size = len(prompt)
|
| 174 |
+
else:
|
| 175 |
+
batch_size = prompt_embeds.shape[0]
|
| 176 |
+
|
| 177 |
+
max_length = 128
|
| 178 |
+
|
| 179 |
+
if prompt_embeds is None:
|
| 180 |
+
text_inputs = self.tokenizer(
|
| 181 |
+
prompt,
|
| 182 |
+
padding="max_length",
|
| 183 |
+
max_length=max_length,
|
| 184 |
+
truncation=True,
|
| 185 |
+
return_tensors="pt",
|
| 186 |
+
)
|
| 187 |
+
text_input_ids = text_inputs.input_ids.to(device)
|
| 188 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 189 |
+
prompt_embeds = self.text_encoder(
|
| 190 |
+
text_input_ids,
|
| 191 |
+
attention_mask=attention_mask,
|
| 192 |
+
)
|
| 193 |
+
prompt_embeds = prompt_embeds[0]
|
| 194 |
+
prompt_embeds, attention_mask = self._process_embeds(prompt_embeds, attention_mask, _cut_context)
|
| 195 |
+
prompt_embeds = prompt_embeds * attention_mask.unsqueeze(2)
|
| 196 |
+
|
| 197 |
+
if self.text_encoder is not None:
|
| 198 |
+
dtype = self.text_encoder.dtype
|
| 199 |
+
else:
|
| 200 |
+
dtype = None
|
| 201 |
+
|
| 202 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 203 |
+
|
| 204 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 205 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 206 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 207 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 208 |
+
attention_mask = attention_mask.repeat(num_images_per_prompt, 1)
|
| 209 |
+
# get unconditional embeddings for classifier free guidance
|
| 210 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 211 |
+
uncond_tokens: List[str]
|
| 212 |
+
|
| 213 |
+
if negative_prompt is None:
|
| 214 |
+
uncond_tokens = [""] * batch_size
|
| 215 |
+
elif isinstance(negative_prompt, str):
|
| 216 |
+
uncond_tokens = [negative_prompt]
|
| 217 |
+
elif batch_size != len(negative_prompt):
|
| 218 |
+
raise ValueError(
|
| 219 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 220 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 221 |
+
" the batch size of `prompt`."
|
| 222 |
+
)
|
| 223 |
+
else:
|
| 224 |
+
uncond_tokens = negative_prompt
|
| 225 |
+
if negative_prompt is not None:
|
| 226 |
+
uncond_input = self.tokenizer(
|
| 227 |
+
uncond_tokens,
|
| 228 |
+
padding="max_length",
|
| 229 |
+
max_length=128,
|
| 230 |
+
truncation=True,
|
| 231 |
+
return_attention_mask=True,
|
| 232 |
+
return_tensors="pt",
|
| 233 |
+
)
|
| 234 |
+
text_input_ids = uncond_input.input_ids.to(device)
|
| 235 |
+
negative_attention_mask = uncond_input.attention_mask.to(device)
|
| 236 |
+
|
| 237 |
+
negative_prompt_embeds = self.text_encoder(
|
| 238 |
+
text_input_ids,
|
| 239 |
+
attention_mask=negative_attention_mask,
|
| 240 |
+
)
|
| 241 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 242 |
+
negative_prompt_embeds = negative_prompt_embeds[:, : prompt_embeds.shape[1]]
|
| 243 |
+
negative_attention_mask = negative_attention_mask[:, : prompt_embeds.shape[1]]
|
| 244 |
+
negative_prompt_embeds = negative_prompt_embeds * negative_attention_mask.unsqueeze(2)
|
| 245 |
+
|
| 246 |
+
else:
|
| 247 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
| 248 |
+
negative_attention_mask = torch.zeros_like(attention_mask)
|
| 249 |
+
|
| 250 |
+
if do_classifier_free_guidance:
|
| 251 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 252 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 253 |
+
|
| 254 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
|
| 255 |
+
if negative_prompt_embeds.shape != prompt_embeds.shape:
|
| 256 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 257 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 258 |
+
negative_attention_mask = negative_attention_mask.repeat(num_images_per_prompt, 1)
|
| 259 |
+
|
| 260 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 261 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 262 |
+
# to avoid doing two forward passes
|
| 263 |
+
else:
|
| 264 |
+
negative_prompt_embeds = None
|
| 265 |
+
negative_attention_mask = None
|
| 266 |
+
return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask
|
| 267 |
+
|
| 268 |
+
def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
|
| 269 |
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
| 270 |
+
raise ValueError(
|
| 271 |
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
image = image.to(device=device, dtype=dtype)
|
| 275 |
+
|
| 276 |
+
batch_size = batch_size * num_images_per_prompt
|
| 277 |
+
|
| 278 |
+
if image.shape[1] == 4:
|
| 279 |
+
init_latents = image
|
| 280 |
+
|
| 281 |
+
else:
|
| 282 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 283 |
+
raise ValueError(
|
| 284 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 285 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
elif isinstance(generator, list):
|
| 289 |
+
init_latents = [
|
| 290 |
+
self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
|
| 291 |
+
]
|
| 292 |
+
init_latents = torch.cat(init_latents, dim=0)
|
| 293 |
+
else:
|
| 294 |
+
init_latents = self.movq.encode(image).latent_dist.sample(generator)
|
| 295 |
+
|
| 296 |
+
init_latents = self.movq.config.scaling_factor * init_latents
|
| 297 |
+
|
| 298 |
+
init_latents = torch.cat([init_latents], dim=0)
|
| 299 |
+
|
| 300 |
+
shape = init_latents.shape
|
| 301 |
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 302 |
+
|
| 303 |
+
# get latents
|
| 304 |
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
| 305 |
+
|
| 306 |
+
latents = init_latents
|
| 307 |
+
|
| 308 |
+
return latents
|
| 309 |
+
|
| 310 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 311 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 312 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 313 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 314 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 315 |
+
# and should be between [0, 1]
|
| 316 |
+
|
| 317 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 318 |
+
extra_step_kwargs = {}
|
| 319 |
+
if accepts_eta:
|
| 320 |
+
extra_step_kwargs["eta"] = eta
|
| 321 |
+
|
| 322 |
+
# check if the scheduler accepts generator
|
| 323 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 324 |
+
if accepts_generator:
|
| 325 |
+
extra_step_kwargs["generator"] = generator
|
| 326 |
+
return extra_step_kwargs
|
| 327 |
+
|
| 328 |
+
def check_inputs(
|
| 329 |
+
self,
|
| 330 |
+
prompt,
|
| 331 |
+
callback_steps,
|
| 332 |
+
negative_prompt=None,
|
| 333 |
+
prompt_embeds=None,
|
| 334 |
+
negative_prompt_embeds=None,
|
| 335 |
+
callback_on_step_end_tensor_inputs=None,
|
| 336 |
+
attention_mask=None,
|
| 337 |
+
negative_attention_mask=None,
|
| 338 |
+
):
|
| 339 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 340 |
+
raise ValueError(
|
| 341 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 342 |
+
f" {type(callback_steps)}."
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 346 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 347 |
+
):
|
| 348 |
+
raise ValueError(
|
| 349 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
if prompt is not None and prompt_embeds is not None:
|
| 353 |
+
raise ValueError(
|
| 354 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 355 |
+
" only forward one of the two."
|
| 356 |
+
)
|
| 357 |
+
elif prompt is None and prompt_embeds is None:
|
| 358 |
+
raise ValueError(
|
| 359 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 360 |
+
)
|
| 361 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 362 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 363 |
+
|
| 364 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 365 |
+
raise ValueError(
|
| 366 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 367 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 371 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 372 |
+
raise ValueError(
|
| 373 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 374 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 375 |
+
f" {negative_prompt_embeds.shape}."
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
if negative_prompt_embeds is not None and negative_attention_mask is None:
|
| 379 |
+
raise ValueError("Please provide `negative_attention_mask` along with `negative_prompt_embeds`")
|
| 380 |
+
|
| 381 |
+
if negative_prompt_embeds is not None and negative_attention_mask is not None:
|
| 382 |
+
if negative_prompt_embeds.shape[:2] != negative_attention_mask.shape:
|
| 383 |
+
raise ValueError(
|
| 384 |
+
"`negative_prompt_embeds` and `negative_attention_mask` must have the same batch_size and token length when passed directly, but"
|
| 385 |
+
f" got: `negative_prompt_embeds` {negative_prompt_embeds.shape[:2]} != `negative_attention_mask`"
|
| 386 |
+
f" {negative_attention_mask.shape}."
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
if prompt_embeds is not None and attention_mask is None:
|
| 390 |
+
raise ValueError("Please provide `attention_mask` along with `prompt_embeds`")
|
| 391 |
+
|
| 392 |
+
if prompt_embeds is not None and attention_mask is not None:
|
| 393 |
+
if prompt_embeds.shape[:2] != attention_mask.shape:
|
| 394 |
+
raise ValueError(
|
| 395 |
+
"`prompt_embeds` and `attention_mask` must have the same batch_size and token length when passed directly, but"
|
| 396 |
+
f" got: `prompt_embeds` {prompt_embeds.shape[:2]} != `attention_mask`"
|
| 397 |
+
f" {attention_mask.shape}."
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
@property
|
| 401 |
+
def guidance_scale(self):
|
| 402 |
+
return self._guidance_scale
|
| 403 |
+
|
| 404 |
+
@property
|
| 405 |
+
def do_classifier_free_guidance(self):
|
| 406 |
+
return self._guidance_scale > 1
|
| 407 |
+
|
| 408 |
+
@property
|
| 409 |
+
def num_timesteps(self):
|
| 410 |
+
return self._num_timesteps
|
| 411 |
+
|
| 412 |
+
@torch.no_grad()
|
| 413 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 414 |
+
def __call__(
|
| 415 |
+
self,
|
| 416 |
+
prompt: Union[str, List[str]] = None,
|
| 417 |
+
image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] = None,
|
| 418 |
+
strength: float = 0.3,
|
| 419 |
+
num_inference_steps: int = 25,
|
| 420 |
+
guidance_scale: float = 3.0,
|
| 421 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 422 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 423 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 424 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 425 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 426 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 427 |
+
negative_attention_mask: Optional[torch.FloatTensor] = None,
|
| 428 |
+
output_type: Optional[str] = "pil",
|
| 429 |
+
return_dict: bool = True,
|
| 430 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 431 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 432 |
+
**kwargs,
|
| 433 |
+
):
|
| 434 |
+
"""
|
| 435 |
+
Function invoked when calling the pipeline for generation.
|
| 436 |
+
|
| 437 |
+
Args:
|
| 438 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 439 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 440 |
+
instead.
|
| 441 |
+
image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
|
| 442 |
+
`Image`, or tensor representing an image batch, that will be used as the starting point for the
|
| 443 |
+
process.
|
| 444 |
+
strength (`float`, *optional*, defaults to 0.8):
|
| 445 |
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
| 446 |
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
| 447 |
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
| 448 |
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
| 449 |
+
essentially ignores `image`.
|
| 450 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 451 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 452 |
+
expense of slower inference.
|
| 453 |
+
guidance_scale (`float`, *optional*, defaults to 3.0):
|
| 454 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 455 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 456 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 457 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 458 |
+
usually at the expense of lower image quality.
|
| 459 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 460 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 461 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 462 |
+
less than `1`).
|
| 463 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 464 |
+
The number of images to generate per prompt.
|
| 465 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 466 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 467 |
+
to make generation deterministic.
|
| 468 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 469 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 470 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 471 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 472 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 473 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 474 |
+
argument.
|
| 475 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
| 476 |
+
Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
|
| 477 |
+
negative_attention_mask (`torch.FloatTensor`, *optional*):
|
| 478 |
+
Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
|
| 479 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 480 |
+
The output format of the generate image. Choose between
|
| 481 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 482 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 483 |
+
Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
|
| 484 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 485 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 486 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 487 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 488 |
+
`callback_on_step_end_tensor_inputs`.
|
| 489 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 490 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 491 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 492 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 493 |
+
|
| 494 |
+
Examples:
|
| 495 |
+
|
| 496 |
+
Returns:
|
| 497 |
+
[`~pipelines.ImagePipelineOutput`] or `tuple`
|
| 498 |
+
|
| 499 |
+
"""
|
| 500 |
+
callback = kwargs.pop("callback", None)
|
| 501 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 502 |
+
|
| 503 |
+
if callback is not None:
|
| 504 |
+
deprecate(
|
| 505 |
+
"callback",
|
| 506 |
+
"1.0.0",
|
| 507 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
| 508 |
+
)
|
| 509 |
+
if callback_steps is not None:
|
| 510 |
+
deprecate(
|
| 511 |
+
"callback_steps",
|
| 512 |
+
"1.0.0",
|
| 513 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 517 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 518 |
+
):
|
| 519 |
+
raise ValueError(
|
| 520 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
cut_context = True
|
| 524 |
+
# 1. Check inputs. Raise error if not correct
|
| 525 |
+
self.check_inputs(
|
| 526 |
+
prompt,
|
| 527 |
+
callback_steps,
|
| 528 |
+
negative_prompt,
|
| 529 |
+
prompt_embeds,
|
| 530 |
+
negative_prompt_embeds,
|
| 531 |
+
callback_on_step_end_tensor_inputs,
|
| 532 |
+
attention_mask,
|
| 533 |
+
negative_attention_mask,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
self._guidance_scale = guidance_scale
|
| 537 |
+
|
| 538 |
+
if prompt is not None and isinstance(prompt, str):
|
| 539 |
+
batch_size = 1
|
| 540 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 541 |
+
batch_size = len(prompt)
|
| 542 |
+
else:
|
| 543 |
+
batch_size = prompt_embeds.shape[0]
|
| 544 |
+
|
| 545 |
+
device = self._execution_device
|
| 546 |
+
|
| 547 |
+
# 3. Encode input prompt
|
| 548 |
+
prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask = self.encode_prompt(
|
| 549 |
+
prompt,
|
| 550 |
+
self.do_classifier_free_guidance,
|
| 551 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 552 |
+
device=device,
|
| 553 |
+
negative_prompt=negative_prompt,
|
| 554 |
+
prompt_embeds=prompt_embeds,
|
| 555 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 556 |
+
_cut_context=cut_context,
|
| 557 |
+
attention_mask=attention_mask,
|
| 558 |
+
negative_attention_mask=negative_attention_mask,
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
if self.do_classifier_free_guidance:
|
| 562 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
| 563 |
+
attention_mask = torch.cat([negative_attention_mask, attention_mask]).bool()
|
| 564 |
+
if not isinstance(image, list):
|
| 565 |
+
image = [image]
|
| 566 |
+
if not all(isinstance(i, (PIL.Image.Image, torch.Tensor)) for i in image):
|
| 567 |
+
raise ValueError(
|
| 568 |
+
f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support PIL image and pytorch tensor"
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
image = torch.cat([prepare_image(i) for i in image], dim=0)
|
| 572 |
+
image = image.to(dtype=prompt_embeds.dtype, device=device)
|
| 573 |
+
# 4. Prepare timesteps
|
| 574 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 575 |
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
| 576 |
+
# 5. Prepare latents
|
| 577 |
+
latents = self.movq.encode(image)["latents"]
|
| 578 |
+
latents = latents.repeat_interleave(num_images_per_prompt, dim=0)
|
| 579 |
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
| 580 |
+
latents = self.prepare_latents(
|
| 581 |
+
latents, latent_timestep, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
|
| 582 |
+
)
|
| 583 |
+
if hasattr(self, "text_encoder_offload_hook") and self.text_encoder_offload_hook is not None:
|
| 584 |
+
self.text_encoder_offload_hook.offload()
|
| 585 |
+
|
| 586 |
+
# 7. Denoising loop
|
| 587 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 588 |
+
self._num_timesteps = len(timesteps)
|
| 589 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 590 |
+
for i, t in enumerate(timesteps):
|
| 591 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 592 |
+
|
| 593 |
+
# predict the noise residual
|
| 594 |
+
noise_pred = self.unet(
|
| 595 |
+
latent_model_input,
|
| 596 |
+
t,
|
| 597 |
+
encoder_hidden_states=prompt_embeds,
|
| 598 |
+
encoder_attention_mask=attention_mask,
|
| 599 |
+
)[0]
|
| 600 |
+
if self.do_classifier_free_guidance:
|
| 601 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 602 |
+
|
| 603 |
+
noise_pred = (guidance_scale + 1.0) * noise_pred_text - guidance_scale * noise_pred_uncond
|
| 604 |
+
|
| 605 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 606 |
+
latents = self.scheduler.step(
|
| 607 |
+
noise_pred,
|
| 608 |
+
t,
|
| 609 |
+
latents,
|
| 610 |
+
generator=generator,
|
| 611 |
+
).prev_sample
|
| 612 |
+
|
| 613 |
+
if callback_on_step_end is not None:
|
| 614 |
+
callback_kwargs = {}
|
| 615 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 616 |
+
callback_kwargs[k] = locals()[k]
|
| 617 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 618 |
+
|
| 619 |
+
latents = callback_outputs.pop("latents", latents)
|
| 620 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 621 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 622 |
+
attention_mask = callback_outputs.pop("attention_mask", attention_mask)
|
| 623 |
+
negative_attention_mask = callback_outputs.pop("negative_attention_mask", negative_attention_mask)
|
| 624 |
+
|
| 625 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 626 |
+
progress_bar.update()
|
| 627 |
+
if callback is not None and i % callback_steps == 0:
|
| 628 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 629 |
+
callback(step_idx, t, latents)
|
| 630 |
+
|
| 631 |
+
# post-processing
|
| 632 |
+
if output_type not in ["pt", "np", "pil", "latent"]:
|
| 633 |
+
raise ValueError(
|
| 634 |
+
f"Only the output types `pt`, `pil`, `np` and `latent` are supported not output_type={output_type}"
|
| 635 |
+
)
|
| 636 |
+
if not output_type == "latent":
|
| 637 |
+
image = self.movq.decode(latents, force_not_quantize=True)["sample"]
|
| 638 |
+
|
| 639 |
+
if output_type in ["np", "pil"]:
|
| 640 |
+
image = image * 0.5 + 0.5
|
| 641 |
+
image = image.clamp(0, 1)
|
| 642 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 643 |
+
|
| 644 |
+
if output_type == "pil":
|
| 645 |
+
image = self.numpy_to_pil(image)
|
| 646 |
+
else:
|
| 647 |
+
image = latents
|
| 648 |
+
|
| 649 |
+
self.maybe_free_model_hooks()
|
| 650 |
+
|
| 651 |
+
if not return_dict:
|
| 652 |
+
return (image,)
|
| 653 |
+
|
| 654 |
+
return ImagePipelineOutput(images=image)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from ...utils import (
|
| 4 |
+
DIFFUSERS_SLOW_IMPORT,
|
| 5 |
+
OptionalDependencyNotAvailable,
|
| 6 |
+
_LazyModule,
|
| 7 |
+
get_objects_from_module,
|
| 8 |
+
is_torch_available,
|
| 9 |
+
is_transformers_available,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
_dummy_objects = {}
|
| 14 |
+
_import_structure = {}
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 18 |
+
raise OptionalDependencyNotAvailable()
|
| 19 |
+
except OptionalDependencyNotAvailable:
|
| 20 |
+
from ...utils import dummy_torch_and_transformers_objects # noqa F403
|
| 21 |
+
|
| 22 |
+
_dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
|
| 23 |
+
else:
|
| 24 |
+
_import_structure["pipeline_leditspp_stable_diffusion"] = ["LEditsPPPipelineStableDiffusion"]
|
| 25 |
+
_import_structure["pipeline_leditspp_stable_diffusion_xl"] = ["LEditsPPPipelineStableDiffusionXL"]
|
| 26 |
+
|
| 27 |
+
_import_structure["pipeline_output"] = ["LEditsPPDiffusionPipelineOutput", "LEditsPPDiffusionPipelineOutput"]
|
| 28 |
+
|
| 29 |
+
if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
|
| 30 |
+
try:
|
| 31 |
+
if not (is_transformers_available() and is_torch_available()):
|
| 32 |
+
raise OptionalDependencyNotAvailable()
|
| 33 |
+
|
| 34 |
+
except OptionalDependencyNotAvailable:
|
| 35 |
+
from ...utils.dummy_torch_and_transformers_objects import *
|
| 36 |
+
else:
|
| 37 |
+
from .pipeline_leditspp_stable_diffusion import (
|
| 38 |
+
LEditsPPDiffusionPipelineOutput,
|
| 39 |
+
LEditsPPInversionPipelineOutput,
|
| 40 |
+
LEditsPPPipelineStableDiffusion,
|
| 41 |
+
)
|
| 42 |
+
from .pipeline_leditspp_stable_diffusion_xl import LEditsPPPipelineStableDiffusionXL
|
| 43 |
+
|
| 44 |
+
else:
|
| 45 |
+
import sys
|
| 46 |
+
|
| 47 |
+
sys.modules[__name__] = _LazyModule(
|
| 48 |
+
__name__,
|
| 49 |
+
globals()["__file__"],
|
| 50 |
+
_import_structure,
|
| 51 |
+
module_spec=__spec__,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
for name, value in _dummy_objects.items():
|
| 55 |
+
setattr(sys.modules[__name__], name, value)
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/__pycache__/pipeline_leditspp_stable_diffusion_xl.cpython-310.pyc
ADDED
|
Binary file (54 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/__pycache__/pipeline_output.cpython-310.pyc
ADDED
|
Binary file (2.11 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py
ADDED
|
@@ -0,0 +1,1505 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import math
|
| 3 |
+
from itertools import repeat
|
| 4 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from packaging import version
|
| 9 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
| 10 |
+
|
| 11 |
+
from ...configuration_utils import FrozenDict
|
| 12 |
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
| 13 |
+
from ...loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
| 14 |
+
from ...models import AutoencoderKL, UNet2DConditionModel
|
| 15 |
+
from ...models.attention_processor import Attention, AttnProcessor
|
| 16 |
+
from ...models.lora import adjust_lora_scale_text_encoder
|
| 17 |
+
from ...pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
|
| 18 |
+
from ...schedulers import DDIMScheduler, DPMSolverMultistepScheduler
|
| 19 |
+
from ...utils import (
|
| 20 |
+
USE_PEFT_BACKEND,
|
| 21 |
+
deprecate,
|
| 22 |
+
logging,
|
| 23 |
+
replace_example_docstring,
|
| 24 |
+
scale_lora_layers,
|
| 25 |
+
unscale_lora_layers,
|
| 26 |
+
)
|
| 27 |
+
from ...utils.torch_utils import randn_tensor
|
| 28 |
+
from ..pipeline_utils import DiffusionPipeline
|
| 29 |
+
from .pipeline_output import LEditsPPDiffusionPipelineOutput, LEditsPPInversionPipelineOutput
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 33 |
+
|
| 34 |
+
EXAMPLE_DOC_STRING = """
|
| 35 |
+
Examples:
|
| 36 |
+
```py
|
| 37 |
+
>>> import PIL
|
| 38 |
+
>>> import requests
|
| 39 |
+
>>> import torch
|
| 40 |
+
>>> from io import BytesIO
|
| 41 |
+
|
| 42 |
+
>>> from diffusers import LEditsPPPipelineStableDiffusion
|
| 43 |
+
|
| 44 |
+
>>> pipe = LEditsPPPipelineStableDiffusion.from_pretrained(
|
| 45 |
+
... "runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16
|
| 46 |
+
... )
|
| 47 |
+
>>> pipe = pipe.to("cuda")
|
| 48 |
+
|
| 49 |
+
>>> def download_image(url):
|
| 50 |
+
... response = requests.get(url)
|
| 51 |
+
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
|
| 52 |
+
|
| 53 |
+
>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/cherry_blossom.png"
|
| 54 |
+
>>> image = download_image(img_url)
|
| 55 |
+
|
| 56 |
+
>>> _ = pipe.invert(
|
| 57 |
+
... image = image,
|
| 58 |
+
... num_inversion_steps=50,
|
| 59 |
+
... skip=0.1
|
| 60 |
+
... )
|
| 61 |
+
|
| 62 |
+
>>> edited_image = pipe(
|
| 63 |
+
... editing_prompt=["cherry blossom"],
|
| 64 |
+
... edit_guidance_scale=10.0,
|
| 65 |
+
... edit_threshold=0.75,
|
| 66 |
+
).images[0]
|
| 67 |
+
```
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionAttendAndExcitePipeline.AttentionStore
|
| 72 |
+
class LeditsAttentionStore:
|
| 73 |
+
@staticmethod
|
| 74 |
+
def get_empty_store():
|
| 75 |
+
return {"down_cross": [], "mid_cross": [], "up_cross": [], "down_self": [], "mid_self": [], "up_self": []}
|
| 76 |
+
|
| 77 |
+
def __call__(self, attn, is_cross: bool, place_in_unet: str, editing_prompts, PnP=False):
|
| 78 |
+
# attn.shape = batch_size * head_size, seq_len query, seq_len_key
|
| 79 |
+
if attn.shape[1] <= self.max_size:
|
| 80 |
+
bs = 1 + int(PnP) + editing_prompts
|
| 81 |
+
skip = 2 if PnP else 1 # skip PnP & unconditional
|
| 82 |
+
attn = torch.stack(attn.split(self.batch_size)).permute(1, 0, 2, 3)
|
| 83 |
+
source_batch_size = int(attn.shape[1] // bs)
|
| 84 |
+
self.forward(attn[:, skip * source_batch_size :], is_cross, place_in_unet)
|
| 85 |
+
|
| 86 |
+
def forward(self, attn, is_cross: bool, place_in_unet: str):
|
| 87 |
+
key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
|
| 88 |
+
|
| 89 |
+
self.step_store[key].append(attn)
|
| 90 |
+
|
| 91 |
+
def between_steps(self, store_step=True):
|
| 92 |
+
if store_step:
|
| 93 |
+
if self.average:
|
| 94 |
+
if len(self.attention_store) == 0:
|
| 95 |
+
self.attention_store = self.step_store
|
| 96 |
+
else:
|
| 97 |
+
for key in self.attention_store:
|
| 98 |
+
for i in range(len(self.attention_store[key])):
|
| 99 |
+
self.attention_store[key][i] += self.step_store[key][i]
|
| 100 |
+
else:
|
| 101 |
+
if len(self.attention_store) == 0:
|
| 102 |
+
self.attention_store = [self.step_store]
|
| 103 |
+
else:
|
| 104 |
+
self.attention_store.append(self.step_store)
|
| 105 |
+
|
| 106 |
+
self.cur_step += 1
|
| 107 |
+
self.step_store = self.get_empty_store()
|
| 108 |
+
|
| 109 |
+
def get_attention(self, step: int):
|
| 110 |
+
if self.average:
|
| 111 |
+
attention = {
|
| 112 |
+
key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store
|
| 113 |
+
}
|
| 114 |
+
else:
|
| 115 |
+
assert step is not None
|
| 116 |
+
attention = self.attention_store[step]
|
| 117 |
+
return attention
|
| 118 |
+
|
| 119 |
+
def aggregate_attention(
|
| 120 |
+
self, attention_maps, prompts, res: Union[int, Tuple[int]], from_where: List[str], is_cross: bool, select: int
|
| 121 |
+
):
|
| 122 |
+
out = [[] for x in range(self.batch_size)]
|
| 123 |
+
if isinstance(res, int):
|
| 124 |
+
num_pixels = res**2
|
| 125 |
+
resolution = (res, res)
|
| 126 |
+
else:
|
| 127 |
+
num_pixels = res[0] * res[1]
|
| 128 |
+
resolution = res[:2]
|
| 129 |
+
|
| 130 |
+
for location in from_where:
|
| 131 |
+
for bs_item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
|
| 132 |
+
for batch, item in enumerate(bs_item):
|
| 133 |
+
if item.shape[1] == num_pixels:
|
| 134 |
+
cross_maps = item.reshape(len(prompts), -1, *resolution, item.shape[-1])[select]
|
| 135 |
+
out[batch].append(cross_maps)
|
| 136 |
+
|
| 137 |
+
out = torch.stack([torch.cat(x, dim=0) for x in out])
|
| 138 |
+
# average over heads
|
| 139 |
+
out = out.sum(1) / out.shape[1]
|
| 140 |
+
return out
|
| 141 |
+
|
| 142 |
+
def __init__(self, average: bool, batch_size=1, max_resolution=16, max_size: int = None):
|
| 143 |
+
self.step_store = self.get_empty_store()
|
| 144 |
+
self.attention_store = []
|
| 145 |
+
self.cur_step = 0
|
| 146 |
+
self.average = average
|
| 147 |
+
self.batch_size = batch_size
|
| 148 |
+
if max_size is None:
|
| 149 |
+
self.max_size = max_resolution**2
|
| 150 |
+
elif max_size is not None and max_resolution is None:
|
| 151 |
+
self.max_size = max_size
|
| 152 |
+
else:
|
| 153 |
+
raise ValueError("Only allowed to set one of max_resolution or max_size")
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionAttendAndExcitePipeline.GaussianSmoothing
|
| 157 |
+
class LeditsGaussianSmoothing:
|
| 158 |
+
def __init__(self, device):
|
| 159 |
+
kernel_size = [3, 3]
|
| 160 |
+
sigma = [0.5, 0.5]
|
| 161 |
+
|
| 162 |
+
# The gaussian kernel is the product of the gaussian function of each dimension.
|
| 163 |
+
kernel = 1
|
| 164 |
+
meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
|
| 165 |
+
for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
|
| 166 |
+
mean = (size - 1) / 2
|
| 167 |
+
kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
|
| 168 |
+
|
| 169 |
+
# Make sure sum of values in gaussian kernel equals 1.
|
| 170 |
+
kernel = kernel / torch.sum(kernel)
|
| 171 |
+
|
| 172 |
+
# Reshape to depthwise convolutional weight
|
| 173 |
+
kernel = kernel.view(1, 1, *kernel.size())
|
| 174 |
+
kernel = kernel.repeat(1, *[1] * (kernel.dim() - 1))
|
| 175 |
+
|
| 176 |
+
self.weight = kernel.to(device)
|
| 177 |
+
|
| 178 |
+
def __call__(self, input):
|
| 179 |
+
"""
|
| 180 |
+
Arguments:
|
| 181 |
+
Apply gaussian filter to input.
|
| 182 |
+
input (torch.Tensor): Input to apply gaussian filter on.
|
| 183 |
+
Returns:
|
| 184 |
+
filtered (torch.Tensor): Filtered output.
|
| 185 |
+
"""
|
| 186 |
+
return F.conv2d(input, weight=self.weight.to(input.dtype))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class LEDITSCrossAttnProcessor:
|
| 190 |
+
def __init__(self, attention_store, place_in_unet, pnp, editing_prompts):
|
| 191 |
+
self.attnstore = attention_store
|
| 192 |
+
self.place_in_unet = place_in_unet
|
| 193 |
+
self.editing_prompts = editing_prompts
|
| 194 |
+
self.pnp = pnp
|
| 195 |
+
|
| 196 |
+
def __call__(
|
| 197 |
+
self,
|
| 198 |
+
attn: Attention,
|
| 199 |
+
hidden_states,
|
| 200 |
+
encoder_hidden_states,
|
| 201 |
+
attention_mask=None,
|
| 202 |
+
temb=None,
|
| 203 |
+
):
|
| 204 |
+
batch_size, sequence_length, _ = (
|
| 205 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 206 |
+
)
|
| 207 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 208 |
+
|
| 209 |
+
query = attn.to_q(hidden_states)
|
| 210 |
+
|
| 211 |
+
if encoder_hidden_states is None:
|
| 212 |
+
encoder_hidden_states = hidden_states
|
| 213 |
+
elif attn.norm_cross:
|
| 214 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 215 |
+
|
| 216 |
+
key = attn.to_k(encoder_hidden_states)
|
| 217 |
+
value = attn.to_v(encoder_hidden_states)
|
| 218 |
+
|
| 219 |
+
query = attn.head_to_batch_dim(query)
|
| 220 |
+
key = attn.head_to_batch_dim(key)
|
| 221 |
+
value = attn.head_to_batch_dim(value)
|
| 222 |
+
|
| 223 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 224 |
+
self.attnstore(
|
| 225 |
+
attention_probs,
|
| 226 |
+
is_cross=True,
|
| 227 |
+
place_in_unet=self.place_in_unet,
|
| 228 |
+
editing_prompts=self.editing_prompts,
|
| 229 |
+
PnP=self.pnp,
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 233 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 234 |
+
|
| 235 |
+
# linear proj
|
| 236 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 237 |
+
# dropout
|
| 238 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 239 |
+
|
| 240 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 241 |
+
return hidden_states
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
| 245 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
| 246 |
+
"""
|
| 247 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
| 248 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
| 249 |
+
"""
|
| 250 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
| 251 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
| 252 |
+
# rescale the results from guidance (fixes overexposure)
|
| 253 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
| 254 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
| 255 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
| 256 |
+
return noise_cfg
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class LEditsPPPipelineStableDiffusion(
|
| 260 |
+
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, IPAdapterMixin, FromSingleFileMixin
|
| 261 |
+
):
|
| 262 |
+
"""
|
| 263 |
+
Pipeline for textual image editing using LEDits++ with Stable Diffusion.
|
| 264 |
+
|
| 265 |
+
This model inherits from [`DiffusionPipeline`] and builds on the [`StableDiffusionPipeline`]. Check the superclass
|
| 266 |
+
documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular
|
| 267 |
+
device, etc.).
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
vae ([`AutoencoderKL`]):
|
| 271 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 272 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
| 273 |
+
Frozen text-encoder. Stable Diffusion uses the text portion of
|
| 274 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
| 275 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 276 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
| 277 |
+
Tokenizer of class
|
| 278 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 279 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
| 280 |
+
scheduler ([`DPMSolverMultistepScheduler`] or [`DDIMScheduler`]):
|
| 281 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
|
| 282 |
+
[`DPMSolverMultistepScheduler`] or [`DDIMScheduler`]. If any other scheduler is passed it will automatically
|
| 283 |
+
be set to [`DPMSolverMultistepScheduler`].
|
| 284 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
| 285 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
| 286 |
+
Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
|
| 287 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 288 |
+
Model that extracts features from generated images to be used as inputs for the `safety_checker`.
|
| 289 |
+
"""
|
| 290 |
+
|
| 291 |
+
model_cpu_offload_seq = "text_encoder->unet->vae"
|
| 292 |
+
_exclude_from_cpu_offload = ["safety_checker"]
|
| 293 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 294 |
+
_optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
|
| 295 |
+
|
| 296 |
+
def __init__(
|
| 297 |
+
self,
|
| 298 |
+
vae: AutoencoderKL,
|
| 299 |
+
text_encoder: CLIPTextModel,
|
| 300 |
+
tokenizer: CLIPTokenizer,
|
| 301 |
+
unet: UNet2DConditionModel,
|
| 302 |
+
scheduler: Union[DDIMScheduler, DPMSolverMultistepScheduler],
|
| 303 |
+
safety_checker: StableDiffusionSafetyChecker,
|
| 304 |
+
feature_extractor: CLIPImageProcessor,
|
| 305 |
+
requires_safety_checker: bool = True,
|
| 306 |
+
):
|
| 307 |
+
super().__init__()
|
| 308 |
+
|
| 309 |
+
if not isinstance(scheduler, DDIMScheduler) and not isinstance(scheduler, DPMSolverMultistepScheduler):
|
| 310 |
+
scheduler = DPMSolverMultistepScheduler.from_config(
|
| 311 |
+
scheduler.config, algorithm_type="sde-dpmsolver++", solver_order=2
|
| 312 |
+
)
|
| 313 |
+
logger.warning(
|
| 314 |
+
"This pipeline only supports DDIMScheduler and DPMSolverMultistepScheduler. "
|
| 315 |
+
"The scheduler has been changed to DPMSolverMultistepScheduler."
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
| 319 |
+
deprecation_message = (
|
| 320 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
| 321 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
| 322 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
| 323 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
| 324 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
| 325 |
+
" file"
|
| 326 |
+
)
|
| 327 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
| 328 |
+
new_config = dict(scheduler.config)
|
| 329 |
+
new_config["steps_offset"] = 1
|
| 330 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 331 |
+
|
| 332 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
| 333 |
+
deprecation_message = (
|
| 334 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
| 335 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
| 336 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
| 337 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
| 338 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
| 339 |
+
)
|
| 340 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
| 341 |
+
new_config = dict(scheduler.config)
|
| 342 |
+
new_config["clip_sample"] = False
|
| 343 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
| 344 |
+
|
| 345 |
+
if safety_checker is None and requires_safety_checker:
|
| 346 |
+
logger.warning(
|
| 347 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
| 348 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
| 349 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
| 350 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
| 351 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
| 352 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
if safety_checker is not None and feature_extractor is None:
|
| 356 |
+
raise ValueError(
|
| 357 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
| 358 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
|
| 362 |
+
version.parse(unet.config._diffusers_version).base_version
|
| 363 |
+
) < version.parse("0.9.0.dev0")
|
| 364 |
+
is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
|
| 365 |
+
if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
|
| 366 |
+
deprecation_message = (
|
| 367 |
+
"The configuration file of the unet has set the default `sample_size` to smaller than"
|
| 368 |
+
" 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
|
| 369 |
+
" following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
|
| 370 |
+
" CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
|
| 371 |
+
" \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
|
| 372 |
+
" configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
|
| 373 |
+
" in the config might lead to incorrect results in future versions. If you have downloaded this"
|
| 374 |
+
" checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
|
| 375 |
+
" the `unet/config.json` file"
|
| 376 |
+
)
|
| 377 |
+
deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
|
| 378 |
+
new_config = dict(unet.config)
|
| 379 |
+
new_config["sample_size"] = 64
|
| 380 |
+
unet._internal_dict = FrozenDict(new_config)
|
| 381 |
+
|
| 382 |
+
self.register_modules(
|
| 383 |
+
vae=vae,
|
| 384 |
+
text_encoder=text_encoder,
|
| 385 |
+
tokenizer=tokenizer,
|
| 386 |
+
unet=unet,
|
| 387 |
+
scheduler=scheduler,
|
| 388 |
+
safety_checker=safety_checker,
|
| 389 |
+
feature_extractor=feature_extractor,
|
| 390 |
+
)
|
| 391 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 392 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 393 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
| 394 |
+
|
| 395 |
+
self.inversion_steps = None
|
| 396 |
+
|
| 397 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
| 398 |
+
def run_safety_checker(self, image, device, dtype):
|
| 399 |
+
if self.safety_checker is None:
|
| 400 |
+
has_nsfw_concept = None
|
| 401 |
+
else:
|
| 402 |
+
if torch.is_tensor(image):
|
| 403 |
+
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
| 404 |
+
else:
|
| 405 |
+
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
| 406 |
+
safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
|
| 407 |
+
image, has_nsfw_concept = self.safety_checker(
|
| 408 |
+
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
| 409 |
+
)
|
| 410 |
+
return image, has_nsfw_concept
|
| 411 |
+
|
| 412 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
|
| 413 |
+
def decode_latents(self, latents):
|
| 414 |
+
deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
|
| 415 |
+
deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
|
| 416 |
+
|
| 417 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 418 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 419 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
| 420 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 421 |
+
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
|
| 422 |
+
return image
|
| 423 |
+
|
| 424 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 425 |
+
def prepare_extra_step_kwargs(self, eta, generator=None):
|
| 426 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 427 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 428 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 429 |
+
# and should be between [0, 1]
|
| 430 |
+
|
| 431 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 432 |
+
extra_step_kwargs = {}
|
| 433 |
+
if accepts_eta:
|
| 434 |
+
extra_step_kwargs["eta"] = eta
|
| 435 |
+
|
| 436 |
+
# check if the scheduler accepts generator
|
| 437 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 438 |
+
if accepts_generator:
|
| 439 |
+
extra_step_kwargs["generator"] = generator
|
| 440 |
+
return extra_step_kwargs
|
| 441 |
+
|
| 442 |
+
# Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
|
| 443 |
+
def check_inputs(
|
| 444 |
+
self,
|
| 445 |
+
negative_prompt=None,
|
| 446 |
+
editing_prompt_embeddings=None,
|
| 447 |
+
negative_prompt_embeds=None,
|
| 448 |
+
callback_on_step_end_tensor_inputs=None,
|
| 449 |
+
):
|
| 450 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 451 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 452 |
+
):
|
| 453 |
+
raise ValueError(
|
| 454 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 455 |
+
)
|
| 456 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 457 |
+
raise ValueError(
|
| 458 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 459 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
if editing_prompt_embeddings is not None and negative_prompt_embeds is not None:
|
| 463 |
+
if editing_prompt_embeddings.shape != negative_prompt_embeds.shape:
|
| 464 |
+
raise ValueError(
|
| 465 |
+
"`editing_prompt_embeddings` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 466 |
+
f" got: `editing_prompt_embeddings` {editing_prompt_embeddings.shape} != `negative_prompt_embeds`"
|
| 467 |
+
f" {negative_prompt_embeds.shape}."
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 471 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, latents):
|
| 472 |
+
# shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 473 |
+
|
| 474 |
+
# if latents.shape != shape:
|
| 475 |
+
# raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
|
| 476 |
+
|
| 477 |
+
latents = latents.to(device)
|
| 478 |
+
|
| 479 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 480 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 481 |
+
return latents
|
| 482 |
+
|
| 483 |
+
def prepare_unet(self, attention_store, PnP: bool = False):
|
| 484 |
+
attn_procs = {}
|
| 485 |
+
for name in self.unet.attn_processors.keys():
|
| 486 |
+
if name.startswith("mid_block"):
|
| 487 |
+
place_in_unet = "mid"
|
| 488 |
+
elif name.startswith("up_blocks"):
|
| 489 |
+
place_in_unet = "up"
|
| 490 |
+
elif name.startswith("down_blocks"):
|
| 491 |
+
place_in_unet = "down"
|
| 492 |
+
else:
|
| 493 |
+
continue
|
| 494 |
+
|
| 495 |
+
if "attn2" in name and place_in_unet != "mid":
|
| 496 |
+
attn_procs[name] = LEDITSCrossAttnProcessor(
|
| 497 |
+
attention_store=attention_store,
|
| 498 |
+
place_in_unet=place_in_unet,
|
| 499 |
+
pnp=PnP,
|
| 500 |
+
editing_prompts=self.enabled_editing_prompts,
|
| 501 |
+
)
|
| 502 |
+
else:
|
| 503 |
+
attn_procs[name] = AttnProcessor()
|
| 504 |
+
|
| 505 |
+
self.unet.set_attn_processor(attn_procs)
|
| 506 |
+
|
| 507 |
+
def encode_prompt(
|
| 508 |
+
self,
|
| 509 |
+
device,
|
| 510 |
+
num_images_per_prompt,
|
| 511 |
+
enable_edit_guidance,
|
| 512 |
+
negative_prompt=None,
|
| 513 |
+
editing_prompt=None,
|
| 514 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 515 |
+
editing_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 516 |
+
lora_scale: Optional[float] = None,
|
| 517 |
+
clip_skip: Optional[int] = None,
|
| 518 |
+
):
|
| 519 |
+
r"""
|
| 520 |
+
Encodes the prompt into text encoder hidden states.
|
| 521 |
+
|
| 522 |
+
Args:
|
| 523 |
+
device: (`torch.device`):
|
| 524 |
+
torch device
|
| 525 |
+
num_images_per_prompt (`int`):
|
| 526 |
+
number of images that should be generated per prompt
|
| 527 |
+
enable_edit_guidance (`bool`):
|
| 528 |
+
whether to perform any editing or reconstruct the input image instead
|
| 529 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 530 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 531 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 532 |
+
less than `1`).
|
| 533 |
+
editing_prompt (`str` or `List[str]`, *optional*):
|
| 534 |
+
Editing prompt(s) to be encoded. If not defined, one has to pass
|
| 535 |
+
`editing_prompt_embeds` instead.
|
| 536 |
+
editing_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 537 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 538 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 539 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 540 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 541 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 542 |
+
argument.
|
| 543 |
+
lora_scale (`float`, *optional*):
|
| 544 |
+
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 545 |
+
clip_skip (`int`, *optional*):
|
| 546 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 547 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 548 |
+
"""
|
| 549 |
+
# set lora scale so that monkey patched LoRA
|
| 550 |
+
# function of text encoder can correctly access it
|
| 551 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 552 |
+
self._lora_scale = lora_scale
|
| 553 |
+
|
| 554 |
+
# dynamically adjust the LoRA scale
|
| 555 |
+
if not USE_PEFT_BACKEND:
|
| 556 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 557 |
+
else:
|
| 558 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 559 |
+
|
| 560 |
+
batch_size = self.batch_size
|
| 561 |
+
num_edit_tokens = None
|
| 562 |
+
|
| 563 |
+
if negative_prompt_embeds is None:
|
| 564 |
+
uncond_tokens: List[str]
|
| 565 |
+
if negative_prompt is None:
|
| 566 |
+
uncond_tokens = [""] * batch_size
|
| 567 |
+
elif isinstance(negative_prompt, str):
|
| 568 |
+
uncond_tokens = [negative_prompt]
|
| 569 |
+
elif batch_size != len(negative_prompt):
|
| 570 |
+
raise ValueError(
|
| 571 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but exoected"
|
| 572 |
+
f"{batch_size} based on the input images. Please make sure that passed `negative_prompt` matches"
|
| 573 |
+
" the batch size of `prompt`."
|
| 574 |
+
)
|
| 575 |
+
else:
|
| 576 |
+
uncond_tokens = negative_prompt
|
| 577 |
+
|
| 578 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 579 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 580 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
| 581 |
+
|
| 582 |
+
uncond_input = self.tokenizer(
|
| 583 |
+
uncond_tokens,
|
| 584 |
+
padding="max_length",
|
| 585 |
+
max_length=self.tokenizer.model_max_length,
|
| 586 |
+
truncation=True,
|
| 587 |
+
return_tensors="pt",
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
| 591 |
+
attention_mask = uncond_input.attention_mask.to(device)
|
| 592 |
+
else:
|
| 593 |
+
attention_mask = None
|
| 594 |
+
|
| 595 |
+
negative_prompt_embeds = self.text_encoder(
|
| 596 |
+
uncond_input.input_ids.to(device),
|
| 597 |
+
attention_mask=attention_mask,
|
| 598 |
+
)
|
| 599 |
+
negative_prompt_embeds = negative_prompt_embeds[0]
|
| 600 |
+
|
| 601 |
+
if self.text_encoder is not None:
|
| 602 |
+
prompt_embeds_dtype = self.text_encoder.dtype
|
| 603 |
+
elif self.unet is not None:
|
| 604 |
+
prompt_embeds_dtype = self.unet.dtype
|
| 605 |
+
else:
|
| 606 |
+
prompt_embeds_dtype = negative_prompt_embeds.dtype
|
| 607 |
+
|
| 608 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 609 |
+
|
| 610 |
+
if enable_edit_guidance:
|
| 611 |
+
if editing_prompt_embeds is None:
|
| 612 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 613 |
+
# if isinstance(self, TextualInversionLoaderMixin):
|
| 614 |
+
# prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
| 615 |
+
if isinstance(editing_prompt, str):
|
| 616 |
+
editing_prompt = [editing_prompt]
|
| 617 |
+
|
| 618 |
+
max_length = negative_prompt_embeds.shape[1]
|
| 619 |
+
text_inputs = self.tokenizer(
|
| 620 |
+
[x for item in editing_prompt for x in repeat(item, batch_size)],
|
| 621 |
+
padding="max_length",
|
| 622 |
+
max_length=max_length,
|
| 623 |
+
truncation=True,
|
| 624 |
+
return_tensors="pt",
|
| 625 |
+
return_length=True,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
num_edit_tokens = text_inputs.length - 2 # not counting startoftext and endoftext
|
| 629 |
+
text_input_ids = text_inputs.input_ids
|
| 630 |
+
untruncated_ids = self.tokenizer(
|
| 631 |
+
[x for item in editing_prompt for x in repeat(item, batch_size)],
|
| 632 |
+
padding="longest",
|
| 633 |
+
return_tensors="pt",
|
| 634 |
+
).input_ids
|
| 635 |
+
|
| 636 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
| 637 |
+
text_input_ids, untruncated_ids
|
| 638 |
+
):
|
| 639 |
+
removed_text = self.tokenizer.batch_decode(
|
| 640 |
+
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
| 641 |
+
)
|
| 642 |
+
logger.warning(
|
| 643 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
| 644 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
if (
|
| 648 |
+
hasattr(self.text_encoder.config, "use_attention_mask")
|
| 649 |
+
and self.text_encoder.config.use_attention_mask
|
| 650 |
+
):
|
| 651 |
+
attention_mask = text_inputs.attention_mask.to(device)
|
| 652 |
+
else:
|
| 653 |
+
attention_mask = None
|
| 654 |
+
|
| 655 |
+
if clip_skip is None:
|
| 656 |
+
editing_prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
|
| 657 |
+
editing_prompt_embeds = editing_prompt_embeds[0]
|
| 658 |
+
else:
|
| 659 |
+
editing_prompt_embeds = self.text_encoder(
|
| 660 |
+
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
|
| 661 |
+
)
|
| 662 |
+
# Access the `hidden_states` first, that contains a tuple of
|
| 663 |
+
# all the hidden states from the encoder layers. Then index into
|
| 664 |
+
# the tuple to access the hidden states from the desired layer.
|
| 665 |
+
editing_prompt_embeds = editing_prompt_embeds[-1][-(clip_skip + 1)]
|
| 666 |
+
# We also need to apply the final LayerNorm here to not mess with the
|
| 667 |
+
# representations. The `last_hidden_states` that we typically use for
|
| 668 |
+
# obtaining the final prompt representations passes through the LayerNorm
|
| 669 |
+
# layer.
|
| 670 |
+
editing_prompt_embeds = self.text_encoder.text_model.final_layer_norm(editing_prompt_embeds)
|
| 671 |
+
|
| 672 |
+
editing_prompt_embeds = editing_prompt_embeds.to(dtype=negative_prompt_embeds.dtype, device=device)
|
| 673 |
+
|
| 674 |
+
bs_embed_edit, seq_len, _ = editing_prompt_embeds.shape
|
| 675 |
+
editing_prompt_embeds = editing_prompt_embeds.to(dtype=negative_prompt_embeds.dtype, device=device)
|
| 676 |
+
editing_prompt_embeds = editing_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 677 |
+
editing_prompt_embeds = editing_prompt_embeds.view(bs_embed_edit * num_images_per_prompt, seq_len, -1)
|
| 678 |
+
|
| 679 |
+
# get unconditional embeddings for classifier free guidance
|
| 680 |
+
|
| 681 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 682 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 683 |
+
|
| 684 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
|
| 685 |
+
|
| 686 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 687 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 688 |
+
|
| 689 |
+
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 690 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 691 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 692 |
+
|
| 693 |
+
return editing_prompt_embeds, negative_prompt_embeds, num_edit_tokens
|
| 694 |
+
|
| 695 |
+
@property
|
| 696 |
+
def guidance_rescale(self):
|
| 697 |
+
return self._guidance_rescale
|
| 698 |
+
|
| 699 |
+
@property
|
| 700 |
+
def clip_skip(self):
|
| 701 |
+
return self._clip_skip
|
| 702 |
+
|
| 703 |
+
@property
|
| 704 |
+
def cross_attention_kwargs(self):
|
| 705 |
+
return self._cross_attention_kwargs
|
| 706 |
+
|
| 707 |
+
@torch.no_grad()
|
| 708 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 709 |
+
def __call__(
|
| 710 |
+
self,
|
| 711 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 712 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 713 |
+
output_type: Optional[str] = "pil",
|
| 714 |
+
return_dict: bool = True,
|
| 715 |
+
editing_prompt: Optional[Union[str, List[str]]] = None,
|
| 716 |
+
editing_prompt_embeds: Optional[torch.Tensor] = None,
|
| 717 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 718 |
+
reverse_editing_direction: Optional[Union[bool, List[bool]]] = False,
|
| 719 |
+
edit_guidance_scale: Optional[Union[float, List[float]]] = 5,
|
| 720 |
+
edit_warmup_steps: Optional[Union[int, List[int]]] = 0,
|
| 721 |
+
edit_cooldown_steps: Optional[Union[int, List[int]]] = None,
|
| 722 |
+
edit_threshold: Optional[Union[float, List[float]]] = 0.9,
|
| 723 |
+
user_mask: Optional[torch.FloatTensor] = None,
|
| 724 |
+
sem_guidance: Optional[List[torch.Tensor]] = None,
|
| 725 |
+
use_cross_attn_mask: bool = False,
|
| 726 |
+
use_intersect_mask: bool = True,
|
| 727 |
+
attn_store_steps: Optional[List[int]] = [],
|
| 728 |
+
store_averaged_over_steps: bool = True,
|
| 729 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 730 |
+
guidance_rescale: float = 0.0,
|
| 731 |
+
clip_skip: Optional[int] = None,
|
| 732 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 733 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 734 |
+
**kwargs,
|
| 735 |
+
):
|
| 736 |
+
r"""
|
| 737 |
+
The call function to the pipeline for editing. The [`~pipelines.ledits_pp.LEditsPPPipelineStableDiffusion.invert`]
|
| 738 |
+
method has to be called beforehand. Edits will always be performed for the last inverted image(s).
|
| 739 |
+
|
| 740 |
+
Args:
|
| 741 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 742 |
+
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
|
| 743 |
+
if `guidance_scale` is less than `1`).
|
| 744 |
+
generator (`torch.Generator`, *optional*):
|
| 745 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 746 |
+
to make generation deterministic.
|
| 747 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 748 |
+
The output format of the generate image. Choose between
|
| 749 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 750 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 751 |
+
Whether or not to return a [`~pipelines.ledits_pp.LEditsPPDiffusionPipelineOutput`] instead of a
|
| 752 |
+
plain tuple.
|
| 753 |
+
editing_prompt (`str` or `List[str]`, *optional*):
|
| 754 |
+
The prompt or prompts to guide the image generation. The image is reconstructed by setting
|
| 755 |
+
`editing_prompt = None`. Guidance direction of prompt should be specified via `reverse_editing_direction`.
|
| 756 |
+
editing_prompt_embeds (`torch.Tensor>`, *optional*):
|
| 757 |
+
Pre-computed embeddings to use for guiding the image generation. Guidance direction of embedding should be
|
| 758 |
+
specified via `reverse_editing_direction`.
|
| 759 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 760 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 761 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 762 |
+
reverse_editing_direction (`bool` or `List[bool]`, *optional*, defaults to `False`):
|
| 763 |
+
Whether the corresponding prompt in `editing_prompt` should be increased or decreased.
|
| 764 |
+
edit_guidance_scale (`float` or `List[float]`, *optional*, defaults to 5):
|
| 765 |
+
Guidance scale for guiding the image generation. If provided as list values should correspond to `editing_prompt`.
|
| 766 |
+
`edit_guidance_scale` is defined as `s_e` of equation 12 of
|
| 767 |
+
[LEDITS++ Paper](https://arxiv.org/abs/2301.12247).
|
| 768 |
+
edit_warmup_steps (`float` or `List[float]`, *optional*, defaults to 10):
|
| 769 |
+
Number of diffusion steps (for each prompt) for which guidance will not be applied.
|
| 770 |
+
edit_cooldown_steps (`float` or `List[float]`, *optional*, defaults to `None`):
|
| 771 |
+
Number of diffusion steps (for each prompt) after which guidance will no longer be applied.
|
| 772 |
+
edit_threshold (`float` or `List[float]`, *optional*, defaults to 0.9):
|
| 773 |
+
Masking threshold of guidance. Threshold should be proportional to the image region that is modified.
|
| 774 |
+
'edit_threshold' is defined as 'λ' of equation 12 of [LEDITS++ Paper](https://arxiv.org/abs/2301.12247).
|
| 775 |
+
user_mask (`torch.FloatTensor`, *optional*):
|
| 776 |
+
User-provided mask for even better control over the editing process. This is helpful when LEDITS++'s implicit
|
| 777 |
+
masks do not meet user preferences.
|
| 778 |
+
sem_guidance (`List[torch.Tensor]`, *optional*):
|
| 779 |
+
List of pre-generated guidance vectors to be applied at generation. Length of the list has to
|
| 780 |
+
correspond to `num_inference_steps`.
|
| 781 |
+
use_cross_attn_mask (`bool`, defaults to `False`):
|
| 782 |
+
Whether cross-attention masks are used. Cross-attention masks are always used when use_intersect_mask
|
| 783 |
+
is set to true. Cross-attention masks are defined as 'M^1' of equation 12 of
|
| 784 |
+
[LEDITS++ paper](https://arxiv.org/pdf/2311.16711.pdf).
|
| 785 |
+
use_intersect_mask (`bool`, defaults to `True`):
|
| 786 |
+
Whether the masking term is calculated as intersection of cross-attention masks and masks derived
|
| 787 |
+
from the noise estimate. Cross-attention mask are defined as 'M^1' and masks derived from the noise
|
| 788 |
+
estimate are defined as 'M^2' of equation 12 of [LEDITS++ paper](https://arxiv.org/pdf/2311.16711.pdf).
|
| 789 |
+
attn_store_steps (`List[int]`, *optional*):
|
| 790 |
+
Steps for which the attention maps are stored in the AttentionStore. Just for visualization purposes.
|
| 791 |
+
store_averaged_over_steps (`bool`, defaults to `True`):
|
| 792 |
+
Whether the attention maps for the 'attn_store_steps' are stored averaged over the diffusion steps.
|
| 793 |
+
If False, attention maps for each step are stores separately. Just for visualization purposes.
|
| 794 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 795 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 796 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 797 |
+
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
| 798 |
+
Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
|
| 799 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
|
| 800 |
+
using zero terminal SNR.
|
| 801 |
+
clip_skip (`int`, *optional*):
|
| 802 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 803 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 804 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 805 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 806 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 807 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 808 |
+
`callback_on_step_end_tensor_inputs`.
|
| 809 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 810 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 811 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 812 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 813 |
+
|
| 814 |
+
Examples:
|
| 815 |
+
|
| 816 |
+
Returns:
|
| 817 |
+
[`~pipelines.ledits_pp.LEditsPPDiffusionPipelineOutput`] or `tuple`:
|
| 818 |
+
[`~pipelines.ledits_pp.LEditsPPDiffusionPipelineOutput`] if `return_dict` is True,
|
| 819 |
+
otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the
|
| 820 |
+
second element is a list of `bool`s denoting whether the corresponding generated image likely represents
|
| 821 |
+
"not-safe-for-work" (nsfw) content, according to the `safety_checker`.
|
| 822 |
+
"""
|
| 823 |
+
|
| 824 |
+
if self.inversion_steps is None:
|
| 825 |
+
raise ValueError(
|
| 826 |
+
"You need to invert an input image first before calling the pipeline. The `invert` method has to be called beforehand. Edits will always be performed for the last inverted image(s)."
|
| 827 |
+
)
|
| 828 |
+
|
| 829 |
+
eta = self.eta
|
| 830 |
+
num_images_per_prompt = 1
|
| 831 |
+
latents = self.init_latents
|
| 832 |
+
|
| 833 |
+
zs = self.zs
|
| 834 |
+
self.scheduler.set_timesteps(len(self.scheduler.timesteps))
|
| 835 |
+
|
| 836 |
+
if use_intersect_mask:
|
| 837 |
+
use_cross_attn_mask = True
|
| 838 |
+
|
| 839 |
+
if use_cross_attn_mask:
|
| 840 |
+
self.smoothing = LeditsGaussianSmoothing(self.device)
|
| 841 |
+
|
| 842 |
+
if user_mask is not None:
|
| 843 |
+
user_mask = user_mask.to(self.device)
|
| 844 |
+
|
| 845 |
+
org_prompt = ""
|
| 846 |
+
|
| 847 |
+
# 1. Check inputs. Raise error if not correct
|
| 848 |
+
self.check_inputs(
|
| 849 |
+
negative_prompt,
|
| 850 |
+
editing_prompt_embeds,
|
| 851 |
+
negative_prompt_embeds,
|
| 852 |
+
callback_on_step_end_tensor_inputs,
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
self._guidance_rescale = guidance_rescale
|
| 856 |
+
self._clip_skip = clip_skip
|
| 857 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 858 |
+
|
| 859 |
+
# 2. Define call parameters
|
| 860 |
+
batch_size = self.batch_size
|
| 861 |
+
|
| 862 |
+
if editing_prompt:
|
| 863 |
+
enable_edit_guidance = True
|
| 864 |
+
if isinstance(editing_prompt, str):
|
| 865 |
+
editing_prompt = [editing_prompt]
|
| 866 |
+
self.enabled_editing_prompts = len(editing_prompt)
|
| 867 |
+
elif editing_prompt_embeds is not None:
|
| 868 |
+
enable_edit_guidance = True
|
| 869 |
+
self.enabled_editing_prompts = editing_prompt_embeds.shape[0]
|
| 870 |
+
else:
|
| 871 |
+
self.enabled_editing_prompts = 0
|
| 872 |
+
enable_edit_guidance = False
|
| 873 |
+
|
| 874 |
+
# 3. Encode input prompt
|
| 875 |
+
lora_scale = (
|
| 876 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 877 |
+
)
|
| 878 |
+
|
| 879 |
+
edit_concepts, uncond_embeddings, num_edit_tokens = self.encode_prompt(
|
| 880 |
+
editing_prompt=editing_prompt,
|
| 881 |
+
device=self.device,
|
| 882 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 883 |
+
enable_edit_guidance=enable_edit_guidance,
|
| 884 |
+
negative_prompt=negative_prompt,
|
| 885 |
+
editing_prompt_embeds=editing_prompt_embeds,
|
| 886 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 887 |
+
lora_scale=lora_scale,
|
| 888 |
+
clip_skip=self.clip_skip,
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 892 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 893 |
+
# to avoid doing two forward passes
|
| 894 |
+
if enable_edit_guidance:
|
| 895 |
+
text_embeddings = torch.cat([uncond_embeddings, edit_concepts])
|
| 896 |
+
self.text_cross_attention_maps = [editing_prompt] if isinstance(editing_prompt, str) else editing_prompt
|
| 897 |
+
else:
|
| 898 |
+
text_embeddings = torch.cat([uncond_embeddings])
|
| 899 |
+
|
| 900 |
+
# 4. Prepare timesteps
|
| 901 |
+
# self.scheduler.set_timesteps(num_inference_steps, device=self.device)
|
| 902 |
+
timesteps = self.inversion_steps
|
| 903 |
+
t_to_idx = {int(v): k for k, v in enumerate(timesteps[-zs.shape[0] :])}
|
| 904 |
+
|
| 905 |
+
if use_cross_attn_mask:
|
| 906 |
+
self.attention_store = LeditsAttentionStore(
|
| 907 |
+
average=store_averaged_over_steps,
|
| 908 |
+
batch_size=batch_size,
|
| 909 |
+
max_size=(latents.shape[-2] / 4.0) * (latents.shape[-1] / 4.0),
|
| 910 |
+
max_resolution=None,
|
| 911 |
+
)
|
| 912 |
+
self.prepare_unet(self.attention_store, PnP=False)
|
| 913 |
+
resolution = latents.shape[-2:]
|
| 914 |
+
att_res = (int(resolution[0] / 4), int(resolution[1] / 4))
|
| 915 |
+
|
| 916 |
+
# 5. Prepare latent variables
|
| 917 |
+
num_channels_latents = self.unet.config.in_channels
|
| 918 |
+
latents = self.prepare_latents(
|
| 919 |
+
batch_size * num_images_per_prompt,
|
| 920 |
+
num_channels_latents,
|
| 921 |
+
None,
|
| 922 |
+
None,
|
| 923 |
+
text_embeddings.dtype,
|
| 924 |
+
self.device,
|
| 925 |
+
latents,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
# 6. Prepare extra step kwargs.
|
| 929 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(eta)
|
| 930 |
+
|
| 931 |
+
self.sem_guidance = None
|
| 932 |
+
self.activation_mask = None
|
| 933 |
+
|
| 934 |
+
# 7. Denoising loop
|
| 935 |
+
num_warmup_steps = 0
|
| 936 |
+
with self.progress_bar(total=len(timesteps)) as progress_bar:
|
| 937 |
+
for i, t in enumerate(timesteps):
|
| 938 |
+
# expand the latents if we are doing classifier free guidance
|
| 939 |
+
|
| 940 |
+
if enable_edit_guidance:
|
| 941 |
+
latent_model_input = torch.cat([latents] * (1 + self.enabled_editing_prompts))
|
| 942 |
+
else:
|
| 943 |
+
latent_model_input = latents
|
| 944 |
+
|
| 945 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 946 |
+
|
| 947 |
+
text_embed_input = text_embeddings
|
| 948 |
+
|
| 949 |
+
# predict the noise residual
|
| 950 |
+
noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embed_input).sample
|
| 951 |
+
|
| 952 |
+
noise_pred_out = noise_pred.chunk(1 + self.enabled_editing_prompts) # [b,4, 64, 64]
|
| 953 |
+
noise_pred_uncond = noise_pred_out[0]
|
| 954 |
+
noise_pred_edit_concepts = noise_pred_out[1:]
|
| 955 |
+
|
| 956 |
+
noise_guidance_edit = torch.zeros(
|
| 957 |
+
noise_pred_uncond.shape,
|
| 958 |
+
device=self.device,
|
| 959 |
+
dtype=noise_pred_uncond.dtype,
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
if sem_guidance is not None and len(sem_guidance) > i:
|
| 963 |
+
noise_guidance_edit += sem_guidance[i].to(self.device)
|
| 964 |
+
|
| 965 |
+
elif enable_edit_guidance:
|
| 966 |
+
if self.activation_mask is None:
|
| 967 |
+
self.activation_mask = torch.zeros(
|
| 968 |
+
(len(timesteps), len(noise_pred_edit_concepts), *noise_pred_edit_concepts[0].shape)
|
| 969 |
+
)
|
| 970 |
+
|
| 971 |
+
if self.sem_guidance is None:
|
| 972 |
+
self.sem_guidance = torch.zeros((len(timesteps), *noise_pred_uncond.shape))
|
| 973 |
+
|
| 974 |
+
for c, noise_pred_edit_concept in enumerate(noise_pred_edit_concepts):
|
| 975 |
+
if isinstance(edit_warmup_steps, list):
|
| 976 |
+
edit_warmup_steps_c = edit_warmup_steps[c]
|
| 977 |
+
else:
|
| 978 |
+
edit_warmup_steps_c = edit_warmup_steps
|
| 979 |
+
if i < edit_warmup_steps_c:
|
| 980 |
+
continue
|
| 981 |
+
|
| 982 |
+
if isinstance(edit_guidance_scale, list):
|
| 983 |
+
edit_guidance_scale_c = edit_guidance_scale[c]
|
| 984 |
+
else:
|
| 985 |
+
edit_guidance_scale_c = edit_guidance_scale
|
| 986 |
+
|
| 987 |
+
if isinstance(edit_threshold, list):
|
| 988 |
+
edit_threshold_c = edit_threshold[c]
|
| 989 |
+
else:
|
| 990 |
+
edit_threshold_c = edit_threshold
|
| 991 |
+
if isinstance(reverse_editing_direction, list):
|
| 992 |
+
reverse_editing_direction_c = reverse_editing_direction[c]
|
| 993 |
+
else:
|
| 994 |
+
reverse_editing_direction_c = reverse_editing_direction
|
| 995 |
+
|
| 996 |
+
if isinstance(edit_cooldown_steps, list):
|
| 997 |
+
edit_cooldown_steps_c = edit_cooldown_steps[c]
|
| 998 |
+
elif edit_cooldown_steps is None:
|
| 999 |
+
edit_cooldown_steps_c = i + 1
|
| 1000 |
+
else:
|
| 1001 |
+
edit_cooldown_steps_c = edit_cooldown_steps
|
| 1002 |
+
|
| 1003 |
+
if i >= edit_cooldown_steps_c:
|
| 1004 |
+
continue
|
| 1005 |
+
|
| 1006 |
+
noise_guidance_edit_tmp = noise_pred_edit_concept - noise_pred_uncond
|
| 1007 |
+
|
| 1008 |
+
if reverse_editing_direction_c:
|
| 1009 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * -1
|
| 1010 |
+
|
| 1011 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * edit_guidance_scale_c
|
| 1012 |
+
|
| 1013 |
+
if user_mask is not None:
|
| 1014 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * user_mask
|
| 1015 |
+
|
| 1016 |
+
if use_cross_attn_mask:
|
| 1017 |
+
out = self.attention_store.aggregate_attention(
|
| 1018 |
+
attention_maps=self.attention_store.step_store,
|
| 1019 |
+
prompts=self.text_cross_attention_maps,
|
| 1020 |
+
res=att_res,
|
| 1021 |
+
from_where=["up", "down"],
|
| 1022 |
+
is_cross=True,
|
| 1023 |
+
select=self.text_cross_attention_maps.index(editing_prompt[c]),
|
| 1024 |
+
)
|
| 1025 |
+
attn_map = out[:, :, :, 1 : 1 + num_edit_tokens[c]] # 0 -> startoftext
|
| 1026 |
+
|
| 1027 |
+
# average over all tokens
|
| 1028 |
+
if attn_map.shape[3] != num_edit_tokens[c]:
|
| 1029 |
+
raise ValueError(
|
| 1030 |
+
f"Incorrect shape of attention_map. Expected size {num_edit_tokens[c]}, but found {attn_map.shape[3]}!"
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
attn_map = torch.sum(attn_map, dim=3)
|
| 1034 |
+
|
| 1035 |
+
# gaussian_smoothing
|
| 1036 |
+
attn_map = F.pad(attn_map.unsqueeze(1), (1, 1, 1, 1), mode="reflect")
|
| 1037 |
+
attn_map = self.smoothing(attn_map).squeeze(1)
|
| 1038 |
+
|
| 1039 |
+
# torch.quantile function expects float32
|
| 1040 |
+
if attn_map.dtype == torch.float32:
|
| 1041 |
+
tmp = torch.quantile(attn_map.flatten(start_dim=1), edit_threshold_c, dim=1)
|
| 1042 |
+
else:
|
| 1043 |
+
tmp = torch.quantile(
|
| 1044 |
+
attn_map.flatten(start_dim=1).to(torch.float32), edit_threshold_c, dim=1
|
| 1045 |
+
).to(attn_map.dtype)
|
| 1046 |
+
attn_mask = torch.where(
|
| 1047 |
+
attn_map >= tmp.unsqueeze(1).unsqueeze(1).repeat(1, *att_res), 1.0, 0.0
|
| 1048 |
+
)
|
| 1049 |
+
|
| 1050 |
+
# resolution must match latent space dimension
|
| 1051 |
+
attn_mask = F.interpolate(
|
| 1052 |
+
attn_mask.unsqueeze(1),
|
| 1053 |
+
noise_guidance_edit_tmp.shape[-2:], # 64,64
|
| 1054 |
+
).repeat(1, 4, 1, 1)
|
| 1055 |
+
self.activation_mask[i, c] = attn_mask.detach().cpu()
|
| 1056 |
+
if not use_intersect_mask:
|
| 1057 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * attn_mask
|
| 1058 |
+
|
| 1059 |
+
if use_intersect_mask:
|
| 1060 |
+
if t <= 800:
|
| 1061 |
+
noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
|
| 1062 |
+
noise_guidance_edit_tmp_quantile = torch.sum(
|
| 1063 |
+
noise_guidance_edit_tmp_quantile, dim=1, keepdim=True
|
| 1064 |
+
)
|
| 1065 |
+
noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(
|
| 1066 |
+
1, self.unet.config.in_channels, 1, 1
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
# torch.quantile function expects float32
|
| 1070 |
+
if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
|
| 1071 |
+
tmp = torch.quantile(
|
| 1072 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
|
| 1073 |
+
edit_threshold_c,
|
| 1074 |
+
dim=2,
|
| 1075 |
+
keepdim=False,
|
| 1076 |
+
)
|
| 1077 |
+
else:
|
| 1078 |
+
tmp = torch.quantile(
|
| 1079 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
|
| 1080 |
+
edit_threshold_c,
|
| 1081 |
+
dim=2,
|
| 1082 |
+
keepdim=False,
|
| 1083 |
+
).to(noise_guidance_edit_tmp_quantile.dtype)
|
| 1084 |
+
|
| 1085 |
+
intersect_mask = (
|
| 1086 |
+
torch.where(
|
| 1087 |
+
noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
|
| 1088 |
+
torch.ones_like(noise_guidance_edit_tmp),
|
| 1089 |
+
torch.zeros_like(noise_guidance_edit_tmp),
|
| 1090 |
+
)
|
| 1091 |
+
* attn_mask
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
self.activation_mask[i, c] = intersect_mask.detach().cpu()
|
| 1095 |
+
|
| 1096 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * intersect_mask
|
| 1097 |
+
|
| 1098 |
+
else:
|
| 1099 |
+
# print(f"only attention mask for step {i}")
|
| 1100 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * attn_mask
|
| 1101 |
+
|
| 1102 |
+
elif not use_cross_attn_mask:
|
| 1103 |
+
# calculate quantile
|
| 1104 |
+
noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
|
| 1105 |
+
noise_guidance_edit_tmp_quantile = torch.sum(
|
| 1106 |
+
noise_guidance_edit_tmp_quantile, dim=1, keepdim=True
|
| 1107 |
+
)
|
| 1108 |
+
noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(1, 4, 1, 1)
|
| 1109 |
+
|
| 1110 |
+
# torch.quantile function expects float32
|
| 1111 |
+
if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
|
| 1112 |
+
tmp = torch.quantile(
|
| 1113 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
|
| 1114 |
+
edit_threshold_c,
|
| 1115 |
+
dim=2,
|
| 1116 |
+
keepdim=False,
|
| 1117 |
+
)
|
| 1118 |
+
else:
|
| 1119 |
+
tmp = torch.quantile(
|
| 1120 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
|
| 1121 |
+
edit_threshold_c,
|
| 1122 |
+
dim=2,
|
| 1123 |
+
keepdim=False,
|
| 1124 |
+
).to(noise_guidance_edit_tmp_quantile.dtype)
|
| 1125 |
+
|
| 1126 |
+
self.activation_mask[i, c] = (
|
| 1127 |
+
torch.where(
|
| 1128 |
+
noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
|
| 1129 |
+
torch.ones_like(noise_guidance_edit_tmp),
|
| 1130 |
+
torch.zeros_like(noise_guidance_edit_tmp),
|
| 1131 |
+
)
|
| 1132 |
+
.detach()
|
| 1133 |
+
.cpu()
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
noise_guidance_edit_tmp = torch.where(
|
| 1137 |
+
noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
|
| 1138 |
+
noise_guidance_edit_tmp,
|
| 1139 |
+
torch.zeros_like(noise_guidance_edit_tmp),
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
noise_guidance_edit += noise_guidance_edit_tmp
|
| 1143 |
+
|
| 1144 |
+
self.sem_guidance[i] = noise_guidance_edit.detach().cpu()
|
| 1145 |
+
|
| 1146 |
+
noise_pred = noise_pred_uncond + noise_guidance_edit
|
| 1147 |
+
|
| 1148 |
+
if enable_edit_guidance and self.guidance_rescale > 0.0:
|
| 1149 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 1150 |
+
noise_pred = rescale_noise_cfg(
|
| 1151 |
+
noise_pred,
|
| 1152 |
+
noise_pred_edit_concepts.mean(dim=0, keepdim=False),
|
| 1153 |
+
guidance_rescale=self.guidance_rescale,
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
idx = t_to_idx[int(t)]
|
| 1157 |
+
latents = self.scheduler.step(
|
| 1158 |
+
noise_pred, t, latents, variance_noise=zs[idx], **extra_step_kwargs
|
| 1159 |
+
).prev_sample
|
| 1160 |
+
|
| 1161 |
+
# step callback
|
| 1162 |
+
if use_cross_attn_mask:
|
| 1163 |
+
store_step = i in attn_store_steps
|
| 1164 |
+
self.attention_store.between_steps(store_step)
|
| 1165 |
+
|
| 1166 |
+
if callback_on_step_end is not None:
|
| 1167 |
+
callback_kwargs = {}
|
| 1168 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 1169 |
+
callback_kwargs[k] = locals()[k]
|
| 1170 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 1171 |
+
|
| 1172 |
+
latents = callback_outputs.pop("latents", latents)
|
| 1173 |
+
# prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 1174 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 1175 |
+
|
| 1176 |
+
# call the callback, if provided
|
| 1177 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 1178 |
+
progress_bar.update()
|
| 1179 |
+
|
| 1180 |
+
# 8. Post-processing
|
| 1181 |
+
if not output_type == "latent":
|
| 1182 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
|
| 1183 |
+
0
|
| 1184 |
+
]
|
| 1185 |
+
image, has_nsfw_concept = self.run_safety_checker(image, self.device, text_embeddings.dtype)
|
| 1186 |
+
else:
|
| 1187 |
+
image = latents
|
| 1188 |
+
has_nsfw_concept = None
|
| 1189 |
+
|
| 1190 |
+
if has_nsfw_concept is None:
|
| 1191 |
+
do_denormalize = [True] * image.shape[0]
|
| 1192 |
+
else:
|
| 1193 |
+
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
| 1194 |
+
|
| 1195 |
+
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
| 1196 |
+
|
| 1197 |
+
# Offload all models
|
| 1198 |
+
self.maybe_free_model_hooks()
|
| 1199 |
+
|
| 1200 |
+
if not return_dict:
|
| 1201 |
+
return (image, has_nsfw_concept)
|
| 1202 |
+
|
| 1203 |
+
return LEditsPPDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
| 1204 |
+
|
| 1205 |
+
@torch.no_grad()
|
| 1206 |
+
def invert(
|
| 1207 |
+
self,
|
| 1208 |
+
image: PipelineImageInput,
|
| 1209 |
+
source_prompt: str = "",
|
| 1210 |
+
source_guidance_scale: float = 3.5,
|
| 1211 |
+
num_inversion_steps: int = 30,
|
| 1212 |
+
skip: float = 0.15,
|
| 1213 |
+
generator: Optional[torch.Generator] = None,
|
| 1214 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 1215 |
+
clip_skip: Optional[int] = None,
|
| 1216 |
+
height: Optional[int] = None,
|
| 1217 |
+
width: Optional[int] = None,
|
| 1218 |
+
resize_mode: Optional[str] = "default",
|
| 1219 |
+
crops_coords: Optional[Tuple[int, int, int, int]] = None,
|
| 1220 |
+
):
|
| 1221 |
+
r"""
|
| 1222 |
+
The function to the pipeline for image inversion as described by the [LEDITS++ Paper](https://arxiv.org/abs/2301.12247).
|
| 1223 |
+
If the scheduler is set to [`~schedulers.DDIMScheduler`] the inversion proposed by [edit-friendly DPDM](https://arxiv.org/abs/2304.06140)
|
| 1224 |
+
will be performed instead.
|
| 1225 |
+
|
| 1226 |
+
Args:
|
| 1227 |
+
image (`PipelineImageInput`):
|
| 1228 |
+
Input for the image(s) that are to be edited. Multiple input images have to default to the same aspect
|
| 1229 |
+
ratio.
|
| 1230 |
+
source_prompt (`str`, defaults to `""`):
|
| 1231 |
+
Prompt describing the input image that will be used for guidance during inversion. Guidance is disabled
|
| 1232 |
+
if the `source_prompt` is `""`.
|
| 1233 |
+
source_guidance_scale (`float`, defaults to `3.5`):
|
| 1234 |
+
Strength of guidance during inversion.
|
| 1235 |
+
num_inversion_steps (`int`, defaults to `30`):
|
| 1236 |
+
Number of total performed inversion steps after discarding the initial `skip` steps.
|
| 1237 |
+
skip (`float`, defaults to `0.15`):
|
| 1238 |
+
Portion of initial steps that will be ignored for inversion and subsequent generation. Lower values
|
| 1239 |
+
will lead to stronger changes to the input image. `skip` has to be between `0` and `1`.
|
| 1240 |
+
generator (`torch.Generator`, *optional*):
|
| 1241 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 1242 |
+
inversion deterministic.
|
| 1243 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 1244 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 1245 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 1246 |
+
clip_skip (`int`, *optional*):
|
| 1247 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 1248 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 1249 |
+
height (`int`, *optional*, defaults to `None`):
|
| 1250 |
+
The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default height.
|
| 1251 |
+
width (`int`, *optional*`, defaults to `None`):
|
| 1252 |
+
The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
|
| 1253 |
+
resize_mode (`str`, *optional*, defaults to `default`):
|
| 1254 |
+
The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit
|
| 1255 |
+
within the specified width and height, and it may not maintaining the original aspect ratio.
|
| 1256 |
+
If `fill`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
| 1257 |
+
within the dimensions, filling empty with data from image.
|
| 1258 |
+
If `crop`, will resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image
|
| 1259 |
+
within the dimensions, cropping the excess.
|
| 1260 |
+
Note that resize_mode `fill` and `crop` are only supported for PIL image input.
|
| 1261 |
+
crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
|
| 1262 |
+
The crop coordinates for each image in the batch. If `None`, will not crop the image.
|
| 1263 |
+
|
| 1264 |
+
Returns:
|
| 1265 |
+
[`~pipelines.ledits_pp.LEditsPPInversionPipelineOutput`]:
|
| 1266 |
+
Output will contain the resized input image(s) and respective VAE reconstruction(s).
|
| 1267 |
+
"""
|
| 1268 |
+
# Reset attn processor, we do not want to store attn maps during inversion
|
| 1269 |
+
self.unet.set_attn_processor(AttnProcessor())
|
| 1270 |
+
|
| 1271 |
+
self.eta = 1.0
|
| 1272 |
+
|
| 1273 |
+
self.scheduler.config.timestep_spacing = "leading"
|
| 1274 |
+
self.scheduler.set_timesteps(int(num_inversion_steps * (1 + skip)))
|
| 1275 |
+
self.inversion_steps = self.scheduler.timesteps[-num_inversion_steps:]
|
| 1276 |
+
timesteps = self.inversion_steps
|
| 1277 |
+
|
| 1278 |
+
# 1. encode image
|
| 1279 |
+
x0, resized = self.encode_image(
|
| 1280 |
+
image,
|
| 1281 |
+
dtype=self.text_encoder.dtype,
|
| 1282 |
+
height=height,
|
| 1283 |
+
width=width,
|
| 1284 |
+
resize_mode=resize_mode,
|
| 1285 |
+
crops_coords=crops_coords,
|
| 1286 |
+
)
|
| 1287 |
+
self.batch_size = x0.shape[0]
|
| 1288 |
+
|
| 1289 |
+
# autoencoder reconstruction
|
| 1290 |
+
image_rec = self.vae.decode(x0 / self.vae.config.scaling_factor, return_dict=False, generator=generator)[0]
|
| 1291 |
+
image_rec = self.image_processor.postprocess(image_rec, output_type="pil")
|
| 1292 |
+
|
| 1293 |
+
# 2. get embeddings
|
| 1294 |
+
do_classifier_free_guidance = source_guidance_scale > 1.0
|
| 1295 |
+
|
| 1296 |
+
lora_scale = cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 1297 |
+
|
| 1298 |
+
uncond_embedding, text_embeddings, _ = self.encode_prompt(
|
| 1299 |
+
num_images_per_prompt=1,
|
| 1300 |
+
device=self.device,
|
| 1301 |
+
negative_prompt=None,
|
| 1302 |
+
enable_edit_guidance=do_classifier_free_guidance,
|
| 1303 |
+
editing_prompt=source_prompt,
|
| 1304 |
+
lora_scale=lora_scale,
|
| 1305 |
+
clip_skip=clip_skip,
|
| 1306 |
+
)
|
| 1307 |
+
|
| 1308 |
+
# 3. find zs and xts
|
| 1309 |
+
variance_noise_shape = (num_inversion_steps, *x0.shape)
|
| 1310 |
+
|
| 1311 |
+
# intermediate latents
|
| 1312 |
+
t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
|
| 1313 |
+
xts = torch.zeros(size=variance_noise_shape, device=self.device, dtype=uncond_embedding.dtype)
|
| 1314 |
+
|
| 1315 |
+
for t in reversed(timesteps):
|
| 1316 |
+
idx = num_inversion_steps - t_to_idx[int(t)] - 1
|
| 1317 |
+
noise = randn_tensor(shape=x0.shape, generator=generator, device=self.device, dtype=x0.dtype)
|
| 1318 |
+
xts[idx] = self.scheduler.add_noise(x0, noise, torch.Tensor([t]))
|
| 1319 |
+
xts = torch.cat([x0.unsqueeze(0), xts], dim=0)
|
| 1320 |
+
|
| 1321 |
+
self.scheduler.set_timesteps(len(self.scheduler.timesteps))
|
| 1322 |
+
# noise maps
|
| 1323 |
+
zs = torch.zeros(size=variance_noise_shape, device=self.device, dtype=uncond_embedding.dtype)
|
| 1324 |
+
|
| 1325 |
+
with self.progress_bar(total=len(timesteps)) as progress_bar:
|
| 1326 |
+
for t in timesteps:
|
| 1327 |
+
idx = num_inversion_steps - t_to_idx[int(t)] - 1
|
| 1328 |
+
# 1. predict noise residual
|
| 1329 |
+
xt = xts[idx + 1]
|
| 1330 |
+
|
| 1331 |
+
noise_pred = self.unet(xt, timestep=t, encoder_hidden_states=uncond_embedding).sample
|
| 1332 |
+
|
| 1333 |
+
if not source_prompt == "":
|
| 1334 |
+
noise_pred_cond = self.unet(xt, timestep=t, encoder_hidden_states=text_embeddings).sample
|
| 1335 |
+
noise_pred = noise_pred + source_guidance_scale * (noise_pred_cond - noise_pred)
|
| 1336 |
+
|
| 1337 |
+
xtm1 = xts[idx]
|
| 1338 |
+
z, xtm1_corrected = compute_noise(self.scheduler, xtm1, xt, t, noise_pred, self.eta)
|
| 1339 |
+
zs[idx] = z
|
| 1340 |
+
|
| 1341 |
+
# correction to avoid error accumulation
|
| 1342 |
+
xts[idx] = xtm1_corrected
|
| 1343 |
+
|
| 1344 |
+
progress_bar.update()
|
| 1345 |
+
|
| 1346 |
+
self.init_latents = xts[-1].expand(self.batch_size, -1, -1, -1)
|
| 1347 |
+
zs = zs.flip(0)
|
| 1348 |
+
self.zs = zs
|
| 1349 |
+
|
| 1350 |
+
return LEditsPPInversionPipelineOutput(images=resized, vae_reconstruction_images=image_rec)
|
| 1351 |
+
|
| 1352 |
+
@torch.no_grad()
|
| 1353 |
+
def encode_image(self, image, dtype=None, height=None, width=None, resize_mode="default", crops_coords=None):
|
| 1354 |
+
image = self.image_processor.preprocess(
|
| 1355 |
+
image=image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
|
| 1356 |
+
)
|
| 1357 |
+
resized = self.image_processor.postprocess(image=image, output_type="pil")
|
| 1358 |
+
|
| 1359 |
+
if max(image.shape[-2:]) > self.vae.config["sample_size"] * 1.5:
|
| 1360 |
+
logger.warning(
|
| 1361 |
+
"Your input images far exceed the default resolution of the underlying diffusion model. "
|
| 1362 |
+
"The output images may contain severe artifacts! "
|
| 1363 |
+
"Consider down-sampling the input using the `height` and `width` parameters"
|
| 1364 |
+
)
|
| 1365 |
+
image = image.to(dtype)
|
| 1366 |
+
|
| 1367 |
+
x0 = self.vae.encode(image.to(self.device)).latent_dist.mode()
|
| 1368 |
+
x0 = x0.to(dtype)
|
| 1369 |
+
x0 = self.vae.config.scaling_factor * x0
|
| 1370 |
+
return x0, resized
|
| 1371 |
+
|
| 1372 |
+
|
| 1373 |
+
def compute_noise_ddim(scheduler, prev_latents, latents, timestep, noise_pred, eta):
|
| 1374 |
+
# 1. get previous step value (=t-1)
|
| 1375 |
+
prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
|
| 1376 |
+
|
| 1377 |
+
# 2. compute alphas, betas
|
| 1378 |
+
alpha_prod_t = scheduler.alphas_cumprod[timestep]
|
| 1379 |
+
alpha_prod_t_prev = (
|
| 1380 |
+
scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
|
| 1381 |
+
)
|
| 1382 |
+
|
| 1383 |
+
beta_prod_t = 1 - alpha_prod_t
|
| 1384 |
+
|
| 1385 |
+
# 3. compute predicted original sample from predicted noise also called
|
| 1386 |
+
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 1387 |
+
pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
|
| 1388 |
+
|
| 1389 |
+
# 4. Clip "predicted x_0"
|
| 1390 |
+
if scheduler.config.clip_sample:
|
| 1391 |
+
pred_original_sample = torch.clamp(pred_original_sample, -1, 1)
|
| 1392 |
+
|
| 1393 |
+
# 5. compute variance: "sigma_t(η)" -> see formula (16)
|
| 1394 |
+
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
|
| 1395 |
+
variance = scheduler._get_variance(timestep, prev_timestep)
|
| 1396 |
+
std_dev_t = eta * variance ** (0.5)
|
| 1397 |
+
|
| 1398 |
+
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 1399 |
+
pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * noise_pred
|
| 1400 |
+
|
| 1401 |
+
# modifed so that updated xtm1 is returned as well (to avoid error accumulation)
|
| 1402 |
+
mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
|
| 1403 |
+
if variance > 0.0:
|
| 1404 |
+
noise = (prev_latents - mu_xt) / (variance ** (0.5) * eta)
|
| 1405 |
+
else:
|
| 1406 |
+
noise = torch.tensor([0.0]).to(latents.device)
|
| 1407 |
+
|
| 1408 |
+
return noise, mu_xt + (eta * variance**0.5) * noise
|
| 1409 |
+
|
| 1410 |
+
|
| 1411 |
+
def compute_noise_sde_dpm_pp_2nd(scheduler, prev_latents, latents, timestep, noise_pred, eta):
|
| 1412 |
+
def first_order_update(model_output, sample): # timestep, prev_timestep, sample):
|
| 1413 |
+
sigma_t, sigma_s = scheduler.sigmas[scheduler.step_index + 1], scheduler.sigmas[scheduler.step_index]
|
| 1414 |
+
alpha_t, sigma_t = scheduler._sigma_to_alpha_sigma_t(sigma_t)
|
| 1415 |
+
alpha_s, sigma_s = scheduler._sigma_to_alpha_sigma_t(sigma_s)
|
| 1416 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 1417 |
+
lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
|
| 1418 |
+
|
| 1419 |
+
h = lambda_t - lambda_s
|
| 1420 |
+
|
| 1421 |
+
mu_xt = (sigma_t / sigma_s * torch.exp(-h)) * sample + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
|
| 1422 |
+
|
| 1423 |
+
mu_xt = scheduler.dpm_solver_first_order_update(
|
| 1424 |
+
model_output=model_output, sample=sample, noise=torch.zeros_like(sample)
|
| 1425 |
+
)
|
| 1426 |
+
|
| 1427 |
+
sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
|
| 1428 |
+
if sigma > 0.0:
|
| 1429 |
+
noise = (prev_latents - mu_xt) / sigma
|
| 1430 |
+
else:
|
| 1431 |
+
noise = torch.tensor([0.0]).to(sample.device)
|
| 1432 |
+
|
| 1433 |
+
prev_sample = mu_xt + sigma * noise
|
| 1434 |
+
return noise, prev_sample
|
| 1435 |
+
|
| 1436 |
+
def second_order_update(model_output_list, sample): # timestep_list, prev_timestep, sample):
|
| 1437 |
+
sigma_t, sigma_s0, sigma_s1 = (
|
| 1438 |
+
scheduler.sigmas[scheduler.step_index + 1],
|
| 1439 |
+
scheduler.sigmas[scheduler.step_index],
|
| 1440 |
+
scheduler.sigmas[scheduler.step_index - 1],
|
| 1441 |
+
)
|
| 1442 |
+
|
| 1443 |
+
alpha_t, sigma_t = scheduler._sigma_to_alpha_sigma_t(sigma_t)
|
| 1444 |
+
alpha_s0, sigma_s0 = scheduler._sigma_to_alpha_sigma_t(sigma_s0)
|
| 1445 |
+
alpha_s1, sigma_s1 = scheduler._sigma_to_alpha_sigma_t(sigma_s1)
|
| 1446 |
+
|
| 1447 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 1448 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 1449 |
+
lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
|
| 1450 |
+
|
| 1451 |
+
m0, m1 = model_output_list[-1], model_output_list[-2]
|
| 1452 |
+
|
| 1453 |
+
h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
|
| 1454 |
+
r0 = h_0 / h
|
| 1455 |
+
D0, D1 = m0, (1.0 / r0) * (m0 - m1)
|
| 1456 |
+
|
| 1457 |
+
mu_xt = (
|
| 1458 |
+
(sigma_t / sigma_s0 * torch.exp(-h)) * sample
|
| 1459 |
+
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
|
| 1460 |
+
+ 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
|
| 1461 |
+
)
|
| 1462 |
+
|
| 1463 |
+
sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
|
| 1464 |
+
if sigma > 0.0:
|
| 1465 |
+
noise = (prev_latents - mu_xt) / sigma
|
| 1466 |
+
else:
|
| 1467 |
+
noise = torch.tensor([0.0]).to(sample.device)
|
| 1468 |
+
|
| 1469 |
+
prev_sample = mu_xt + sigma * noise
|
| 1470 |
+
|
| 1471 |
+
return noise, prev_sample
|
| 1472 |
+
|
| 1473 |
+
if scheduler.step_index is None:
|
| 1474 |
+
scheduler._init_step_index(timestep)
|
| 1475 |
+
|
| 1476 |
+
model_output = scheduler.convert_model_output(model_output=noise_pred, sample=latents)
|
| 1477 |
+
for i in range(scheduler.config.solver_order - 1):
|
| 1478 |
+
scheduler.model_outputs[i] = scheduler.model_outputs[i + 1]
|
| 1479 |
+
scheduler.model_outputs[-1] = model_output
|
| 1480 |
+
|
| 1481 |
+
if scheduler.lower_order_nums < 1:
|
| 1482 |
+
noise, prev_sample = first_order_update(model_output, latents)
|
| 1483 |
+
else:
|
| 1484 |
+
noise, prev_sample = second_order_update(scheduler.model_outputs, latents)
|
| 1485 |
+
|
| 1486 |
+
if scheduler.lower_order_nums < scheduler.config.solver_order:
|
| 1487 |
+
scheduler.lower_order_nums += 1
|
| 1488 |
+
|
| 1489 |
+
# upon completion increase step index by one
|
| 1490 |
+
scheduler._step_index += 1
|
| 1491 |
+
|
| 1492 |
+
return noise, prev_sample
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
+
def compute_noise(scheduler, *args):
|
| 1496 |
+
if isinstance(scheduler, DDIMScheduler):
|
| 1497 |
+
return compute_noise_ddim(scheduler, *args)
|
| 1498 |
+
elif (
|
| 1499 |
+
isinstance(scheduler, DPMSolverMultistepScheduler)
|
| 1500 |
+
and scheduler.config.algorithm_type == "sde-dpmsolver++"
|
| 1501 |
+
and scheduler.config.solver_order == 2
|
| 1502 |
+
):
|
| 1503 |
+
return compute_noise_sde_dpm_pp_2nd(scheduler, *args)
|
| 1504 |
+
else:
|
| 1505 |
+
raise NotImplementedError
|
evalkit_tf437/lib/python3.10/site-packages/diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py
ADDED
|
@@ -0,0 +1,1797 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import math
|
| 17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
from transformers import (
|
| 22 |
+
CLIPImageProcessor,
|
| 23 |
+
CLIPTextModel,
|
| 24 |
+
CLIPTextModelWithProjection,
|
| 25 |
+
CLIPTokenizer,
|
| 26 |
+
CLIPVisionModelWithProjection,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from ...image_processor import PipelineImageInput, VaeImageProcessor
|
| 30 |
+
from ...loaders import (
|
| 31 |
+
FromSingleFileMixin,
|
| 32 |
+
IPAdapterMixin,
|
| 33 |
+
StableDiffusionXLLoraLoaderMixin,
|
| 34 |
+
TextualInversionLoaderMixin,
|
| 35 |
+
)
|
| 36 |
+
from ...models import AutoencoderKL, UNet2DConditionModel
|
| 37 |
+
from ...models.attention_processor import (
|
| 38 |
+
Attention,
|
| 39 |
+
AttnProcessor,
|
| 40 |
+
AttnProcessor2_0,
|
| 41 |
+
LoRAAttnProcessor2_0,
|
| 42 |
+
LoRAXFormersAttnProcessor,
|
| 43 |
+
XFormersAttnProcessor,
|
| 44 |
+
)
|
| 45 |
+
from ...models.lora import adjust_lora_scale_text_encoder
|
| 46 |
+
from ...schedulers import DDIMScheduler, DPMSolverMultistepScheduler
|
| 47 |
+
from ...utils import (
|
| 48 |
+
USE_PEFT_BACKEND,
|
| 49 |
+
is_invisible_watermark_available,
|
| 50 |
+
is_torch_xla_available,
|
| 51 |
+
logging,
|
| 52 |
+
replace_example_docstring,
|
| 53 |
+
scale_lora_layers,
|
| 54 |
+
unscale_lora_layers,
|
| 55 |
+
)
|
| 56 |
+
from ...utils.torch_utils import randn_tensor
|
| 57 |
+
from ..pipeline_utils import DiffusionPipeline
|
| 58 |
+
from .pipeline_output import LEditsPPDiffusionPipelineOutput, LEditsPPInversionPipelineOutput
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if is_invisible_watermark_available():
|
| 62 |
+
from ..stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
|
| 63 |
+
|
| 64 |
+
if is_torch_xla_available():
|
| 65 |
+
import torch_xla.core.xla_model as xm
|
| 66 |
+
|
| 67 |
+
XLA_AVAILABLE = True
|
| 68 |
+
else:
|
| 69 |
+
XLA_AVAILABLE = False
|
| 70 |
+
|
| 71 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 72 |
+
|
| 73 |
+
EXAMPLE_DOC_STRING = """
|
| 74 |
+
Examples:
|
| 75 |
+
```py
|
| 76 |
+
>>> import torch
|
| 77 |
+
>>> import PIL
|
| 78 |
+
>>> import requests
|
| 79 |
+
>>> from io import BytesIO
|
| 80 |
+
|
| 81 |
+
>>> from diffusers import LEditsPPPipelineStableDiffusionXL
|
| 82 |
+
|
| 83 |
+
>>> pipe = LEditsPPPipelineStableDiffusionXL.from_pretrained(
|
| 84 |
+
... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 85 |
+
... )
|
| 86 |
+
>>> pipe = pipe.to("cuda")
|
| 87 |
+
|
| 88 |
+
>>> def download_image(url):
|
| 89 |
+
... response = requests.get(url)
|
| 90 |
+
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
|
| 91 |
+
|
| 92 |
+
>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/tennis.jpg"
|
| 93 |
+
>>> image = download_image(img_url)
|
| 94 |
+
|
| 95 |
+
>>> _ = pipe.invert(
|
| 96 |
+
... image = image,
|
| 97 |
+
... num_inversion_steps=50,
|
| 98 |
+
... skip=0.2
|
| 99 |
+
... )
|
| 100 |
+
|
| 101 |
+
>>> edited_image = pipe(
|
| 102 |
+
... editing_prompt=["tennis ball","tomato"],
|
| 103 |
+
... reverse_editing_direction=[True,False],
|
| 104 |
+
... edit_guidance_scale=[5.0,10.0],
|
| 105 |
+
... edit_threshold=[0.9,0.85],
|
| 106 |
+
).images[0]
|
| 107 |
+
```
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# Copied from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.LeditsAttentionStore
|
| 112 |
+
class LeditsAttentionStore:
|
| 113 |
+
@staticmethod
|
| 114 |
+
def get_empty_store():
|
| 115 |
+
return {"down_cross": [], "mid_cross": [], "up_cross": [], "down_self": [], "mid_self": [], "up_self": []}
|
| 116 |
+
|
| 117 |
+
def __call__(self, attn, is_cross: bool, place_in_unet: str, editing_prompts, PnP=False):
|
| 118 |
+
# attn.shape = batch_size * head_size, seq_len query, seq_len_key
|
| 119 |
+
if attn.shape[1] <= self.max_size:
|
| 120 |
+
bs = 1 + int(PnP) + editing_prompts
|
| 121 |
+
skip = 2 if PnP else 1 # skip PnP & unconditional
|
| 122 |
+
attn = torch.stack(attn.split(self.batch_size)).permute(1, 0, 2, 3)
|
| 123 |
+
source_batch_size = int(attn.shape[1] // bs)
|
| 124 |
+
self.forward(attn[:, skip * source_batch_size :], is_cross, place_in_unet)
|
| 125 |
+
|
| 126 |
+
def forward(self, attn, is_cross: bool, place_in_unet: str):
|
| 127 |
+
key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
|
| 128 |
+
|
| 129 |
+
self.step_store[key].append(attn)
|
| 130 |
+
|
| 131 |
+
def between_steps(self, store_step=True):
|
| 132 |
+
if store_step:
|
| 133 |
+
if self.average:
|
| 134 |
+
if len(self.attention_store) == 0:
|
| 135 |
+
self.attention_store = self.step_store
|
| 136 |
+
else:
|
| 137 |
+
for key in self.attention_store:
|
| 138 |
+
for i in range(len(self.attention_store[key])):
|
| 139 |
+
self.attention_store[key][i] += self.step_store[key][i]
|
| 140 |
+
else:
|
| 141 |
+
if len(self.attention_store) == 0:
|
| 142 |
+
self.attention_store = [self.step_store]
|
| 143 |
+
else:
|
| 144 |
+
self.attention_store.append(self.step_store)
|
| 145 |
+
|
| 146 |
+
self.cur_step += 1
|
| 147 |
+
self.step_store = self.get_empty_store()
|
| 148 |
+
|
| 149 |
+
def get_attention(self, step: int):
|
| 150 |
+
if self.average:
|
| 151 |
+
attention = {
|
| 152 |
+
key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store
|
| 153 |
+
}
|
| 154 |
+
else:
|
| 155 |
+
assert step is not None
|
| 156 |
+
attention = self.attention_store[step]
|
| 157 |
+
return attention
|
| 158 |
+
|
| 159 |
+
def aggregate_attention(
|
| 160 |
+
self, attention_maps, prompts, res: Union[int, Tuple[int]], from_where: List[str], is_cross: bool, select: int
|
| 161 |
+
):
|
| 162 |
+
out = [[] for x in range(self.batch_size)]
|
| 163 |
+
if isinstance(res, int):
|
| 164 |
+
num_pixels = res**2
|
| 165 |
+
resolution = (res, res)
|
| 166 |
+
else:
|
| 167 |
+
num_pixels = res[0] * res[1]
|
| 168 |
+
resolution = res[:2]
|
| 169 |
+
|
| 170 |
+
for location in from_where:
|
| 171 |
+
for bs_item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
|
| 172 |
+
for batch, item in enumerate(bs_item):
|
| 173 |
+
if item.shape[1] == num_pixels:
|
| 174 |
+
cross_maps = item.reshape(len(prompts), -1, *resolution, item.shape[-1])[select]
|
| 175 |
+
out[batch].append(cross_maps)
|
| 176 |
+
|
| 177 |
+
out = torch.stack([torch.cat(x, dim=0) for x in out])
|
| 178 |
+
# average over heads
|
| 179 |
+
out = out.sum(1) / out.shape[1]
|
| 180 |
+
return out
|
| 181 |
+
|
| 182 |
+
def __init__(self, average: bool, batch_size=1, max_resolution=16, max_size: int = None):
|
| 183 |
+
self.step_store = self.get_empty_store()
|
| 184 |
+
self.attention_store = []
|
| 185 |
+
self.cur_step = 0
|
| 186 |
+
self.average = average
|
| 187 |
+
self.batch_size = batch_size
|
| 188 |
+
if max_size is None:
|
| 189 |
+
self.max_size = max_resolution**2
|
| 190 |
+
elif max_size is not None and max_resolution is None:
|
| 191 |
+
self.max_size = max_size
|
| 192 |
+
else:
|
| 193 |
+
raise ValueError("Only allowed to set one of max_resolution or max_size")
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# Copied from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.LeditsGaussianSmoothing
|
| 197 |
+
class LeditsGaussianSmoothing:
|
| 198 |
+
def __init__(self, device):
|
| 199 |
+
kernel_size = [3, 3]
|
| 200 |
+
sigma = [0.5, 0.5]
|
| 201 |
+
|
| 202 |
+
# The gaussian kernel is the product of the gaussian function of each dimension.
|
| 203 |
+
kernel = 1
|
| 204 |
+
meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
|
| 205 |
+
for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
|
| 206 |
+
mean = (size - 1) / 2
|
| 207 |
+
kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
|
| 208 |
+
|
| 209 |
+
# Make sure sum of values in gaussian kernel equals 1.
|
| 210 |
+
kernel = kernel / torch.sum(kernel)
|
| 211 |
+
|
| 212 |
+
# Reshape to depthwise convolutional weight
|
| 213 |
+
kernel = kernel.view(1, 1, *kernel.size())
|
| 214 |
+
kernel = kernel.repeat(1, *[1] * (kernel.dim() - 1))
|
| 215 |
+
|
| 216 |
+
self.weight = kernel.to(device)
|
| 217 |
+
|
| 218 |
+
def __call__(self, input):
|
| 219 |
+
"""
|
| 220 |
+
Arguments:
|
| 221 |
+
Apply gaussian filter to input.
|
| 222 |
+
input (torch.Tensor): Input to apply gaussian filter on.
|
| 223 |
+
Returns:
|
| 224 |
+
filtered (torch.Tensor): Filtered output.
|
| 225 |
+
"""
|
| 226 |
+
return F.conv2d(input, weight=self.weight.to(input.dtype))
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# Copied from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.LEDITSCrossAttnProcessor
|
| 230 |
+
class LEDITSCrossAttnProcessor:
|
| 231 |
+
def __init__(self, attention_store, place_in_unet, pnp, editing_prompts):
|
| 232 |
+
self.attnstore = attention_store
|
| 233 |
+
self.place_in_unet = place_in_unet
|
| 234 |
+
self.editing_prompts = editing_prompts
|
| 235 |
+
self.pnp = pnp
|
| 236 |
+
|
| 237 |
+
def __call__(
|
| 238 |
+
self,
|
| 239 |
+
attn: Attention,
|
| 240 |
+
hidden_states,
|
| 241 |
+
encoder_hidden_states,
|
| 242 |
+
attention_mask=None,
|
| 243 |
+
temb=None,
|
| 244 |
+
):
|
| 245 |
+
batch_size, sequence_length, _ = (
|
| 246 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
| 247 |
+
)
|
| 248 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
| 249 |
+
|
| 250 |
+
query = attn.to_q(hidden_states)
|
| 251 |
+
|
| 252 |
+
if encoder_hidden_states is None:
|
| 253 |
+
encoder_hidden_states = hidden_states
|
| 254 |
+
elif attn.norm_cross:
|
| 255 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
| 256 |
+
|
| 257 |
+
key = attn.to_k(encoder_hidden_states)
|
| 258 |
+
value = attn.to_v(encoder_hidden_states)
|
| 259 |
+
|
| 260 |
+
query = attn.head_to_batch_dim(query)
|
| 261 |
+
key = attn.head_to_batch_dim(key)
|
| 262 |
+
value = attn.head_to_batch_dim(value)
|
| 263 |
+
|
| 264 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
| 265 |
+
self.attnstore(
|
| 266 |
+
attention_probs,
|
| 267 |
+
is_cross=True,
|
| 268 |
+
place_in_unet=self.place_in_unet,
|
| 269 |
+
editing_prompts=self.editing_prompts,
|
| 270 |
+
PnP=self.pnp,
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
hidden_states = torch.bmm(attention_probs, value)
|
| 274 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
| 275 |
+
|
| 276 |
+
# linear proj
|
| 277 |
+
hidden_states = attn.to_out[0](hidden_states)
|
| 278 |
+
# dropout
|
| 279 |
+
hidden_states = attn.to_out[1](hidden_states)
|
| 280 |
+
|
| 281 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
| 282 |
+
return hidden_states
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class LEditsPPPipelineStableDiffusionXL(
|
| 286 |
+
DiffusionPipeline,
|
| 287 |
+
FromSingleFileMixin,
|
| 288 |
+
StableDiffusionXLLoraLoaderMixin,
|
| 289 |
+
TextualInversionLoaderMixin,
|
| 290 |
+
IPAdapterMixin,
|
| 291 |
+
):
|
| 292 |
+
"""
|
| 293 |
+
Pipeline for textual image editing using LEDits++ with Stable Diffusion XL.
|
| 294 |
+
|
| 295 |
+
This model inherits from [`DiffusionPipeline`] and builds on the [`StableDiffusionXLPipeline`]. Check the superclass
|
| 296 |
+
documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular
|
| 297 |
+
device, etc.).
|
| 298 |
+
|
| 299 |
+
In addition the pipeline inherits the following loading methods:
|
| 300 |
+
- *LoRA*: [`LEditsPPPipelineStableDiffusionXL.load_lora_weights`]
|
| 301 |
+
- *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
|
| 302 |
+
|
| 303 |
+
as well as the following saving methods:
|
| 304 |
+
- *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
vae ([`AutoencoderKL`]):
|
| 308 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 309 |
+
text_encoder ([`~transformers.CLIPTextModel`]):
|
| 310 |
+
Frozen text-encoder. Stable Diffusion XL uses the text portion of
|
| 311 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
| 312 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 313 |
+
text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
|
| 314 |
+
Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
|
| 315 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
| 316 |
+
specifically the
|
| 317 |
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
| 318 |
+
variant.
|
| 319 |
+
tokenizer ([`~transformers.CLIPTokenizer`]):
|
| 320 |
+
Tokenizer of class
|
| 321 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 322 |
+
tokenizer_2 ([`~transformers.CLIPTokenizer`]):
|
| 323 |
+
Second Tokenizer of class
|
| 324 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 325 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
| 326 |
+
scheduler ([`DPMSolverMultistepScheduler`] or [`DDIMScheduler`]):
|
| 327 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
|
| 328 |
+
[`DPMSolverMultistepScheduler`] or [`DDIMScheduler`]. If any other scheduler is passed it will automatically
|
| 329 |
+
be set to [`DPMSolverMultistepScheduler`].
|
| 330 |
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
| 331 |
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
| 332 |
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
| 333 |
+
add_watermarker (`bool`, *optional*):
|
| 334 |
+
Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
|
| 335 |
+
watermark output images. If not defined, it will default to True if the package is installed, otherwise no
|
| 336 |
+
watermarker will be used.
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
|
| 340 |
+
_optional_components = [
|
| 341 |
+
"tokenizer",
|
| 342 |
+
"tokenizer_2",
|
| 343 |
+
"text_encoder",
|
| 344 |
+
"text_encoder_2",
|
| 345 |
+
"image_encoder",
|
| 346 |
+
"feature_extractor",
|
| 347 |
+
]
|
| 348 |
+
_callback_tensor_inputs = [
|
| 349 |
+
"latents",
|
| 350 |
+
"prompt_embeds",
|
| 351 |
+
"negative_prompt_embeds",
|
| 352 |
+
"add_text_embeds",
|
| 353 |
+
"add_time_ids",
|
| 354 |
+
"negative_pooled_prompt_embeds",
|
| 355 |
+
"negative_add_time_ids",
|
| 356 |
+
]
|
| 357 |
+
|
| 358 |
+
def __init__(
|
| 359 |
+
self,
|
| 360 |
+
vae: AutoencoderKL,
|
| 361 |
+
text_encoder: CLIPTextModel,
|
| 362 |
+
text_encoder_2: CLIPTextModelWithProjection,
|
| 363 |
+
tokenizer: CLIPTokenizer,
|
| 364 |
+
tokenizer_2: CLIPTokenizer,
|
| 365 |
+
unet: UNet2DConditionModel,
|
| 366 |
+
scheduler: Union[DPMSolverMultistepScheduler, DDIMScheduler],
|
| 367 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
| 368 |
+
feature_extractor: CLIPImageProcessor = None,
|
| 369 |
+
force_zeros_for_empty_prompt: bool = True,
|
| 370 |
+
add_watermarker: Optional[bool] = None,
|
| 371 |
+
):
|
| 372 |
+
super().__init__()
|
| 373 |
+
|
| 374 |
+
self.register_modules(
|
| 375 |
+
vae=vae,
|
| 376 |
+
text_encoder=text_encoder,
|
| 377 |
+
text_encoder_2=text_encoder_2,
|
| 378 |
+
tokenizer=tokenizer,
|
| 379 |
+
tokenizer_2=tokenizer_2,
|
| 380 |
+
unet=unet,
|
| 381 |
+
scheduler=scheduler,
|
| 382 |
+
image_encoder=image_encoder,
|
| 383 |
+
feature_extractor=feature_extractor,
|
| 384 |
+
)
|
| 385 |
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
| 386 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 387 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 388 |
+
|
| 389 |
+
if not isinstance(scheduler, DDIMScheduler) and not isinstance(scheduler, DPMSolverMultistepScheduler):
|
| 390 |
+
self.scheduler = DPMSolverMultistepScheduler.from_config(
|
| 391 |
+
scheduler.config, algorithm_type="sde-dpmsolver++", solver_order=2
|
| 392 |
+
)
|
| 393 |
+
logger.warning(
|
| 394 |
+
"This pipeline only supports DDIMScheduler and DPMSolverMultistepScheduler. "
|
| 395 |
+
"The scheduler has been changed to DPMSolverMultistepScheduler."
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
self.default_sample_size = self.unet.config.sample_size
|
| 399 |
+
|
| 400 |
+
add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
|
| 401 |
+
|
| 402 |
+
if add_watermarker:
|
| 403 |
+
self.watermark = StableDiffusionXLWatermarker()
|
| 404 |
+
else:
|
| 405 |
+
self.watermark = None
|
| 406 |
+
self.inversion_steps = None
|
| 407 |
+
|
| 408 |
+
def encode_prompt(
|
| 409 |
+
self,
|
| 410 |
+
device: Optional[torch.device] = None,
|
| 411 |
+
num_images_per_prompt: int = 1,
|
| 412 |
+
negative_prompt: Optional[str] = None,
|
| 413 |
+
negative_prompt_2: Optional[str] = None,
|
| 414 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 415 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 416 |
+
lora_scale: Optional[float] = None,
|
| 417 |
+
clip_skip: Optional[int] = None,
|
| 418 |
+
enable_edit_guidance: bool = True,
|
| 419 |
+
editing_prompt: Optional[str] = None,
|
| 420 |
+
editing_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 421 |
+
editing_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 422 |
+
) -> object:
|
| 423 |
+
r"""
|
| 424 |
+
Encodes the prompt into text encoder hidden states.
|
| 425 |
+
|
| 426 |
+
Args:
|
| 427 |
+
device: (`torch.device`):
|
| 428 |
+
torch device
|
| 429 |
+
num_images_per_prompt (`int`):
|
| 430 |
+
number of images that should be generated per prompt
|
| 431 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 432 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 433 |
+
`negative_prompt_embeds` instead.
|
| 434 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 435 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 436 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
| 437 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 438 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 439 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 440 |
+
argument.
|
| 441 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 442 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 443 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 444 |
+
input argument.
|
| 445 |
+
lora_scale (`float`, *optional*):
|
| 446 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 447 |
+
clip_skip (`int`, *optional*):
|
| 448 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 449 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 450 |
+
enable_edit_guidance (`bool`):
|
| 451 |
+
Whether to guide towards an editing prompt or not.
|
| 452 |
+
editing_prompt (`str` or `List[str]`, *optional*):
|
| 453 |
+
Editing prompt(s) to be encoded. If not defined and 'enable_edit_guidance' is True, one has to pass
|
| 454 |
+
`editing_prompt_embeds` instead.
|
| 455 |
+
editing_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 456 |
+
Pre-generated edit text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 457 |
+
weighting. If not provided and 'enable_edit_guidance' is True, editing_prompt_embeds will be generated from `editing_prompt` input
|
| 458 |
+
argument.
|
| 459 |
+
editing_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 460 |
+
Pre-generated edit pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 461 |
+
weighting. If not provided, pooled editing_pooled_prompt_embeds will be generated from `editing_prompt`
|
| 462 |
+
input argument.
|
| 463 |
+
"""
|
| 464 |
+
device = device or self._execution_device
|
| 465 |
+
|
| 466 |
+
# set lora scale so that monkey patched LoRA
|
| 467 |
+
# function of text encoder can correctly access it
|
| 468 |
+
if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
|
| 469 |
+
self._lora_scale = lora_scale
|
| 470 |
+
|
| 471 |
+
# dynamically adjust the LoRA scale
|
| 472 |
+
if self.text_encoder is not None:
|
| 473 |
+
if not USE_PEFT_BACKEND:
|
| 474 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
| 475 |
+
else:
|
| 476 |
+
scale_lora_layers(self.text_encoder, lora_scale)
|
| 477 |
+
|
| 478 |
+
if self.text_encoder_2 is not None:
|
| 479 |
+
if not USE_PEFT_BACKEND:
|
| 480 |
+
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
| 481 |
+
else:
|
| 482 |
+
scale_lora_layers(self.text_encoder_2, lora_scale)
|
| 483 |
+
|
| 484 |
+
batch_size = self.batch_size
|
| 485 |
+
|
| 486 |
+
# Define tokenizers and text encoders
|
| 487 |
+
tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
|
| 488 |
+
text_encoders = (
|
| 489 |
+
[self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
|
| 490 |
+
)
|
| 491 |
+
num_edit_tokens = 0
|
| 492 |
+
|
| 493 |
+
# get unconditional embeddings for classifier free guidance
|
| 494 |
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
| 495 |
+
|
| 496 |
+
if negative_prompt_embeds is None:
|
| 497 |
+
negative_prompt = negative_prompt or ""
|
| 498 |
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
| 499 |
+
|
| 500 |
+
# normalize str to list
|
| 501 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 502 |
+
negative_prompt_2 = (
|
| 503 |
+
batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
uncond_tokens: List[str]
|
| 507 |
+
|
| 508 |
+
if batch_size != len(negative_prompt):
|
| 509 |
+
raise ValueError(
|
| 510 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but image inversion "
|
| 511 |
+
f" has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 512 |
+
" the batch size of the input images."
|
| 513 |
+
)
|
| 514 |
+
else:
|
| 515 |
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
| 516 |
+
|
| 517 |
+
negative_prompt_embeds_list = []
|
| 518 |
+
for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
|
| 519 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 520 |
+
negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
|
| 521 |
+
|
| 522 |
+
uncond_input = tokenizer(
|
| 523 |
+
negative_prompt,
|
| 524 |
+
padding="max_length",
|
| 525 |
+
max_length=tokenizer.model_max_length,
|
| 526 |
+
truncation=True,
|
| 527 |
+
return_tensors="pt",
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
negative_prompt_embeds = text_encoder(
|
| 531 |
+
uncond_input.input_ids.to(device),
|
| 532 |
+
output_hidden_states=True,
|
| 533 |
+
)
|
| 534 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 535 |
+
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
| 536 |
+
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
| 537 |
+
|
| 538 |
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
| 539 |
+
|
| 540 |
+
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
| 541 |
+
|
| 542 |
+
if zero_out_negative_prompt:
|
| 543 |
+
negative_prompt_embeds = torch.zeros_like(negative_prompt_embeds)
|
| 544 |
+
negative_pooled_prompt_embeds = torch.zeros_like(negative_pooled_prompt_embeds)
|
| 545 |
+
|
| 546 |
+
if enable_edit_guidance and editing_prompt_embeds is None:
|
| 547 |
+
editing_prompt_2 = editing_prompt
|
| 548 |
+
|
| 549 |
+
editing_prompts = [editing_prompt, editing_prompt_2]
|
| 550 |
+
edit_prompt_embeds_list = []
|
| 551 |
+
|
| 552 |
+
for editing_prompt, tokenizer, text_encoder in zip(editing_prompts, tokenizers, text_encoders):
|
| 553 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 554 |
+
editing_prompt = self.maybe_convert_prompt(editing_prompt, tokenizer)
|
| 555 |
+
|
| 556 |
+
max_length = negative_prompt_embeds.shape[1]
|
| 557 |
+
edit_concepts_input = tokenizer(
|
| 558 |
+
# [x for item in editing_prompt for x in repeat(item, batch_size)],
|
| 559 |
+
editing_prompt,
|
| 560 |
+
padding="max_length",
|
| 561 |
+
max_length=max_length,
|
| 562 |
+
truncation=True,
|
| 563 |
+
return_tensors="pt",
|
| 564 |
+
return_length=True,
|
| 565 |
+
)
|
| 566 |
+
num_edit_tokens = edit_concepts_input.length - 2
|
| 567 |
+
|
| 568 |
+
edit_concepts_embeds = text_encoder(
|
| 569 |
+
edit_concepts_input.input_ids.to(device),
|
| 570 |
+
output_hidden_states=True,
|
| 571 |
+
)
|
| 572 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 573 |
+
editing_pooled_prompt_embeds = edit_concepts_embeds[0]
|
| 574 |
+
if clip_skip is None:
|
| 575 |
+
edit_concepts_embeds = edit_concepts_embeds.hidden_states[-2]
|
| 576 |
+
else:
|
| 577 |
+
# "2" because SDXL always indexes from the penultimate layer.
|
| 578 |
+
edit_concepts_embeds = edit_concepts_embeds.hidden_states[-(clip_skip + 2)]
|
| 579 |
+
|
| 580 |
+
edit_prompt_embeds_list.append(edit_concepts_embeds)
|
| 581 |
+
|
| 582 |
+
edit_concepts_embeds = torch.concat(edit_prompt_embeds_list, dim=-1)
|
| 583 |
+
elif not enable_edit_guidance:
|
| 584 |
+
edit_concepts_embeds = None
|
| 585 |
+
editing_pooled_prompt_embeds = None
|
| 586 |
+
|
| 587 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
| 588 |
+
bs_embed, seq_len, _ = negative_prompt_embeds.shape
|
| 589 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 590 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 591 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
| 592 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 593 |
+
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
| 594 |
+
|
| 595 |
+
if enable_edit_guidance:
|
| 596 |
+
bs_embed_edit, seq_len, _ = edit_concepts_embeds.shape
|
| 597 |
+
edit_concepts_embeds = edit_concepts_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
| 598 |
+
edit_concepts_embeds = edit_concepts_embeds.repeat(1, num_images_per_prompt, 1)
|
| 599 |
+
edit_concepts_embeds = edit_concepts_embeds.view(bs_embed_edit * num_images_per_prompt, seq_len, -1)
|
| 600 |
+
|
| 601 |
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 602 |
+
bs_embed * num_images_per_prompt, -1
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
if enable_edit_guidance:
|
| 606 |
+
editing_pooled_prompt_embeds = editing_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 607 |
+
bs_embed_edit * num_images_per_prompt, -1
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
if self.text_encoder is not None:
|
| 611 |
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 612 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 613 |
+
unscale_lora_layers(self.text_encoder, lora_scale)
|
| 614 |
+
|
| 615 |
+
if self.text_encoder_2 is not None:
|
| 616 |
+
if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
|
| 617 |
+
# Retrieve the original scale by scaling back the LoRA layers
|
| 618 |
+
unscale_lora_layers(self.text_encoder_2, lora_scale)
|
| 619 |
+
|
| 620 |
+
return (
|
| 621 |
+
negative_prompt_embeds,
|
| 622 |
+
edit_concepts_embeds,
|
| 623 |
+
negative_pooled_prompt_embeds,
|
| 624 |
+
editing_pooled_prompt_embeds,
|
| 625 |
+
num_edit_tokens,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 629 |
+
def prepare_extra_step_kwargs(self, eta, generator=None):
|
| 630 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 631 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 632 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 633 |
+
# and should be between [0, 1]
|
| 634 |
+
|
| 635 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 636 |
+
extra_step_kwargs = {}
|
| 637 |
+
if accepts_eta:
|
| 638 |
+
extra_step_kwargs["eta"] = eta
|
| 639 |
+
|
| 640 |
+
# check if the scheduler accepts generator
|
| 641 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 642 |
+
if accepts_generator:
|
| 643 |
+
extra_step_kwargs["generator"] = generator
|
| 644 |
+
return extra_step_kwargs
|
| 645 |
+
|
| 646 |
+
def check_inputs(
|
| 647 |
+
self,
|
| 648 |
+
negative_prompt=None,
|
| 649 |
+
negative_prompt_2=None,
|
| 650 |
+
negative_prompt_embeds=None,
|
| 651 |
+
negative_pooled_prompt_embeds=None,
|
| 652 |
+
):
|
| 653 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 654 |
+
raise ValueError(
|
| 655 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 656 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 657 |
+
)
|
| 658 |
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
| 659 |
+
raise ValueError(
|
| 660 |
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
| 661 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
| 665 |
+
raise ValueError(
|
| 666 |
+
"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`."
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
# Modified from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 670 |
+
def prepare_latents(self, device, latents):
|
| 671 |
+
latents = latents.to(device)
|
| 672 |
+
|
| 673 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 674 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 675 |
+
return latents
|
| 676 |
+
|
| 677 |
+
def _get_add_time_ids(
|
| 678 |
+
self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
|
| 679 |
+
):
|
| 680 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 681 |
+
|
| 682 |
+
passed_add_embed_dim = (
|
| 683 |
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
|
| 684 |
+
)
|
| 685 |
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
| 686 |
+
|
| 687 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
| 688 |
+
raise ValueError(
|
| 689 |
+
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`."
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 693 |
+
return add_time_ids
|
| 694 |
+
|
| 695 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
| 696 |
+
def upcast_vae(self):
|
| 697 |
+
dtype = self.vae.dtype
|
| 698 |
+
self.vae.to(dtype=torch.float32)
|
| 699 |
+
use_torch_2_0_or_xformers = isinstance(
|
| 700 |
+
self.vae.decoder.mid_block.attentions[0].processor,
|
| 701 |
+
(
|
| 702 |
+
AttnProcessor2_0,
|
| 703 |
+
XFormersAttnProcessor,
|
| 704 |
+
LoRAXFormersAttnProcessor,
|
| 705 |
+
LoRAAttnProcessor2_0,
|
| 706 |
+
),
|
| 707 |
+
)
|
| 708 |
+
# if xformers or torch_2_0 is used attention block does not need
|
| 709 |
+
# to be in float32 which can save lots of memory
|
| 710 |
+
if use_torch_2_0_or_xformers:
|
| 711 |
+
self.vae.post_quant_conv.to(dtype)
|
| 712 |
+
self.vae.decoder.conv_in.to(dtype)
|
| 713 |
+
self.vae.decoder.mid_block.to(dtype)
|
| 714 |
+
|
| 715 |
+
# Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
|
| 716 |
+
def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
|
| 717 |
+
"""
|
| 718 |
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
| 719 |
+
|
| 720 |
+
Args:
|
| 721 |
+
timesteps (`torch.Tensor`):
|
| 722 |
+
generate embedding vectors at these timesteps
|
| 723 |
+
embedding_dim (`int`, *optional*, defaults to 512):
|
| 724 |
+
dimension of the embeddings to generate
|
| 725 |
+
dtype:
|
| 726 |
+
data type of the generated embeddings
|
| 727 |
+
|
| 728 |
+
Returns:
|
| 729 |
+
`torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
|
| 730 |
+
"""
|
| 731 |
+
assert len(w.shape) == 1
|
| 732 |
+
w = w * 1000.0
|
| 733 |
+
|
| 734 |
+
half_dim = embedding_dim // 2
|
| 735 |
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
| 736 |
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
| 737 |
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
| 738 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 739 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 740 |
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
| 741 |
+
assert emb.shape == (w.shape[0], embedding_dim)
|
| 742 |
+
return emb
|
| 743 |
+
|
| 744 |
+
@property
|
| 745 |
+
def guidance_scale(self):
|
| 746 |
+
return self._guidance_scale
|
| 747 |
+
|
| 748 |
+
@property
|
| 749 |
+
def guidance_rescale(self):
|
| 750 |
+
return self._guidance_rescale
|
| 751 |
+
|
| 752 |
+
@property
|
| 753 |
+
def clip_skip(self):
|
| 754 |
+
return self._clip_skip
|
| 755 |
+
|
| 756 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 757 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 758 |
+
# corresponds to doing no classifier free guidance.
|
| 759 |
+
@property
|
| 760 |
+
def do_classifier_free_guidance(self):
|
| 761 |
+
return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
|
| 762 |
+
|
| 763 |
+
@property
|
| 764 |
+
def cross_attention_kwargs(self):
|
| 765 |
+
return self._cross_attention_kwargs
|
| 766 |
+
|
| 767 |
+
@property
|
| 768 |
+
def denoising_end(self):
|
| 769 |
+
return self._denoising_end
|
| 770 |
+
|
| 771 |
+
@property
|
| 772 |
+
def num_timesteps(self):
|
| 773 |
+
return self._num_timesteps
|
| 774 |
+
|
| 775 |
+
# Copied from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.LEditsPPPipelineStableDiffusion.prepare_unet
|
| 776 |
+
def prepare_unet(self, attention_store, PnP: bool = False):
|
| 777 |
+
attn_procs = {}
|
| 778 |
+
for name in self.unet.attn_processors.keys():
|
| 779 |
+
if name.startswith("mid_block"):
|
| 780 |
+
place_in_unet = "mid"
|
| 781 |
+
elif name.startswith("up_blocks"):
|
| 782 |
+
place_in_unet = "up"
|
| 783 |
+
elif name.startswith("down_blocks"):
|
| 784 |
+
place_in_unet = "down"
|
| 785 |
+
else:
|
| 786 |
+
continue
|
| 787 |
+
|
| 788 |
+
if "attn2" in name and place_in_unet != "mid":
|
| 789 |
+
attn_procs[name] = LEDITSCrossAttnProcessor(
|
| 790 |
+
attention_store=attention_store,
|
| 791 |
+
place_in_unet=place_in_unet,
|
| 792 |
+
pnp=PnP,
|
| 793 |
+
editing_prompts=self.enabled_editing_prompts,
|
| 794 |
+
)
|
| 795 |
+
else:
|
| 796 |
+
attn_procs[name] = AttnProcessor()
|
| 797 |
+
|
| 798 |
+
self.unet.set_attn_processor(attn_procs)
|
| 799 |
+
|
| 800 |
+
@torch.no_grad()
|
| 801 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 802 |
+
def __call__(
|
| 803 |
+
self,
|
| 804 |
+
denoising_end: Optional[float] = None,
|
| 805 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 806 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 807 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 808 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 809 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 810 |
+
output_type: Optional[str] = "pil",
|
| 811 |
+
return_dict: bool = True,
|
| 812 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 813 |
+
guidance_rescale: float = 0.0,
|
| 814 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 815 |
+
target_size: Optional[Tuple[int, int]] = None,
|
| 816 |
+
editing_prompt: Optional[Union[str, List[str]]] = None,
|
| 817 |
+
editing_prompt_embeddings: Optional[torch.Tensor] = None,
|
| 818 |
+
editing_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
| 819 |
+
reverse_editing_direction: Optional[Union[bool, List[bool]]] = False,
|
| 820 |
+
edit_guidance_scale: Optional[Union[float, List[float]]] = 5,
|
| 821 |
+
edit_warmup_steps: Optional[Union[int, List[int]]] = 0,
|
| 822 |
+
edit_cooldown_steps: Optional[Union[int, List[int]]] = None,
|
| 823 |
+
edit_threshold: Optional[Union[float, List[float]]] = 0.9,
|
| 824 |
+
sem_guidance: Optional[List[torch.Tensor]] = None,
|
| 825 |
+
use_cross_attn_mask: bool = False,
|
| 826 |
+
use_intersect_mask: bool = False,
|
| 827 |
+
user_mask: Optional[torch.FloatTensor] = None,
|
| 828 |
+
attn_store_steps: Optional[List[int]] = [],
|
| 829 |
+
store_averaged_over_steps: bool = True,
|
| 830 |
+
clip_skip: Optional[int] = None,
|
| 831 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 832 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 833 |
+
**kwargs,
|
| 834 |
+
):
|
| 835 |
+
r"""
|
| 836 |
+
The call function to the pipeline for editing. The [`~pipelines.ledits_pp.LEditsPPPipelineStableDiffusionXL.invert`]
|
| 837 |
+
method has to be called beforehand. Edits will always be performed for the last inverted image(s).
|
| 838 |
+
|
| 839 |
+
Args:
|
| 840 |
+
denoising_end (`float`, *optional*):
|
| 841 |
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
| 842 |
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
| 843 |
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
| 844 |
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
| 845 |
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
| 846 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 847 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 848 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 849 |
+
less than `1`).
|
| 850 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 851 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 852 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
| 853 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 854 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 855 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 856 |
+
argument.
|
| 857 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 858 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 859 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 860 |
+
input argument.
|
| 861 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*):
|
| 862 |
+
Optional image input to work with IP Adapters.
|
| 863 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 864 |
+
The output format of the generate image. Choose between
|
| 865 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 866 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 867 |
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
| 868 |
+
of a plain tuple.
|
| 869 |
+
callback (`Callable`, *optional*):
|
| 870 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
| 871 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
| 872 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
| 873 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
| 874 |
+
called at every step.
|
| 875 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 876 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 877 |
+
`self.processor` in
|
| 878 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 879 |
+
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
| 880 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
| 881 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
| 882 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
| 883 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
| 884 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 885 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
| 886 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
| 887 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 888 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 889 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 890 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
| 891 |
+
not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
|
| 892 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 893 |
+
editing_prompt (`str` or `List[str]`, *optional*):
|
| 894 |
+
The prompt or prompts to guide the image generation. The image is reconstructed by setting
|
| 895 |
+
`editing_prompt = None`. Guidance direction of prompt should be specified via `reverse_editing_direction`.
|
| 896 |
+
editing_prompt_embeddings (`torch.Tensor`, *optional*):
|
| 897 |
+
Pre-generated edit text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 898 |
+
weighting. If not provided, editing_prompt_embeddings will be generated from `editing_prompt` input
|
| 899 |
+
argument.
|
| 900 |
+
editing_pooled_prompt_embeddings (`torch.Tensor`, *optional*):
|
| 901 |
+
Pre-generated pooled edit text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 902 |
+
weighting. If not provided, editing_prompt_embeddings will be generated from `editing_prompt` input
|
| 903 |
+
argument.
|
| 904 |
+
reverse_editing_direction (`bool` or `List[bool]`, *optional*, defaults to `False`):
|
| 905 |
+
Whether the corresponding prompt in `editing_prompt` should be increased or decreased.
|
| 906 |
+
edit_guidance_scale (`float` or `List[float]`, *optional*, defaults to 5):
|
| 907 |
+
Guidance scale for guiding the image generation. If provided as list values should correspond to `editing_prompt`.
|
| 908 |
+
`edit_guidance_scale` is defined as `s_e` of equation 12 of
|
| 909 |
+
[LEDITS++ Paper](https://arxiv.org/abs/2301.12247).
|
| 910 |
+
edit_warmup_steps (`float` or `List[float]`, *optional*, defaults to 10):
|
| 911 |
+
Number of diffusion steps (for each prompt) for which guidance is not applied.
|
| 912 |
+
edit_cooldown_steps (`float` or `List[float]`, *optional*, defaults to `None`):
|
| 913 |
+
Number of diffusion steps (for each prompt) after which guidance is no longer applied.
|
| 914 |
+
edit_threshold (`float` or `List[float]`, *optional*, defaults to 0.9):
|
| 915 |
+
Masking threshold of guidance. Threshold should be proportional to the image region that is modified.
|
| 916 |
+
'edit_threshold' is defined as 'λ' of equation 12 of [LEDITS++ Paper](https://arxiv.org/abs/2301.12247).
|
| 917 |
+
sem_guidance (`List[torch.Tensor]`, *optional*):
|
| 918 |
+
List of pre-generated guidance vectors to be applied at generation. Length of the list has to
|
| 919 |
+
correspond to `num_inference_steps`.
|
| 920 |
+
use_cross_attn_mask:
|
| 921 |
+
Whether cross-attention masks are used. Cross-attention masks are always used when use_intersect_mask
|
| 922 |
+
is set to true. Cross-attention masks are defined as 'M^1' of equation 12 of
|
| 923 |
+
[LEDITS++ paper](https://arxiv.org/pdf/2311.16711.pdf).
|
| 924 |
+
use_intersect_mask:
|
| 925 |
+
Whether the masking term is calculated as intersection of cross-attention masks and masks derived
|
| 926 |
+
from the noise estimate. Cross-attention mask are defined as 'M^1' and masks derived from the noise
|
| 927 |
+
estimate are defined as 'M^2' of equation 12 of [LEDITS++ paper](https://arxiv.org/pdf/2311.16711.pdf).
|
| 928 |
+
user_mask:
|
| 929 |
+
User-provided mask for even better control over the editing process. This is helpful when LEDITS++'s implicit
|
| 930 |
+
masks do not meet user preferences.
|
| 931 |
+
attn_store_steps:
|
| 932 |
+
Steps for which the attention maps are stored in the AttentionStore. Just for visualization purposes.
|
| 933 |
+
store_averaged_over_steps:
|
| 934 |
+
Whether the attention maps for the 'attn_store_steps' are stored averaged over the diffusion steps.
|
| 935 |
+
If False, attention maps for each step are stores separately. Just for visualization purposes.
|
| 936 |
+
clip_skip (`int`, *optional*):
|
| 937 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 938 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 939 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 940 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 941 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 942 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 943 |
+
`callback_on_step_end_tensor_inputs`.
|
| 944 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 945 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 946 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 947 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 948 |
+
|
| 949 |
+
Examples:
|
| 950 |
+
|
| 951 |
+
Returns:
|
| 952 |
+
[`~pipelines.ledits_pp.LEditsPPDiffusionPipelineOutput`] or `tuple`:
|
| 953 |
+
[`~pipelines.ledits_pp.LEditsPPDiffusionPipelineOutput`] if `return_dict` is True,
|
| 954 |
+
otherwise a `tuple. When returning a tuple, the first element is a list with the generated images.
|
| 955 |
+
"""
|
| 956 |
+
if self.inversion_steps is None:
|
| 957 |
+
raise ValueError(
|
| 958 |
+
"You need to invert an input image first before calling the pipeline. The `invert` method has to be called beforehand. Edits will always be performed for the last inverted image(s)."
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
eta = self.eta
|
| 962 |
+
num_images_per_prompt = 1
|
| 963 |
+
latents = self.init_latents
|
| 964 |
+
|
| 965 |
+
zs = self.zs
|
| 966 |
+
self.scheduler.set_timesteps(len(self.scheduler.timesteps))
|
| 967 |
+
|
| 968 |
+
if use_intersect_mask:
|
| 969 |
+
use_cross_attn_mask = True
|
| 970 |
+
|
| 971 |
+
if use_cross_attn_mask:
|
| 972 |
+
self.smoothing = LeditsGaussianSmoothing(self.device)
|
| 973 |
+
|
| 974 |
+
if user_mask is not None:
|
| 975 |
+
user_mask = user_mask.to(self.device)
|
| 976 |
+
|
| 977 |
+
# TODO: Check inputs
|
| 978 |
+
# 1. Check inputs. Raise error if not correct
|
| 979 |
+
# self.check_inputs(
|
| 980 |
+
# callback_steps,
|
| 981 |
+
# negative_prompt,
|
| 982 |
+
# negative_prompt_2,
|
| 983 |
+
# prompt_embeds,
|
| 984 |
+
# negative_prompt_embeds,
|
| 985 |
+
# pooled_prompt_embeds,
|
| 986 |
+
# negative_pooled_prompt_embeds,
|
| 987 |
+
# )
|
| 988 |
+
self._guidance_rescale = guidance_rescale
|
| 989 |
+
self._clip_skip = clip_skip
|
| 990 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 991 |
+
self._denoising_end = denoising_end
|
| 992 |
+
|
| 993 |
+
# 2. Define call parameters
|
| 994 |
+
batch_size = self.batch_size
|
| 995 |
+
|
| 996 |
+
device = self._execution_device
|
| 997 |
+
|
| 998 |
+
if editing_prompt:
|
| 999 |
+
enable_edit_guidance = True
|
| 1000 |
+
if isinstance(editing_prompt, str):
|
| 1001 |
+
editing_prompt = [editing_prompt]
|
| 1002 |
+
self.enabled_editing_prompts = len(editing_prompt)
|
| 1003 |
+
elif editing_prompt_embeddings is not None:
|
| 1004 |
+
enable_edit_guidance = True
|
| 1005 |
+
self.enabled_editing_prompts = editing_prompt_embeddings.shape[0]
|
| 1006 |
+
else:
|
| 1007 |
+
self.enabled_editing_prompts = 0
|
| 1008 |
+
enable_edit_guidance = False
|
| 1009 |
+
|
| 1010 |
+
# 3. Encode input prompt
|
| 1011 |
+
text_encoder_lora_scale = (
|
| 1012 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 1013 |
+
)
|
| 1014 |
+
(
|
| 1015 |
+
prompt_embeds,
|
| 1016 |
+
edit_prompt_embeds,
|
| 1017 |
+
negative_pooled_prompt_embeds,
|
| 1018 |
+
pooled_edit_embeds,
|
| 1019 |
+
num_edit_tokens,
|
| 1020 |
+
) = self.encode_prompt(
|
| 1021 |
+
device=device,
|
| 1022 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 1023 |
+
negative_prompt=negative_prompt,
|
| 1024 |
+
negative_prompt_2=negative_prompt_2,
|
| 1025 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1026 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 1027 |
+
lora_scale=text_encoder_lora_scale,
|
| 1028 |
+
clip_skip=self.clip_skip,
|
| 1029 |
+
enable_edit_guidance=enable_edit_guidance,
|
| 1030 |
+
editing_prompt=editing_prompt,
|
| 1031 |
+
editing_prompt_embeds=editing_prompt_embeddings,
|
| 1032 |
+
editing_pooled_prompt_embeds=editing_pooled_prompt_embeds,
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
# 4. Prepare timesteps
|
| 1036 |
+
# self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 1037 |
+
|
| 1038 |
+
timesteps = self.inversion_steps
|
| 1039 |
+
t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
|
| 1040 |
+
|
| 1041 |
+
if use_cross_attn_mask:
|
| 1042 |
+
self.attention_store = LeditsAttentionStore(
|
| 1043 |
+
average=store_averaged_over_steps,
|
| 1044 |
+
batch_size=batch_size,
|
| 1045 |
+
max_size=(latents.shape[-2] / 4.0) * (latents.shape[-1] / 4.0),
|
| 1046 |
+
max_resolution=None,
|
| 1047 |
+
)
|
| 1048 |
+
self.prepare_unet(self.attention_store)
|
| 1049 |
+
resolution = latents.shape[-2:]
|
| 1050 |
+
att_res = (int(resolution[0] / 4), int(resolution[1] / 4))
|
| 1051 |
+
|
| 1052 |
+
# 5. Prepare latent variables
|
| 1053 |
+
latents = self.prepare_latents(device=device, latents=latents)
|
| 1054 |
+
|
| 1055 |
+
# 6. Prepare extra step kwargs.
|
| 1056 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(eta)
|
| 1057 |
+
|
| 1058 |
+
if self.text_encoder_2 is None:
|
| 1059 |
+
text_encoder_projection_dim = int(negative_pooled_prompt_embeds.shape[-1])
|
| 1060 |
+
else:
|
| 1061 |
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
| 1062 |
+
|
| 1063 |
+
# 7. Prepare added time ids & embeddings
|
| 1064 |
+
add_text_embeds = negative_pooled_prompt_embeds
|
| 1065 |
+
add_time_ids = self._get_add_time_ids(
|
| 1066 |
+
self.size,
|
| 1067 |
+
crops_coords_top_left,
|
| 1068 |
+
self.size,
|
| 1069 |
+
dtype=negative_pooled_prompt_embeds.dtype,
|
| 1070 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
if enable_edit_guidance:
|
| 1074 |
+
prompt_embeds = torch.cat([prompt_embeds, edit_prompt_embeds], dim=0)
|
| 1075 |
+
add_text_embeds = torch.cat([add_text_embeds, pooled_edit_embeds], dim=0)
|
| 1076 |
+
edit_concepts_time_ids = add_time_ids.repeat(edit_prompt_embeds.shape[0], 1)
|
| 1077 |
+
add_time_ids = torch.cat([add_time_ids, edit_concepts_time_ids], dim=0)
|
| 1078 |
+
self.text_cross_attention_maps = [editing_prompt] if isinstance(editing_prompt, str) else editing_prompt
|
| 1079 |
+
|
| 1080 |
+
prompt_embeds = prompt_embeds.to(device)
|
| 1081 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 1082 |
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
| 1083 |
+
|
| 1084 |
+
if ip_adapter_image is not None:
|
| 1085 |
+
# TODO: fix image encoding
|
| 1086 |
+
image_embeds, negative_image_embeds = self.encode_image(ip_adapter_image, device, num_images_per_prompt)
|
| 1087 |
+
if self.do_classifier_free_guidance:
|
| 1088 |
+
image_embeds = torch.cat([negative_image_embeds, image_embeds])
|
| 1089 |
+
image_embeds = image_embeds.to(device)
|
| 1090 |
+
|
| 1091 |
+
# 8. Denoising loop
|
| 1092 |
+
self.sem_guidance = None
|
| 1093 |
+
self.activation_mask = None
|
| 1094 |
+
|
| 1095 |
+
if (
|
| 1096 |
+
self.denoising_end is not None
|
| 1097 |
+
and isinstance(self.denoising_end, float)
|
| 1098 |
+
and self.denoising_end > 0
|
| 1099 |
+
and self.denoising_end < 1
|
| 1100 |
+
):
|
| 1101 |
+
discrete_timestep_cutoff = int(
|
| 1102 |
+
round(
|
| 1103 |
+
self.scheduler.config.num_train_timesteps
|
| 1104 |
+
- (self.denoising_end * self.scheduler.config.num_train_timesteps)
|
| 1105 |
+
)
|
| 1106 |
+
)
|
| 1107 |
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
| 1108 |
+
timesteps = timesteps[:num_inference_steps]
|
| 1109 |
+
|
| 1110 |
+
# 9. Optionally get Guidance Scale Embedding
|
| 1111 |
+
timestep_cond = None
|
| 1112 |
+
if self.unet.config.time_cond_proj_dim is not None:
|
| 1113 |
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
| 1114 |
+
timestep_cond = self.get_guidance_scale_embedding(
|
| 1115 |
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
| 1116 |
+
).to(device=device, dtype=latents.dtype)
|
| 1117 |
+
|
| 1118 |
+
self._num_timesteps = len(timesteps)
|
| 1119 |
+
with self.progress_bar(total=self._num_timesteps) as progress_bar:
|
| 1120 |
+
for i, t in enumerate(timesteps):
|
| 1121 |
+
# expand the latents if we are doing classifier free guidance
|
| 1122 |
+
latent_model_input = torch.cat([latents] * (1 + self.enabled_editing_prompts))
|
| 1123 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 1124 |
+
# predict the noise residual
|
| 1125 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 1126 |
+
if ip_adapter_image is not None:
|
| 1127 |
+
added_cond_kwargs["image_embeds"] = image_embeds
|
| 1128 |
+
noise_pred = self.unet(
|
| 1129 |
+
latent_model_input,
|
| 1130 |
+
t,
|
| 1131 |
+
encoder_hidden_states=prompt_embeds,
|
| 1132 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 1133 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 1134 |
+
return_dict=False,
|
| 1135 |
+
)[0]
|
| 1136 |
+
|
| 1137 |
+
noise_pred_out = noise_pred.chunk(1 + self.enabled_editing_prompts) # [b,4, 64, 64]
|
| 1138 |
+
noise_pred_uncond = noise_pred_out[0]
|
| 1139 |
+
noise_pred_edit_concepts = noise_pred_out[1:]
|
| 1140 |
+
|
| 1141 |
+
noise_guidance_edit = torch.zeros(
|
| 1142 |
+
noise_pred_uncond.shape,
|
| 1143 |
+
device=self.device,
|
| 1144 |
+
dtype=noise_pred_uncond.dtype,
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
if sem_guidance is not None and len(sem_guidance) > i:
|
| 1148 |
+
noise_guidance_edit += sem_guidance[i].to(self.device)
|
| 1149 |
+
|
| 1150 |
+
elif enable_edit_guidance:
|
| 1151 |
+
if self.activation_mask is None:
|
| 1152 |
+
self.activation_mask = torch.zeros(
|
| 1153 |
+
(len(timesteps), self.enabled_editing_prompts, *noise_pred_edit_concepts[0].shape)
|
| 1154 |
+
)
|
| 1155 |
+
if self.sem_guidance is None:
|
| 1156 |
+
self.sem_guidance = torch.zeros((len(timesteps), *noise_pred_uncond.shape))
|
| 1157 |
+
|
| 1158 |
+
# noise_guidance_edit = torch.zeros_like(noise_guidance)
|
| 1159 |
+
for c, noise_pred_edit_concept in enumerate(noise_pred_edit_concepts):
|
| 1160 |
+
if isinstance(edit_warmup_steps, list):
|
| 1161 |
+
edit_warmup_steps_c = edit_warmup_steps[c]
|
| 1162 |
+
else:
|
| 1163 |
+
edit_warmup_steps_c = edit_warmup_steps
|
| 1164 |
+
if i < edit_warmup_steps_c:
|
| 1165 |
+
continue
|
| 1166 |
+
|
| 1167 |
+
if isinstance(edit_guidance_scale, list):
|
| 1168 |
+
edit_guidance_scale_c = edit_guidance_scale[c]
|
| 1169 |
+
else:
|
| 1170 |
+
edit_guidance_scale_c = edit_guidance_scale
|
| 1171 |
+
|
| 1172 |
+
if isinstance(edit_threshold, list):
|
| 1173 |
+
edit_threshold_c = edit_threshold[c]
|
| 1174 |
+
else:
|
| 1175 |
+
edit_threshold_c = edit_threshold
|
| 1176 |
+
if isinstance(reverse_editing_direction, list):
|
| 1177 |
+
reverse_editing_direction_c = reverse_editing_direction[c]
|
| 1178 |
+
else:
|
| 1179 |
+
reverse_editing_direction_c = reverse_editing_direction
|
| 1180 |
+
|
| 1181 |
+
if isinstance(edit_cooldown_steps, list):
|
| 1182 |
+
edit_cooldown_steps_c = edit_cooldown_steps[c]
|
| 1183 |
+
elif edit_cooldown_steps is None:
|
| 1184 |
+
edit_cooldown_steps_c = i + 1
|
| 1185 |
+
else:
|
| 1186 |
+
edit_cooldown_steps_c = edit_cooldown_steps
|
| 1187 |
+
|
| 1188 |
+
if i >= edit_cooldown_steps_c:
|
| 1189 |
+
continue
|
| 1190 |
+
|
| 1191 |
+
noise_guidance_edit_tmp = noise_pred_edit_concept - noise_pred_uncond
|
| 1192 |
+
|
| 1193 |
+
if reverse_editing_direction_c:
|
| 1194 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * -1
|
| 1195 |
+
|
| 1196 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * edit_guidance_scale_c
|
| 1197 |
+
|
| 1198 |
+
if user_mask is not None:
|
| 1199 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * user_mask
|
| 1200 |
+
|
| 1201 |
+
if use_cross_attn_mask:
|
| 1202 |
+
out = self.attention_store.aggregate_attention(
|
| 1203 |
+
attention_maps=self.attention_store.step_store,
|
| 1204 |
+
prompts=self.text_cross_attention_maps,
|
| 1205 |
+
res=att_res,
|
| 1206 |
+
from_where=["up", "down"],
|
| 1207 |
+
is_cross=True,
|
| 1208 |
+
select=self.text_cross_attention_maps.index(editing_prompt[c]),
|
| 1209 |
+
)
|
| 1210 |
+
attn_map = out[:, :, :, 1 : 1 + num_edit_tokens[c]] # 0 -> startoftext
|
| 1211 |
+
|
| 1212 |
+
# average over all tokens
|
| 1213 |
+
if attn_map.shape[3] != num_edit_tokens[c]:
|
| 1214 |
+
raise ValueError(
|
| 1215 |
+
f"Incorrect shape of attention_map. Expected size {num_edit_tokens[c]}, but found {attn_map.shape[3]}!"
|
| 1216 |
+
)
|
| 1217 |
+
attn_map = torch.sum(attn_map, dim=3)
|
| 1218 |
+
|
| 1219 |
+
# gaussian_smoothing
|
| 1220 |
+
attn_map = F.pad(attn_map.unsqueeze(1), (1, 1, 1, 1), mode="reflect")
|
| 1221 |
+
attn_map = self.smoothing(attn_map).squeeze(1)
|
| 1222 |
+
|
| 1223 |
+
# torch.quantile function expects float32
|
| 1224 |
+
if attn_map.dtype == torch.float32:
|
| 1225 |
+
tmp = torch.quantile(attn_map.flatten(start_dim=1), edit_threshold_c, dim=1)
|
| 1226 |
+
else:
|
| 1227 |
+
tmp = torch.quantile(
|
| 1228 |
+
attn_map.flatten(start_dim=1).to(torch.float32), edit_threshold_c, dim=1
|
| 1229 |
+
).to(attn_map.dtype)
|
| 1230 |
+
attn_mask = torch.where(
|
| 1231 |
+
attn_map >= tmp.unsqueeze(1).unsqueeze(1).repeat(1, *att_res), 1.0, 0.0
|
| 1232 |
+
)
|
| 1233 |
+
|
| 1234 |
+
# resolution must match latent space dimension
|
| 1235 |
+
attn_mask = F.interpolate(
|
| 1236 |
+
attn_mask.unsqueeze(1),
|
| 1237 |
+
noise_guidance_edit_tmp.shape[-2:], # 64,64
|
| 1238 |
+
).repeat(1, 4, 1, 1)
|
| 1239 |
+
self.activation_mask[i, c] = attn_mask.detach().cpu()
|
| 1240 |
+
if not use_intersect_mask:
|
| 1241 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * attn_mask
|
| 1242 |
+
|
| 1243 |
+
if use_intersect_mask:
|
| 1244 |
+
noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
|
| 1245 |
+
noise_guidance_edit_tmp_quantile = torch.sum(
|
| 1246 |
+
noise_guidance_edit_tmp_quantile, dim=1, keepdim=True
|
| 1247 |
+
)
|
| 1248 |
+
noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(
|
| 1249 |
+
1, self.unet.config.in_channels, 1, 1
|
| 1250 |
+
)
|
| 1251 |
+
|
| 1252 |
+
# torch.quantile function expects float32
|
| 1253 |
+
if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
|
| 1254 |
+
tmp = torch.quantile(
|
| 1255 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
|
| 1256 |
+
edit_threshold_c,
|
| 1257 |
+
dim=2,
|
| 1258 |
+
keepdim=False,
|
| 1259 |
+
)
|
| 1260 |
+
else:
|
| 1261 |
+
tmp = torch.quantile(
|
| 1262 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
|
| 1263 |
+
edit_threshold_c,
|
| 1264 |
+
dim=2,
|
| 1265 |
+
keepdim=False,
|
| 1266 |
+
).to(noise_guidance_edit_tmp_quantile.dtype)
|
| 1267 |
+
|
| 1268 |
+
intersect_mask = (
|
| 1269 |
+
torch.where(
|
| 1270 |
+
noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
|
| 1271 |
+
torch.ones_like(noise_guidance_edit_tmp),
|
| 1272 |
+
torch.zeros_like(noise_guidance_edit_tmp),
|
| 1273 |
+
)
|
| 1274 |
+
* attn_mask
|
| 1275 |
+
)
|
| 1276 |
+
|
| 1277 |
+
self.activation_mask[i, c] = intersect_mask.detach().cpu()
|
| 1278 |
+
|
| 1279 |
+
noise_guidance_edit_tmp = noise_guidance_edit_tmp * intersect_mask
|
| 1280 |
+
|
| 1281 |
+
elif not use_cross_attn_mask:
|
| 1282 |
+
# calculate quantile
|
| 1283 |
+
noise_guidance_edit_tmp_quantile = torch.abs(noise_guidance_edit_tmp)
|
| 1284 |
+
noise_guidance_edit_tmp_quantile = torch.sum(
|
| 1285 |
+
noise_guidance_edit_tmp_quantile, dim=1, keepdim=True
|
| 1286 |
+
)
|
| 1287 |
+
noise_guidance_edit_tmp_quantile = noise_guidance_edit_tmp_quantile.repeat(1, 4, 1, 1)
|
| 1288 |
+
|
| 1289 |
+
# torch.quantile function expects float32
|
| 1290 |
+
if noise_guidance_edit_tmp_quantile.dtype == torch.float32:
|
| 1291 |
+
tmp = torch.quantile(
|
| 1292 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2),
|
| 1293 |
+
edit_threshold_c,
|
| 1294 |
+
dim=2,
|
| 1295 |
+
keepdim=False,
|
| 1296 |
+
)
|
| 1297 |
+
else:
|
| 1298 |
+
tmp = torch.quantile(
|
| 1299 |
+
noise_guidance_edit_tmp_quantile.flatten(start_dim=2).to(torch.float32),
|
| 1300 |
+
edit_threshold_c,
|
| 1301 |
+
dim=2,
|
| 1302 |
+
keepdim=False,
|
| 1303 |
+
).to(noise_guidance_edit_tmp_quantile.dtype)
|
| 1304 |
+
|
| 1305 |
+
self.activation_mask[i, c] = (
|
| 1306 |
+
torch.where(
|
| 1307 |
+
noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
|
| 1308 |
+
torch.ones_like(noise_guidance_edit_tmp),
|
| 1309 |
+
torch.zeros_like(noise_guidance_edit_tmp),
|
| 1310 |
+
)
|
| 1311 |
+
.detach()
|
| 1312 |
+
.cpu()
|
| 1313 |
+
)
|
| 1314 |
+
|
| 1315 |
+
noise_guidance_edit_tmp = torch.where(
|
| 1316 |
+
noise_guidance_edit_tmp_quantile >= tmp[:, :, None, None],
|
| 1317 |
+
noise_guidance_edit_tmp,
|
| 1318 |
+
torch.zeros_like(noise_guidance_edit_tmp),
|
| 1319 |
+
)
|
| 1320 |
+
|
| 1321 |
+
noise_guidance_edit += noise_guidance_edit_tmp
|
| 1322 |
+
|
| 1323 |
+
self.sem_guidance[i] = noise_guidance_edit.detach().cpu()
|
| 1324 |
+
|
| 1325 |
+
noise_pred = noise_pred_uncond + noise_guidance_edit
|
| 1326 |
+
|
| 1327 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 1328 |
+
if enable_edit_guidance and self.guidance_rescale > 0.0:
|
| 1329 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
| 1330 |
+
noise_pred = rescale_noise_cfg(
|
| 1331 |
+
noise_pred,
|
| 1332 |
+
noise_pred_edit_concepts.mean(dim=0, keepdim=False),
|
| 1333 |
+
guidance_rescale=self.guidance_rescale,
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
idx = t_to_idx[int(t)]
|
| 1337 |
+
latents = self.scheduler.step(
|
| 1338 |
+
noise_pred, t, latents, variance_noise=zs[idx], **extra_step_kwargs, return_dict=False
|
| 1339 |
+
)[0]
|
| 1340 |
+
|
| 1341 |
+
# step callback
|
| 1342 |
+
if use_cross_attn_mask:
|
| 1343 |
+
store_step = i in attn_store_steps
|
| 1344 |
+
self.attention_store.between_steps(store_step)
|
| 1345 |
+
|
| 1346 |
+
if callback_on_step_end is not None:
|
| 1347 |
+
callback_kwargs = {}
|
| 1348 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 1349 |
+
callback_kwargs[k] = locals()[k]
|
| 1350 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 1351 |
+
|
| 1352 |
+
latents = callback_outputs.pop("latents", latents)
|
| 1353 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 1354 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 1355 |
+
add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
|
| 1356 |
+
negative_pooled_prompt_embeds = callback_outputs.pop(
|
| 1357 |
+
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
| 1358 |
+
)
|
| 1359 |
+
add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
|
| 1360 |
+
# negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
|
| 1361 |
+
|
| 1362 |
+
# call the callback, if provided
|
| 1363 |
+
if i == len(timesteps) - 1 or ((i + 1) > 0 and (i + 1) % self.scheduler.order == 0):
|
| 1364 |
+
progress_bar.update()
|
| 1365 |
+
|
| 1366 |
+
if XLA_AVAILABLE:
|
| 1367 |
+
xm.mark_step()
|
| 1368 |
+
|
| 1369 |
+
if not output_type == "latent":
|
| 1370 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 1371 |
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
| 1372 |
+
|
| 1373 |
+
if needs_upcasting:
|
| 1374 |
+
self.upcast_vae()
|
| 1375 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 1376 |
+
|
| 1377 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
| 1378 |
+
|
| 1379 |
+
# cast back to fp16 if needed
|
| 1380 |
+
if needs_upcasting:
|
| 1381 |
+
self.vae.to(dtype=torch.float16)
|
| 1382 |
+
else:
|
| 1383 |
+
image = latents
|
| 1384 |
+
|
| 1385 |
+
if not output_type == "latent":
|
| 1386 |
+
# apply watermark if available
|
| 1387 |
+
if self.watermark is not None:
|
| 1388 |
+
image = self.watermark.apply_watermark(image)
|
| 1389 |
+
|
| 1390 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 1391 |
+
|
| 1392 |
+
# Offload all models
|
| 1393 |
+
self.maybe_free_model_hooks()
|
| 1394 |
+
|
| 1395 |
+
if not return_dict:
|
| 1396 |
+
return (image,)
|
| 1397 |
+
|
| 1398 |
+
return LEditsPPDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
|
| 1399 |
+
|
| 1400 |
+
@torch.no_grad()
|
| 1401 |
+
# Modified from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.LEditsPPPipelineStableDiffusion.encode_image
|
| 1402 |
+
def encode_image(self, image, dtype=None, height=None, width=None, resize_mode="default", crops_coords=None):
|
| 1403 |
+
image = self.image_processor.preprocess(
|
| 1404 |
+
image=image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
|
| 1405 |
+
)
|
| 1406 |
+
resized = self.image_processor.postprocess(image=image, output_type="pil")
|
| 1407 |
+
|
| 1408 |
+
if max(image.shape[-2:]) > self.vae.config["sample_size"] * 1.5:
|
| 1409 |
+
logger.warning(
|
| 1410 |
+
"Your input images far exceed the default resolution of the underlying diffusion model. "
|
| 1411 |
+
"The output images may contain severe artifacts! "
|
| 1412 |
+
"Consider down-sampling the input using the `height` and `width` parameters"
|
| 1413 |
+
)
|
| 1414 |
+
image = image.to(self.device, dtype=dtype)
|
| 1415 |
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
| 1416 |
+
|
| 1417 |
+
if needs_upcasting:
|
| 1418 |
+
image = image.float()
|
| 1419 |
+
self.upcast_vae()
|
| 1420 |
+
image = image.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 1421 |
+
|
| 1422 |
+
x0 = self.vae.encode(image).latent_dist.mode()
|
| 1423 |
+
x0 = x0.to(dtype)
|
| 1424 |
+
# cast back to fp16 if needed
|
| 1425 |
+
if needs_upcasting:
|
| 1426 |
+
self.vae.to(dtype=torch.float16)
|
| 1427 |
+
|
| 1428 |
+
x0 = self.vae.config.scaling_factor * x0
|
| 1429 |
+
return x0, resized
|
| 1430 |
+
|
| 1431 |
+
@torch.no_grad()
|
| 1432 |
+
def invert(
|
| 1433 |
+
self,
|
| 1434 |
+
image: PipelineImageInput,
|
| 1435 |
+
source_prompt: str = "",
|
| 1436 |
+
source_guidance_scale=3.5,
|
| 1437 |
+
negative_prompt: str = None,
|
| 1438 |
+
negative_prompt_2: str = None,
|
| 1439 |
+
num_inversion_steps: int = 50,
|
| 1440 |
+
skip: float = 0.15,
|
| 1441 |
+
generator: Optional[torch.Generator] = None,
|
| 1442 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 1443 |
+
num_zero_noise_steps: int = 3,
|
| 1444 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 1445 |
+
):
|
| 1446 |
+
r"""
|
| 1447 |
+
The function to the pipeline for image inversion as described by the [LEDITS++ Paper](https://arxiv.org/abs/2301.12247).
|
| 1448 |
+
If the scheduler is set to [`~schedulers.DDIMScheduler`] the inversion proposed by [edit-friendly DPDM](https://arxiv.org/abs/2304.06140)
|
| 1449 |
+
will be performed instead.
|
| 1450 |
+
|
| 1451 |
+
Args:
|
| 1452 |
+
image (`PipelineImageInput`):
|
| 1453 |
+
Input for the image(s) that are to be edited. Multiple input images have to default to the same aspect
|
| 1454 |
+
ratio.
|
| 1455 |
+
source_prompt (`str`, defaults to `""`):
|
| 1456 |
+
Prompt describing the input image that will be used for guidance during inversion. Guidance is disabled
|
| 1457 |
+
if the `source_prompt` is `""`.
|
| 1458 |
+
source_guidance_scale (`float`, defaults to `3.5`):
|
| 1459 |
+
Strength of guidance during inversion.
|
| 1460 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 1461 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 1462 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 1463 |
+
less than `1`).
|
| 1464 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 1465 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
| 1466 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
| 1467 |
+
num_inversion_steps (`int`, defaults to `50`):
|
| 1468 |
+
Number of total performed inversion steps after discarding the initial `skip` steps.
|
| 1469 |
+
skip (`float`, defaults to `0.15`):
|
| 1470 |
+
Portion of initial steps that will be ignored for inversion and subsequent generation. Lower values
|
| 1471 |
+
will lead to stronger changes to the input image. `skip` has to be between `0` and `1`.
|
| 1472 |
+
generator (`torch.Generator`, *optional*):
|
| 1473 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 1474 |
+
inversion deterministic.
|
| 1475 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 1476 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
| 1477 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
| 1478 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 1479 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 1480 |
+
num_zero_noise_steps (`int`, defaults to `3`):
|
| 1481 |
+
Number of final diffusion steps that will not renoise the current image. If no steps are set to zero
|
| 1482 |
+
SD-XL in combination with [`DPMSolverMultistepScheduler`] will produce noise artifacts.
|
| 1483 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 1484 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 1485 |
+
`self.processor` in
|
| 1486 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 1487 |
+
|
| 1488 |
+
Returns:
|
| 1489 |
+
[`~pipelines.ledits_pp.LEditsPPInversionPipelineOutput`]:
|
| 1490 |
+
Output will contain the resized input image(s) and respective VAE reconstruction(s).
|
| 1491 |
+
"""
|
| 1492 |
+
|
| 1493 |
+
# Reset attn processor, we do not want to store attn maps during inversion
|
| 1494 |
+
self.unet.set_attn_processor(AttnProcessor())
|
| 1495 |
+
|
| 1496 |
+
self.eta = 1.0
|
| 1497 |
+
|
| 1498 |
+
self.scheduler.config.timestep_spacing = "leading"
|
| 1499 |
+
self.scheduler.set_timesteps(int(num_inversion_steps * (1 + skip)))
|
| 1500 |
+
self.inversion_steps = self.scheduler.timesteps[-num_inversion_steps:]
|
| 1501 |
+
timesteps = self.inversion_steps
|
| 1502 |
+
|
| 1503 |
+
num_images_per_prompt = 1
|
| 1504 |
+
|
| 1505 |
+
device = self._execution_device
|
| 1506 |
+
|
| 1507 |
+
# 0. Ensure that only uncond embedding is used if prompt = ""
|
| 1508 |
+
if source_prompt == "":
|
| 1509 |
+
# noise pred should only be noise_pred_uncond
|
| 1510 |
+
source_guidance_scale = 0.0
|
| 1511 |
+
do_classifier_free_guidance = False
|
| 1512 |
+
else:
|
| 1513 |
+
do_classifier_free_guidance = source_guidance_scale > 1.0
|
| 1514 |
+
|
| 1515 |
+
# 1. prepare image
|
| 1516 |
+
x0, resized = self.encode_image(image, dtype=self.text_encoder_2.dtype)
|
| 1517 |
+
width = x0.shape[2] * self.vae_scale_factor
|
| 1518 |
+
height = x0.shape[3] * self.vae_scale_factor
|
| 1519 |
+
self.size = (height, width)
|
| 1520 |
+
|
| 1521 |
+
self.batch_size = x0.shape[0]
|
| 1522 |
+
|
| 1523 |
+
# 2. get embeddings
|
| 1524 |
+
text_encoder_lora_scale = (
|
| 1525 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
| 1526 |
+
)
|
| 1527 |
+
|
| 1528 |
+
if isinstance(source_prompt, str):
|
| 1529 |
+
source_prompt = [source_prompt] * self.batch_size
|
| 1530 |
+
|
| 1531 |
+
(
|
| 1532 |
+
negative_prompt_embeds,
|
| 1533 |
+
prompt_embeds,
|
| 1534 |
+
negative_pooled_prompt_embeds,
|
| 1535 |
+
edit_pooled_prompt_embeds,
|
| 1536 |
+
_,
|
| 1537 |
+
) = self.encode_prompt(
|
| 1538 |
+
device=device,
|
| 1539 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 1540 |
+
negative_prompt=negative_prompt,
|
| 1541 |
+
negative_prompt_2=negative_prompt_2,
|
| 1542 |
+
editing_prompt=source_prompt,
|
| 1543 |
+
lora_scale=text_encoder_lora_scale,
|
| 1544 |
+
enable_edit_guidance=do_classifier_free_guidance,
|
| 1545 |
+
)
|
| 1546 |
+
if self.text_encoder_2 is None:
|
| 1547 |
+
text_encoder_projection_dim = int(negative_pooled_prompt_embeds.shape[-1])
|
| 1548 |
+
else:
|
| 1549 |
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
| 1550 |
+
|
| 1551 |
+
# 3. Prepare added time ids & embeddings
|
| 1552 |
+
add_text_embeds = negative_pooled_prompt_embeds
|
| 1553 |
+
add_time_ids = self._get_add_time_ids(
|
| 1554 |
+
self.size,
|
| 1555 |
+
crops_coords_top_left,
|
| 1556 |
+
self.size,
|
| 1557 |
+
dtype=negative_prompt_embeds.dtype,
|
| 1558 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
| 1559 |
+
)
|
| 1560 |
+
|
| 1561 |
+
if do_classifier_free_guidance:
|
| 1562 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
| 1563 |
+
add_text_embeds = torch.cat([add_text_embeds, edit_pooled_prompt_embeds], dim=0)
|
| 1564 |
+
add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
|
| 1565 |
+
|
| 1566 |
+
negative_prompt_embeds = negative_prompt_embeds.to(device)
|
| 1567 |
+
|
| 1568 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 1569 |
+
add_time_ids = add_time_ids.to(device).repeat(self.batch_size * num_images_per_prompt, 1)
|
| 1570 |
+
|
| 1571 |
+
# autoencoder reconstruction
|
| 1572 |
+
if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
|
| 1573 |
+
self.upcast_vae()
|
| 1574 |
+
x0_tmp = x0.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 1575 |
+
image_rec = self.vae.decode(
|
| 1576 |
+
x0_tmp / self.vae.config.scaling_factor, return_dict=False, generator=generator
|
| 1577 |
+
)[0]
|
| 1578 |
+
elif self.vae.config.force_upcast:
|
| 1579 |
+
x0_tmp = x0.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 1580 |
+
image_rec = self.vae.decode(
|
| 1581 |
+
x0_tmp / self.vae.config.scaling_factor, return_dict=False, generator=generator
|
| 1582 |
+
)[0]
|
| 1583 |
+
else:
|
| 1584 |
+
image_rec = self.vae.decode(x0 / self.vae.config.scaling_factor, return_dict=False, generator=generator)[0]
|
| 1585 |
+
|
| 1586 |
+
image_rec = self.image_processor.postprocess(image_rec, output_type="pil")
|
| 1587 |
+
|
| 1588 |
+
# 5. find zs and xts
|
| 1589 |
+
variance_noise_shape = (num_inversion_steps, *x0.shape)
|
| 1590 |
+
|
| 1591 |
+
# intermediate latents
|
| 1592 |
+
t_to_idx = {int(v): k for k, v in enumerate(timesteps)}
|
| 1593 |
+
xts = torch.zeros(size=variance_noise_shape, device=self.device, dtype=negative_prompt_embeds.dtype)
|
| 1594 |
+
|
| 1595 |
+
for t in reversed(timesteps):
|
| 1596 |
+
idx = num_inversion_steps - t_to_idx[int(t)] - 1
|
| 1597 |
+
noise = randn_tensor(shape=x0.shape, generator=generator, device=self.device, dtype=x0.dtype)
|
| 1598 |
+
xts[idx] = self.scheduler.add_noise(x0, noise, t.unsqueeze(0))
|
| 1599 |
+
xts = torch.cat([x0.unsqueeze(0), xts], dim=0)
|
| 1600 |
+
|
| 1601 |
+
# noise maps
|
| 1602 |
+
zs = torch.zeros(size=variance_noise_shape, device=self.device, dtype=negative_prompt_embeds.dtype)
|
| 1603 |
+
|
| 1604 |
+
self.scheduler.set_timesteps(len(self.scheduler.timesteps))
|
| 1605 |
+
|
| 1606 |
+
for t in self.progress_bar(timesteps):
|
| 1607 |
+
idx = num_inversion_steps - t_to_idx[int(t)] - 1
|
| 1608 |
+
# 1. predict noise residual
|
| 1609 |
+
xt = xts[idx + 1]
|
| 1610 |
+
|
| 1611 |
+
latent_model_input = torch.cat([xt] * 2) if do_classifier_free_guidance else xt
|
| 1612 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 1613 |
+
|
| 1614 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 1615 |
+
|
| 1616 |
+
noise_pred = self.unet(
|
| 1617 |
+
latent_model_input,
|
| 1618 |
+
t,
|
| 1619 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 1620 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 1621 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 1622 |
+
return_dict=False,
|
| 1623 |
+
)[0]
|
| 1624 |
+
|
| 1625 |
+
# 2. perform guidance
|
| 1626 |
+
if do_classifier_free_guidance:
|
| 1627 |
+
noise_pred_out = noise_pred.chunk(2)
|
| 1628 |
+
noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1]
|
| 1629 |
+
noise_pred = noise_pred_uncond + source_guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 1630 |
+
|
| 1631 |
+
xtm1 = xts[idx]
|
| 1632 |
+
z, xtm1_corrected = compute_noise(self.scheduler, xtm1, xt, t, noise_pred, self.eta)
|
| 1633 |
+
zs[idx] = z
|
| 1634 |
+
|
| 1635 |
+
# correction to avoid error accumulation
|
| 1636 |
+
xts[idx] = xtm1_corrected
|
| 1637 |
+
|
| 1638 |
+
self.init_latents = xts[-1]
|
| 1639 |
+
zs = zs.flip(0)
|
| 1640 |
+
|
| 1641 |
+
if num_zero_noise_steps > 0:
|
| 1642 |
+
zs[-num_zero_noise_steps:] = torch.zeros_like(zs[-num_zero_noise_steps:])
|
| 1643 |
+
self.zs = zs
|
| 1644 |
+
return LEditsPPInversionPipelineOutput(images=resized, vae_reconstruction_images=image_rec)
|
| 1645 |
+
|
| 1646 |
+
|
| 1647 |
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.rescale_noise_cfg
|
| 1648 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
| 1649 |
+
"""
|
| 1650 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
| 1651 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
| 1652 |
+
"""
|
| 1653 |
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
| 1654 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
| 1655 |
+
# rescale the results from guidance (fixes overexposure)
|
| 1656 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
| 1657 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
| 1658 |
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
| 1659 |
+
return noise_cfg
|
| 1660 |
+
|
| 1661 |
+
|
| 1662 |
+
# Copied from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.compute_noise_ddim
|
| 1663 |
+
def compute_noise_ddim(scheduler, prev_latents, latents, timestep, noise_pred, eta):
|
| 1664 |
+
# 1. get previous step value (=t-1)
|
| 1665 |
+
prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
|
| 1666 |
+
|
| 1667 |
+
# 2. compute alphas, betas
|
| 1668 |
+
alpha_prod_t = scheduler.alphas_cumprod[timestep]
|
| 1669 |
+
alpha_prod_t_prev = (
|
| 1670 |
+
scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
|
| 1671 |
+
)
|
| 1672 |
+
|
| 1673 |
+
beta_prod_t = 1 - alpha_prod_t
|
| 1674 |
+
|
| 1675 |
+
# 3. compute predicted original sample from predicted noise also called
|
| 1676 |
+
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 1677 |
+
pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
|
| 1678 |
+
|
| 1679 |
+
# 4. Clip "predicted x_0"
|
| 1680 |
+
if scheduler.config.clip_sample:
|
| 1681 |
+
pred_original_sample = torch.clamp(pred_original_sample, -1, 1)
|
| 1682 |
+
|
| 1683 |
+
# 5. compute variance: "sigma_t(η)" -> see formula (16)
|
| 1684 |
+
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
|
| 1685 |
+
variance = scheduler._get_variance(timestep, prev_timestep)
|
| 1686 |
+
std_dev_t = eta * variance ** (0.5)
|
| 1687 |
+
|
| 1688 |
+
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
|
| 1689 |
+
pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * noise_pred
|
| 1690 |
+
|
| 1691 |
+
# modifed so that updated xtm1 is returned as well (to avoid error accumulation)
|
| 1692 |
+
mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
|
| 1693 |
+
if variance > 0.0:
|
| 1694 |
+
noise = (prev_latents - mu_xt) / (variance ** (0.5) * eta)
|
| 1695 |
+
else:
|
| 1696 |
+
noise = torch.tensor([0.0]).to(latents.device)
|
| 1697 |
+
|
| 1698 |
+
return noise, mu_xt + (eta * variance**0.5) * noise
|
| 1699 |
+
|
| 1700 |
+
|
| 1701 |
+
# Copied from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.compute_noise_sde_dpm_pp_2nd
|
| 1702 |
+
def compute_noise_sde_dpm_pp_2nd(scheduler, prev_latents, latents, timestep, noise_pred, eta):
|
| 1703 |
+
def first_order_update(model_output, sample): # timestep, prev_timestep, sample):
|
| 1704 |
+
sigma_t, sigma_s = scheduler.sigmas[scheduler.step_index + 1], scheduler.sigmas[scheduler.step_index]
|
| 1705 |
+
alpha_t, sigma_t = scheduler._sigma_to_alpha_sigma_t(sigma_t)
|
| 1706 |
+
alpha_s, sigma_s = scheduler._sigma_to_alpha_sigma_t(sigma_s)
|
| 1707 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 1708 |
+
lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
|
| 1709 |
+
|
| 1710 |
+
h = lambda_t - lambda_s
|
| 1711 |
+
|
| 1712 |
+
mu_xt = (sigma_t / sigma_s * torch.exp(-h)) * sample + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
|
| 1713 |
+
|
| 1714 |
+
mu_xt = scheduler.dpm_solver_first_order_update(
|
| 1715 |
+
model_output=model_output, sample=sample, noise=torch.zeros_like(sample)
|
| 1716 |
+
)
|
| 1717 |
+
|
| 1718 |
+
sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
|
| 1719 |
+
if sigma > 0.0:
|
| 1720 |
+
noise = (prev_latents - mu_xt) / sigma
|
| 1721 |
+
else:
|
| 1722 |
+
noise = torch.tensor([0.0]).to(sample.device)
|
| 1723 |
+
|
| 1724 |
+
prev_sample = mu_xt + sigma * noise
|
| 1725 |
+
return noise, prev_sample
|
| 1726 |
+
|
| 1727 |
+
def second_order_update(model_output_list, sample): # timestep_list, prev_timestep, sample):
|
| 1728 |
+
sigma_t, sigma_s0, sigma_s1 = (
|
| 1729 |
+
scheduler.sigmas[scheduler.step_index + 1],
|
| 1730 |
+
scheduler.sigmas[scheduler.step_index],
|
| 1731 |
+
scheduler.sigmas[scheduler.step_index - 1],
|
| 1732 |
+
)
|
| 1733 |
+
|
| 1734 |
+
alpha_t, sigma_t = scheduler._sigma_to_alpha_sigma_t(sigma_t)
|
| 1735 |
+
alpha_s0, sigma_s0 = scheduler._sigma_to_alpha_sigma_t(sigma_s0)
|
| 1736 |
+
alpha_s1, sigma_s1 = scheduler._sigma_to_alpha_sigma_t(sigma_s1)
|
| 1737 |
+
|
| 1738 |
+
lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
|
| 1739 |
+
lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
|
| 1740 |
+
lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
|
| 1741 |
+
|
| 1742 |
+
m0, m1 = model_output_list[-1], model_output_list[-2]
|
| 1743 |
+
|
| 1744 |
+
h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
|
| 1745 |
+
r0 = h_0 / h
|
| 1746 |
+
D0, D1 = m0, (1.0 / r0) * (m0 - m1)
|
| 1747 |
+
|
| 1748 |
+
mu_xt = (
|
| 1749 |
+
(sigma_t / sigma_s0 * torch.exp(-h)) * sample
|
| 1750 |
+
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
|
| 1751 |
+
+ 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
|
| 1752 |
+
)
|
| 1753 |
+
|
| 1754 |
+
sigma = sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h))
|
| 1755 |
+
if sigma > 0.0:
|
| 1756 |
+
noise = (prev_latents - mu_xt) / sigma
|
| 1757 |
+
else:
|
| 1758 |
+
noise = torch.tensor([0.0]).to(sample.device)
|
| 1759 |
+
|
| 1760 |
+
prev_sample = mu_xt + sigma * noise
|
| 1761 |
+
|
| 1762 |
+
return noise, prev_sample
|
| 1763 |
+
|
| 1764 |
+
if scheduler.step_index is None:
|
| 1765 |
+
scheduler._init_step_index(timestep)
|
| 1766 |
+
|
| 1767 |
+
model_output = scheduler.convert_model_output(model_output=noise_pred, sample=latents)
|
| 1768 |
+
for i in range(scheduler.config.solver_order - 1):
|
| 1769 |
+
scheduler.model_outputs[i] = scheduler.model_outputs[i + 1]
|
| 1770 |
+
scheduler.model_outputs[-1] = model_output
|
| 1771 |
+
|
| 1772 |
+
if scheduler.lower_order_nums < 1:
|
| 1773 |
+
noise, prev_sample = first_order_update(model_output, latents)
|
| 1774 |
+
else:
|
| 1775 |
+
noise, prev_sample = second_order_update(scheduler.model_outputs, latents)
|
| 1776 |
+
|
| 1777 |
+
if scheduler.lower_order_nums < scheduler.config.solver_order:
|
| 1778 |
+
scheduler.lower_order_nums += 1
|
| 1779 |
+
|
| 1780 |
+
# upon completion increase step index by one
|
| 1781 |
+
scheduler._step_index += 1
|
| 1782 |
+
|
| 1783 |
+
return noise, prev_sample
|
| 1784 |
+
|
| 1785 |
+
|
| 1786 |
+
# Copied from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.compute_noise
|
| 1787 |
+
def compute_noise(scheduler, *args):
|
| 1788 |
+
if isinstance(scheduler, DDIMScheduler):
|
| 1789 |
+
return compute_noise_ddim(scheduler, *args)
|
| 1790 |
+
elif (
|
| 1791 |
+
isinstance(scheduler, DPMSolverMultistepScheduler)
|
| 1792 |
+
and scheduler.config.algorithm_type == "sde-dpmsolver++"
|
| 1793 |
+
and scheduler.config.solver_order == 2
|
| 1794 |
+
):
|
| 1795 |
+
return compute_noise_sde_dpm_pp_2nd(scheduler, *args)
|
| 1796 |
+
else:
|
| 1797 |
+
raise NotImplementedError
|