federicogirella commited on
Commit
217bd11
·
verified ·
1 Parent(s): 8e6eb47

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ ckpts/lots/lots.bin filter=lfs diff=lfs merge=lfs -text
2
+ static/LOTS.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python,visualstudiocode
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python,visualstudiocode
3
+
4
+ ### Python ###
5
+ # Byte-compiled / optimized / DLL files
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+ cover/
57
+
58
+ # Translations
59
+ *.mo
60
+ *.pot
61
+
62
+ # Django stuff:
63
+ *.log
64
+ local_settings.py
65
+ db.sqlite3
66
+ db.sqlite3-journal
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ .pybuilder/
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # IPython
86
+ profile_default/
87
+ ipython_config.py
88
+
89
+ # pyenv
90
+ # For a library or package, you might want to ignore these files since the code is
91
+ # intended to run in multiple environments; otherwise, check them in:
92
+ # .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # poetry
102
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
104
+ # commonly ignored for libraries.
105
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106
+ #poetry.lock
107
+
108
+ # pdm
109
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110
+ #pdm.lock
111
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112
+ # in version control.
113
+ # https://pdm.fming.dev/#use-with-ide
114
+ .pdm.toml
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
165
+
166
+ ### Python Patch ###
167
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168
+ poetry.toml
169
+
170
+ # ruff
171
+ .ruff_cache/
172
+
173
+ # LSP config files
174
+ pyrightconfig.json
175
+
176
+ ### VisualStudioCode ###
177
+ .vscode/
178
+ !.vscode/settings.json
179
+ !.vscode/tasks.json
180
+ !.vscode/launch.json
181
+ !.vscode/extensions.json
182
+ !.vscode/*.code-snippets
183
+
184
+ # Local History for Visual Studio Code
185
+ .history/
186
+
187
+ # Built Visual Studio Code Extensions
188
+ *.vsix
189
+
190
+ ### VisualStudioCode Patch ###
191
+ # Ignore all local history of files
192
+ .history
193
+ .ionide
194
+
195
+ ### Custom ###
196
+
197
+ outputs
README.md CHANGED
@@ -1,3 +1,65 @@
1
- ---
2
- license: cc-by-nc-4.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LOTS of Fashion! Multi-Conditioning for Image Generation via Sketch-Text Pairing #
2
+
3
+ [![Code](https://img.shields.io/badge/Code-%23121011.svg?style=flat&logo=github&logoColor=white)](https://github.com/intelligolabs/lots)
4
+ [![Project Page](https://img.shields.io/badge/Project_Page-121013?style=flat&logo=github&logoColor=white)](https://intelligolabs.github.io/lots)
5
+
6
+ [![Dataset on HF](https://huggingface.co/datasets/huggingface/badges/resolve/main/dataset-on-hf-sm-dark.svg)](https://huggingface.co/datasets/federicogirella/sketchy)
7
+
8
+ ![LOTS](static/LOTS.png)
9
+
10
+ This is the official implementation of the **LOTS** adapter from the paper *"LOTS of Fashion! Multi-Conditioning for Image Generation via Sketch-Text Pairing"*, published as **Oral at ICCV25** in Honolulu.
11
+
12
+ To access the **Sketchy** dataset, refer to [the HuggingFace repository](https://huggingface.co/datasets/federicogirella/sketchy)
13
+
14
+ ## Road Map ##
15
+
16
+ - [x] Code release
17
+ - [x] Weights release
18
+ - [ ] Platform release
19
+
20
+ ## Repository Structure ##
21
+ 1. `ckpts` folder
22
+ * Contains the pre-trained weights of the LOTS adapter.
23
+
24
+ 2. `scripts` folder
25
+ * Contains all the scripts for training and inference with LOTS on Sketchy.
26
+
27
+ 3. `src` folder
28
+ * Contains all the source code for the classes, models, and dataloaders used in the scripts.
29
+
30
+ ## Installation ##
31
+
32
+ We advise creating a Conda environment as follows
33
+ * `conda create -n lots python=3.12`
34
+ * `conda activate lots`
35
+ * `pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 --index-url https://download.pytorch.org/whl/cu121`
36
+ * `pip install -r requirements.txt`
37
+ * `pip install -e .`
38
+
39
+ Unzip the pre-trained weights and config
40
+ ```
41
+ cd ckpts
42
+ unzip lots.zip
43
+ cd ..
44
+ ```
45
+
46
+
47
+ ## **Training** ##
48
+ We provide the script to train LOTS on our Sketchy dataset in `scripts/lots/train_lots.py`.
49
+ For an example of usage, check `run_train.sh`, which contains the default parameters used in our experiments.
50
+
51
+ ## **Inference** ##
52
+ You can test our pre-trained model with the inference script in `scripts/lots/inference_lots.py`.
53
+ For an example, check `run_inference.sh`.
54
+ This script generates an image for each item in the test split of Sketchy, and saves them in a structured folder, with each item identified by its unique ID.
55
+
56
+ ## Citation
57
+ If you find our work useful, please cite our work:
58
+ ```
59
+ @inproceedings{girella2025lots,
60
+ author = {Girella, Federico and Talon, Davide and Lie, Ziyue and Ruan, Zanxi and Wang, Yiming and Cristani, Marco},
61
+ title = {LOTS of Fashion! Multi-Conditioning for Image Generation via Sketch-Text Pairing},
62
+ journal = {Proceedings of the International Conference on Computer Vision},
63
+ year = {2025},
64
+ }
65
+ ```
ckpts/lots/lots.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f6db0781dd119e34c9b8fbad48572eef423347be9a8a57b7297d173be899e075
3
+ size 2105167979
ckpts/lots/pair_former_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"in_channels": 2048, "fusion_strategy": "deferred", "num_layers": 2, "num_attention_heads": 8, "inner_dim": 2048, "dropout": 0.0, "norm_num_groups": 32, "activation_fn": "geglu", "masking_strategy": "compression", "num_cls_tokens": 32}
pyproject.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backedn = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lots"
7
+ authors = [
8
+ {name = "Federico Girella", email = "federico.girella@univr.it"},
9
+ ]
10
+ description = "Package for LOTS experiments"
11
+ readme = "README.md"
12
+ version = "1.0.0"
13
+ requires-python = ">=3.12"
14
+ dependencies = []
15
+
16
+ [tool.setuptools.packages.find]
17
+ where = ["src"]
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==1.3.0
2
+ diffusers==0.33.1
3
+ fashionpedia==1.1
4
+ huggingface-hub==0.28.1
5
+ matplotlib==3.10.0
6
+ notebook==7.3.2
7
+ numpy==2.1.2
8
+ opencv-python==4.11.0.86
9
+ pillow==11.0.0
10
+ pycocotools==2.0.8
11
+ tokenizers==0.21.0
12
+ tqdm==4.67.1
13
+ transformers==4.48.3
run_inference.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RUN_NAME="test_run"
2
+
3
+ python scripts/lots/inference_lots.py \
4
+ --base_model_path="stabilityai/stable-diffusion-xl-base-1.0" \
5
+ --device="cuda" \
6
+ --seed=21 \
7
+ --dinov2_model="vits14" \
8
+ --ckpt_path="ckpts/lots/lots.bin" \
9
+ --dataset_root="data/sketchy" \
10
+ --out_dir="outputs/inference/$RUN_NAME" \
11
+ --resolution=512
run_train.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RUN_NAME="test_run"
2
+
3
+ accelerate launch --mixed_precision "bf16" --num_processes 4 --multi-gpu --gpu_ids='all'\
4
+ scripts/lots/train_lots.py \
5
+ --pretrained_model_name_or_path="stabilityai/stable-diffusion-xl-base-1.0" \
6
+ --dataset_root="data/sketchy" \
7
+ --output_dir="outputs/checkpoints/$RUN_NAME" \
8
+ --resolution=512 \
9
+ --learning_rate=1e-5 \
10
+ --num_train_epochs=80 \
11
+ --dataloader_num_workers=8 \
12
+ --save_steps=10000 \
13
+ --train_batch_size=8 \
14
+ --dinov2_model="vits14" \
15
+ --num_cls_tokens=32 \
16
+ --fusion_strategy="deferred" \
17
+ --gradient_accumulation_steps=8
scripts/lots/convert_lots_weights.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+
4
+ def convert_lots_weights(ckpt):
5
+ sd = torch.load(ckpt, map_location="cpu")
6
+ image_proj_sd = {}
7
+ cross_attn = {}
8
+ text_proj_sd = {}
9
+ pair_former_sd = {}
10
+ for k in sd:
11
+ if k.startswith("unet"):
12
+ pass
13
+ elif k.startswith("image_proj_model"):
14
+ image_proj_sd[k.replace("image_proj_model.", "")] = sd[k]
15
+ elif k.startswith("text_proj_model"):
16
+ text_proj_sd[k.replace("text_proj_model.", "")] = sd[k]
17
+ elif k.startswith("cross_attn_modules"):
18
+ cross_attn[k.replace("cross_attn_modules.", "")] = sd[k]
19
+ elif k.startswith("pair_former_model"):
20
+ pair_former_sd[k.replace("pair_former_model.", "")] = sd[k]
21
+ assert len(text_proj_sd) > 0, "text projection weights are empty"
22
+ assert len(cross_attn) > 0, "cross-attn modules weights are empty"
23
+ assert len(image_proj_sd) > 0, "image projection weights are empty"
24
+ assert len(pair_former_sd) > 0, "pair former weights are empty"
25
+ return {"image_proj": image_proj_sd, "cross_attn": cross_attn, "text_proj": text_proj_sd, "pair_former": pair_former_sd}
26
+
27
+ if __name__ == "__main__":
28
+ ckpt = "/path/to/training/pytorch_model.bin"
29
+ state_dict = convert_lots_weights(ckpt)
30
+ torch.save(state_dict, ckpt.replace(os.path.basename(ckpt), "lots.bin"))
scripts/lots/inference_lots.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import StableDiffusionXLPipeline
3
+ import os
4
+ from lots.lots_pipeline import LOTSPipeline
5
+ from utils.dinov2_utils import get_dinov2_model
6
+ from tqdm import tqdm
7
+ from utils.script_utils import set_seed
8
+ import argparse
9
+ import os
10
+ from convert_lots_weights import convert_lots_weights
11
+ from sketchy.sketchy_dataset import SketchyDataset
12
+
13
+ def get_args():
14
+ parser = argparse.ArgumentParser(description="Inference script for CLIPAdapter")
15
+ parser.add_argument("--base_model_path", type=str, default="stabilityai/stable-diffusion-xl-base-1.0", help="Path to the base model")
16
+ parser.add_argument("--device", type=str, default="cuda", help="Device to run the model on")
17
+ parser.add_argument("--seed", type=int, default=21, help="Seed for reproducibility")
18
+ parser.add_argument("--dinov2_model", type=str, default="vits14",
19
+ choices=["vits14", "vitb14", "vitl14", "vitg14"],
20
+ help="DINOv2 model type to use")
21
+ parser.add_argument("--ckpt_path", type=str, required=True, help="Path to the checkpoint.bin")
22
+ parser.add_argument("--dataset_root", type=str, required=True, help="Path to the validation dataset root")
23
+ parser.add_argument("--out_dir", type=str, required=True, help="Path to the output directory")
24
+ parser.add_argument("--with_shoes", action="store_true", help="Keep shoes in the dataset")
25
+ parser.add_argument("--resolution", type=int, default=512, help="Resolution for the generated images")
26
+ args = parser.parse_args()
27
+ return args
28
+
29
+ if __name__ == "__main__":
30
+ args = get_args()
31
+ base_model_path = args.base_model_path
32
+ device = args.device
33
+ SEED = args.seed
34
+ ckpt_path = args.ckpt_path
35
+ val_dataset_root = args.dataset_root
36
+ out_dir = args.out_dir
37
+ with_shoes = args.with_shoes
38
+
39
+
40
+
41
+ image_encoder = get_dinov2_model(args.dinov2_model)
42
+
43
+
44
+ # load SDXL pipeline
45
+ pipe = StableDiffusionXLPipeline.from_pretrained(
46
+ base_model_path,
47
+ torch_dtype=torch.float16,
48
+ add_watermarker=False,
49
+ )
50
+
51
+ # check that the bin exists and is properly converted
52
+ if not os.path.exists(ckpt_path):
53
+ print('Converting weights')
54
+ state_dict = convert_lots_weights(ckpt_path.replace(os.path.basename(ckpt_path), "pytorch_model.bin"))
55
+ torch.save(state_dict, ckpt_path)
56
+
57
+ lots_pipe = LOTSPipeline(
58
+ pipe,
59
+ image_encoder=image_encoder,
60
+ model_type=args.dinov2_model,
61
+ lots_ckpt=ckpt_path,
62
+ device=device,
63
+ num_tokens=32,
64
+ )
65
+
66
+
67
+ set_seed(SEED)
68
+ os.makedirs(out_dir, exist_ok=True)
69
+
70
+ os.makedirs(out_dir, exist_ok=True)
71
+ img_dir = os.path.join(out_dir, "image_dir")
72
+ os.makedirs(img_dir, exist_ok=True)
73
+ global_sketch_dir = os.path.join(out_dir, "global_sketch_dir")
74
+ os.makedirs(global_sketch_dir, exist_ok=True)
75
+ local_sketches_dir = os.path.join(out_dir, "local_sketches_dir")
76
+ os.makedirs(local_sketches_dir, exist_ok=True)
77
+ global_descriptions_dir = os.path.join(out_dir, "global_description_dir")
78
+ os.makedirs(global_descriptions_dir, exist_ok=True)
79
+ local_descriptions_dir = os.path.join(out_dir, "local_descriptions_dir")
80
+ os.makedirs(local_descriptions_dir, exist_ok=True)
81
+
82
+ run_name = ckpt_path.split("/")[-3] + "-" + ckpt_path.split("/")[-2].split("-")[-1]
83
+
84
+ val_dataset = SketchyDataset(
85
+ dataset_root=val_dataset_root,
86
+ split="test",
87
+ load_img = True,
88
+ load_global_sketch=True,
89
+ load_local_sketch=True,
90
+ compose_global_sketch=True,
91
+ img_size=args.resolution,
92
+ img_transforms=None,
93
+ global_sketch_transforms=None,
94
+ local_sketch_transforms=None,
95
+ text_tokenizers=None,
96
+ with_shoes=with_shoes,
97
+ concat_locals=True,
98
+ )
99
+
100
+ val_dataloader = torch.utils.data.DataLoader(
101
+ val_dataset,
102
+ batch_size=1,
103
+ num_workers=0,
104
+ drop_last=False,
105
+ shuffle=False,
106
+ collate_fn=val_dataset.collate_fn,
107
+ )
108
+
109
+ prompt = "High quality photo of a model, artistic, 4k"
110
+ with open(os.path.join(out_dir, "prompt.txt"), "w") as f:
111
+ f.write(prompt)
112
+
113
+ for idx, batch in tqdm(enumerate(val_dataloader), desc="Generating images", total=len(val_dataloader)):
114
+ image = batch["image"][0]
115
+ # apply transformations
116
+ global_sketch = batch["global_sketch"][0]
117
+ ann_ids = batch["local_descriptions_ann_ids"][0]
118
+ input_sketches = batch["local_sketches"][0]
119
+ # batch the sketches
120
+ global_desc = batch["global_description"][0]
121
+ local_descriptions = batch["local_descriptions"][0]
122
+ image_id = batch["image_id"][0]
123
+
124
+ gen_images = lots_pipe.generate(prompt=prompt, pil_images=input_sketches, descriptions=local_descriptions, num_samples=1, num_inference_steps=30, resolution=args.resolution, scale=0.8)
125
+ gen_image = gen_images[0]
126
+
127
+ # save data
128
+ with open(os.path.join(global_descriptions_dir, f"{image_id}.txt"), "w") as f:
129
+ f.write(global_desc)
130
+ # save the partial desccriptions
131
+ with open(os.path.join(local_descriptions_dir, f"{image_id}.txt"), "w") as f:
132
+ f.write('\n'.join(local_descriptions))
133
+ # save the sketch
134
+ os.makedirs(os.path.join(local_sketches_dir, f"{image_id}"), exist_ok=True)
135
+ for s, sid in zip(input_sketches, ann_ids):
136
+ s.save(os.path.join(local_sketches_dir, f"{image_id}", f"{sid}.png"))
137
+ global_sketch.save(os.path.join(global_sketch_dir, f"{image_id}.png"))
138
+ output_path = os.path.join(img_dir, f"{image_id}.png")
139
+ gen_image.save(output_path)
140
+ print(f"DONE")
scripts/lots/train_lots.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## partially adapted from https://github.dev/tencent-ailab/IP-Adapter/tree/main
2
+
3
+ import os
4
+ import random
5
+ import argparse
6
+ from pathlib import Path
7
+ import itertools
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torchvision import transforms
12
+ from transformers import AutoImageProcessor
13
+
14
+ from accelerate import Accelerator
15
+ from accelerate.utils import ProjectConfiguration
16
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
17
+ from transformers import CLIPTextModel, CLIPTokenizer, CLIPTextModelWithProjection
18
+ import os
19
+
20
+ from utils.dinov2_utils import get_dinov2_model, get_feature_dim, extract_features, get_pooling_dim
21
+ from utils.script_utils import is_torch2_available
22
+
23
+ if is_torch2_available():
24
+ from lots.cross_attn import AttnProcessor2_0 as AttnProcessor
25
+ from lots.cross_attn import LOTSAttnProcessor2_0 as LOTSAttnProcessor
26
+ else:
27
+ from lots.cross_attn import AttnProcessor
28
+ from lots.cross_attn import LOTSAttnProcessor as LOTSAttnProcessor
29
+
30
+ from convert_lots_weights import convert_lots_weights
31
+ from lots.projectors import TokenProjector, SequenceProjModel
32
+ from lots.pair_former import PairFormer
33
+ from sketchy.sketchy_dataset import SketchyDataset
34
+
35
+ def parse_args():
36
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
37
+ parser.add_argument(
38
+ "--pretrained_model_name_or_path",
39
+ type=str,
40
+ default=None,
41
+ required=True,
42
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
43
+ )
44
+ parser.add_argument(
45
+ "--dataset_root",
46
+ type=str,
47
+ default="",
48
+ required=True,
49
+ help="Training data root path",
50
+ )
51
+ parser.add_argument(
52
+ "--output_dir",
53
+ type=str,
54
+ default="lots_adapter",
55
+ help="The output directory where the model predictions and checkpoints will be written.",
56
+ )
57
+ parser.add_argument(
58
+ "--resolution",
59
+ type=int,
60
+ default=512,
61
+ help=(
62
+ "The resolution for input images"
63
+ ),
64
+ )
65
+ parser.add_argument(
66
+ "--learning_rate",
67
+ type=float,
68
+ default=1e-5,
69
+ help="Learning rate to use.",
70
+ )
71
+ parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
72
+ parser.add_argument("--num_train_epochs", type=int, default=80)
73
+ parser.add_argument(
74
+ "--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
75
+ )
76
+ parser.add_argument("--noise_offset", type=float, default=None, help="noise offset")
77
+ parser.add_argument(
78
+ "--dataloader_num_workers",
79
+ type=int,
80
+ default=0,
81
+ help=(
82
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
83
+ ),
84
+ )
85
+ parser.add_argument(
86
+ "--save_steps",
87
+ type=int,
88
+ default=10000,
89
+ help=(
90
+ "Save a checkpoint of the training state every X updates"
91
+ ),
92
+ )
93
+ parser.add_argument(
94
+ "--mixed_precision",
95
+ type=str,
96
+ default=None,
97
+ choices=["no", "fp16", "bf16"],
98
+ help=(
99
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
100
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
101
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
102
+ ),
103
+ )
104
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
105
+
106
+ parser.add_argument(
107
+ "--dinov2_model",
108
+ type=str,
109
+ default="vits14",
110
+ choices=["vits14", "vitb14", "vitl14", "vitg14"],
111
+ help="DINOv2 model type to use",
112
+ )
113
+ parser.add_argument("--with_shoes", action="store_true", help="Use shoes in the annotations")
114
+
115
+ parser.add_argument("--num_cls_tokens", type=int, default=32, help="Number of class tokens")
116
+ parser.add_argument("--fusion_strategy", type=str, default="deferred", help="Fusion strategy to use", choices=["mean", "deferred"])
117
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.")
118
+
119
+ args = parser.parse_args()
120
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
121
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
122
+ args.local_rank = env_local_rank
123
+
124
+ return args
125
+
126
+
127
+ class LOTSTrainingPipeline(torch.nn.Module):
128
+ """LOTS"""
129
+ def __init__(self, unet, image_proj_model, text_proj_model, pair_former_model, cross_attn_modules, ckpt_path=None):
130
+ super().__init__()
131
+ self.unet = unet
132
+ self.image_proj_model = image_proj_model
133
+ self.text_proj_model = text_proj_model
134
+ self.pair_former_model = pair_former_model
135
+ self.cross_attn_modules = cross_attn_modules
136
+
137
+ if ckpt_path is not None:
138
+ self.load_from_checkpoint(ckpt_path)
139
+
140
+ def forward(self, noisy_latents, timesteps, encoder_hidden_states, unet_added_cond_kwargs, image_embeds, image_masks, partial_text_embeds, partial_text_masks):
141
+ pair_img_tokens = self.image_proj_model(image_embeds)
142
+ pair_txt_tokens = self.text_proj_model(partial_text_embeds)
143
+ # pair fusion with mask
144
+ compressed_pairs = self.pair_former_model(image_embeds=pair_img_tokens, text_embeds=pair_txt_tokens, image_masks=image_masks, text_masks=partial_text_masks)
145
+ # fusion output has shape: B, N*L, C where L is a variable number of tokens
146
+ # create the cross_attn_mask for the unet
147
+ # the mask needs to be a tensor (batch, seq_len) where True means keep, False means discard
148
+ tokens_per_item = self.pair_former_model.num_cls_tokens
149
+ num_items = pair_img_tokens.shape[1]
150
+ pair_cross_attn_mask = torch.zeros((compressed_pairs.shape[0], tokens_per_item*num_items), dtype=torch.bool, device=compressed_pairs.device)
151
+ for i, mask in enumerate(image_masks):
152
+ pair_cross_attn_mask[i, :sum(mask) * tokens_per_item ] = True
153
+
154
+ # encoder_hidden_states will be fed to unet.
155
+ # The processors will handle the first part of the sequence (global text) with the pre-trained weights,
156
+ # and the pairs with the additional cross-attn modules
157
+ encoder_hidden_states = torch.cat([encoder_hidden_states, compressed_pairs], dim=1)
158
+
159
+ # Predict the noise residual
160
+ noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states, added_cond_kwargs=unet_added_cond_kwargs, encoder_attention_mask=pair_cross_attn_mask).sample
161
+ return noise_pred
162
+
163
+ def load_from_checkpoint(self, ckpt_path: str):
164
+ # Calculate original checksums
165
+ orig_img_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
166
+ orig_text_sum = torch.sum(torch.stack([torch.sum(p) for p in self.text_proj_model.parameters()]))
167
+ orig_pair_former_sum = torch.sum(torch.stack([torch.sum(p) for p in self.pair_former_model.parameters()]))
168
+ orig_cross_attn_sum = torch.sum(torch.stack([torch.sum(p) for p in self.cross_attn_modules.parameters()]))
169
+
170
+ state_dict = torch.load(ckpt_path, map_location="cpu")
171
+
172
+ # Load state dict for projection models, pair former, and cross-attn modules
173
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
174
+ self.text_proj_model.load_state_dict(state_dict["text_proj"], strict=True)
175
+ self.pair_former_model.load_state_dict(state_dict["pair_former"], strict=True)
176
+ self.cross_attn_modules.load_state_dict(state_dict["cross_attn"], strict=True)
177
+
178
+ # Calculate new checksums
179
+ new_img_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
180
+ new_text_sum = torch.sum(torch.stack([torch.sum(p) for p in self.text_proj_model.parameters()]))
181
+ new_pair_former_sum = torch.sum(torch.stack([torch.sum(p) for p in self.pair_former_model.parameters()]))
182
+ new_cross_attn_sum = torch.sum(torch.stack([torch.sum(p) for p in self.cross_attn_modules.parameters()]))
183
+
184
+ # Verify if the weights have changed
185
+ assert orig_img_sum != new_img_sum, "Weights of image_proj_model did not change!"
186
+ assert orig_text_sum != new_text_sum, "Weights of text_proj_model did not change!"
187
+ assert orig_pair_former_sum != new_pair_former_sum, "Weights of pair_former_model did not change!"
188
+ assert orig_cross_attn_sum != new_cross_attn_sum, "Weights of cross_attn_modules did not change!"
189
+
190
+ print(f"Successfully loaded weights from checkpoint {ckpt_path}")
191
+
192
+
193
+ def create_batch_tensor(batch, image_drop_prob=0.0, image_size=512):
194
+ # data is returned as a dict of lists
195
+ batch_size = len(batch["image"])
196
+ # find the item in data with the maximum number of sketches
197
+ max_num_sketches = max([len(example) for example in batch["local_sketches"]])
198
+ # do padding to items to put all data in a tensor
199
+ batch["local_sketch_masks"] = []
200
+ batch["local_text_masks"] = []
201
+ batch["drop_image_embeds"] = []
202
+ batch["crop_coords_top_left"] = []
203
+ batch["target_size"] = []
204
+ batch["original_size"] = []
205
+ for idx in range(batch_size):
206
+ # pad local sketches
207
+ num_sketches = len(batch["local_sketches"][idx])
208
+ batch['local_sketch_masks'].append([True for _ in range(num_sketches)]) # True means it's not padding
209
+ batch['local_text_masks'].append([True for _ in range(len(batch["local_descriptions_ids"][idx]))]) # True means it's not padding
210
+ if num_sketches < max_num_sketches:
211
+ batch["local_sketches"][idx] += [torch.zeros_like(batch["local_sketches"][idx][0]) for _ in range(max_num_sketches - num_sketches)]
212
+ # add the padding mask
213
+ batch["local_sketch_masks"][idx] += [False for _ in range(max_num_sketches - num_sketches)]
214
+
215
+ batch["local_sketches"][idx] = torch.cat(batch["local_sketches"][idx], dim=0)
216
+
217
+ # pad local text
218
+ num_local_texts = len(batch["local_descriptions_ids"][idx])
219
+ if num_local_texts < max_num_sketches:
220
+ batch["local_descriptions_ids"][idx] += [torch.zeros_like(batch["local_descriptions_ids"][idx][0]) for _ in range(max_num_sketches - num_local_texts)]
221
+ batch["local_text_masks"][idx] += [False for _ in range(max_num_sketches - num_local_texts)]
222
+
223
+ batch["local_descriptions_ids"][idx] = torch.cat(batch["local_descriptions_ids"][idx], dim=0) # TODO: check dim
224
+
225
+ # pad local text 2
226
+ num_local_texts_2 = len(batch["local_descriptions_ids_2"][idx])
227
+ if num_local_texts_2 < max_num_sketches:
228
+ batch["local_descriptions_ids_2"][idx] += [torch.zeros_like(batch["local_descriptions_ids_2"][idx][0]) for _ in range(max_num_sketches - num_local_texts_2)]
229
+ batch["local_descriptions_ids_2"][idx] = torch.cat(batch["local_descriptions_ids_2"][idx], dim=0) # TODO: check dim
230
+
231
+ # decide whether to drop the image embed
232
+ rand_num = random.random()
233
+ if rand_num < image_drop_prob:
234
+ batch['drop_image_embeds'].append(1)
235
+ else:
236
+ batch['drop_image_embeds'].append(0)
237
+
238
+ # add crop_coords_top_left, original, and target_size
239
+ batch['crop_coords_top_left'].append(torch.tensor([0, 0]))
240
+ batch['original_size'].append(torch.tensor([image_size, image_size]))
241
+ batch['target_size'].append(torch.tensor([image_size, image_size]))
242
+
243
+
244
+ batch["local_descriptions_ids"] = torch.stack(batch["local_descriptions_ids"], dim=0)
245
+ batch["local_descriptions_ids_2"] = torch.stack(batch["local_descriptions_ids_2"], dim=0)
246
+ batch["local_sketches"] = torch.stack(batch["local_sketches"], dim=0)
247
+ batch["original_size"] = torch.stack(batch["original_size"], dim=0)
248
+ batch["crop_coords_top_left"] = torch.stack(batch["crop_coords_top_left"], dim=0)
249
+ batch["target_size"] = torch.stack(batch["target_size"], dim=0)
250
+ return batch
251
+
252
+ def main():
253
+ args = parse_args()
254
+ logging_dir = Path(args.output_dir, "logs")
255
+
256
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
257
+
258
+ accelerator = Accelerator(
259
+ mixed_precision=args.mixed_precision,
260
+ project_config=accelerator_project_config,
261
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
262
+ )
263
+
264
+ if accelerator.is_main_process:
265
+ if args.output_dir is not None:
266
+ os.makedirs(args.output_dir, exist_ok=True)
267
+
268
+ # Load scheduler, tokenizer and models.
269
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
270
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
271
+ text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
272
+ tokenizer_2 = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer_2")
273
+ text_encoder_2 = CLIPTextModelWithProjection.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder_2")
274
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
275
+ unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
276
+ image_encoder = get_dinov2_model(args.dinov2_model)
277
+ feature_dim = get_feature_dim(args.dinov2_model)
278
+ # freeze parameters of models to save more memory
279
+ unet.requires_grad_(False)
280
+ vae.requires_grad_(False)
281
+ text_encoder.requires_grad_(False)
282
+ text_encoder_2.requires_grad_(False)
283
+ image_encoder.requires_grad_(False)
284
+
285
+ num_tokens = 4
286
+ image_proj_model = TokenProjector(
287
+ cross_attention_dim=unet.config.cross_attention_dim,
288
+ embeddings_dim=feature_dim,
289
+ )
290
+ text_proj_model = SequenceProjModel(
291
+ cross_attention_dim=unet.config.cross_attention_dim,
292
+ embeddings_dim=text_encoder.config.projection_dim + text_encoder_2.config.projection_dim,
293
+ extra_context_tokens=num_tokens,
294
+ )
295
+ num_global_tokens = 77 # clip text tokens
296
+
297
+
298
+ pair_former = PairFormer(
299
+ in_channels=unet.config.cross_attention_dim,
300
+ inner_dim=unet.config.cross_attention_dim,
301
+ fusion_strategy=args.fusion_strategy,
302
+ num_layers=2,
303
+ num_attention_heads=8,
304
+ dropout=0.0,
305
+ activation_fn="geglu",
306
+ norm_num_groups=32,
307
+ masking_strategy="compression",
308
+ num_cls_tokens=args.num_cls_tokens
309
+ )
310
+
311
+ # init cross_attention layers
312
+ # credits to IP-Adapter for the procedure
313
+ attn_procs = {}
314
+ unet_sd = unet.state_dict()
315
+ for name in unet.attn_processors.keys():
316
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
317
+ if name.startswith("mid_block"):
318
+ hidden_size = unet.config.block_out_channels[-1]
319
+ elif name.startswith("up_blocks"):
320
+ block_id = int(name[len("up_blocks.")])
321
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
322
+ elif name.startswith("down_blocks"):
323
+ block_id = int(name[len("down_blocks.")])
324
+ hidden_size = unet.config.block_out_channels[block_id]
325
+ if cross_attention_dim is None:
326
+ attn_procs[name] = AttnProcessor()
327
+ else:
328
+ layer_name = name.split(".processor")[0]
329
+ weights = {
330
+ "to_k_lots.weight": unet_sd[layer_name + ".to_k.weight"],
331
+ "to_v_lots.weight": unet_sd[layer_name + ".to_v.weight"],
332
+ }
333
+ attn_procs[name] = LOTSAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_global_tokens=num_global_tokens)
334
+ attn_procs[name].load_state_dict(weights)
335
+ unet.set_attn_processor(attn_procs)
336
+ adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
337
+
338
+ lots_pipeline = LOTSTrainingPipeline(unet, image_proj_model=image_proj_model, text_proj_model=text_proj_model, pair_former_model=pair_former, cross_attn_modules=adapter_modules)
339
+
340
+ weight_dtype = torch.float32
341
+ if accelerator.mixed_precision == "fp16":
342
+ weight_dtype = torch.float16
343
+ elif accelerator.mixed_precision == "bf16":
344
+ weight_dtype = torch.bfloat16
345
+ vae.to(accelerator.device) # use fp32
346
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
347
+ text_encoder_2.to(accelerator.device, dtype=weight_dtype)
348
+ image_encoder.to(accelerator.device, dtype=weight_dtype)
349
+
350
+ params_to_opt = itertools.chain(lots_pipeline.image_proj_model.parameters(), lots_pipeline.text_proj_model.parameters(), lots_pipeline.cross_attn_modules.parameters(), lots_pipeline.pair_former_model.parameters())
351
+ optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
352
+
353
+ # dataloader
354
+ image_transforms = transforms.Compose([
355
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
356
+ transforms.ToTensor(),
357
+ transforms.Normalize([0.5], [0.5]),
358
+ ])
359
+
360
+ sketch_processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base")
361
+ # lambda function to automatically extract pixel values from dino processor
362
+ sketch_transforms = lambda pil_image: sketch_processor(images=pil_image, return_tensors="pt").pixel_values
363
+
364
+ train_dataset = SketchyDataset(args.dataset_root,
365
+ split="train",
366
+ load_img=True,
367
+ load_global_sketch=False,
368
+ load_local_sketch=True,
369
+ img_size=args.resolution,
370
+ img_transforms=image_transforms,
371
+ global_sketch_transforms=None,
372
+ local_sketch_transforms=sketch_transforms,
373
+ text_tokenizers=[tokenizer, tokenizer_2],
374
+ with_shoes=args.with_shoes,
375
+ concat_locals=True, # not needed
376
+ compose_global_sketch=False # not needed
377
+ )
378
+ train_dataloader = torch.utils.data.DataLoader(
379
+ train_dataset,
380
+ shuffle=True,
381
+ collate_fn=train_dataset.collate_fn,
382
+ batch_size=args.train_batch_size,
383
+ num_workers=args.dataloader_num_workers,
384
+ drop_last=True
385
+ )
386
+
387
+ # pre-compute the global description text tokens
388
+ global_desc = "High quality photo of a model, artistic, 4k"
389
+ global_desc_ids1 = tokenizer(global_desc, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt").input_ids
390
+ global_desc_ids2 = tokenizer_2(global_desc, max_length=tokenizer_2.model_max_length, padding="max_length", truncation=True, return_tensors="pt").input_ids
391
+
392
+ # Prepare everything with our `accelerator`.
393
+ lots_pipeline, optimizer, train_dataloader = accelerator.prepare(lots_pipeline, optimizer, train_dataloader)
394
+
395
+ global_step = 0
396
+ for epoch in range(0, args.num_train_epochs):
397
+ for step, batch in enumerate(train_dataloader):
398
+ with accelerator.accumulate(lots_pipeline):
399
+ # handle batching of the inputs with padding
400
+ batch = create_batch_tensor(batch, image_drop_prob=0.05, image_size=args.resolution)
401
+
402
+ # Convert images to latent space
403
+ with torch.no_grad():
404
+ # vae of sdxl should use fp32
405
+ latents = vae.encode(batch["image"].to(accelerator.device, dtype=torch.float32)).latent_dist.sample()
406
+ latents = latents * vae.config.scaling_factor
407
+ latents = latents.to(accelerator.device, dtype=weight_dtype)
408
+
409
+ # Sample noise that we'll add to the latents
410
+ noise = torch.randn_like(latents)
411
+ if args.noise_offset:
412
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
413
+ noise += args.noise_offset * torch.randn((latents.shape[0], latents.shape[1], 1, 1)).to(accelerator.device, dtype=weight_dtype)
414
+
415
+ bsz = latents.shape[0]
416
+ # Sample a random timestep for each image
417
+ timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
418
+ timesteps = timesteps.long()
419
+
420
+ # Add noise to the latents according to the noise magnitude at each timestep
421
+ # (this is the forward diffusion process)
422
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
423
+
424
+ with torch.no_grad():
425
+ image_embeds = []
426
+ for sketches in batch['local_sketches']:
427
+ image_embeds.append(image_encoder(sketches).last_hidden_state)
428
+ image_embeds = torch.stack(image_embeds)
429
+
430
+ image_embeds_ = []
431
+ for image_embed, drop_image_embed in zip(image_embeds, batch["drop_image_embeds"]):
432
+ if drop_image_embed == 1:
433
+ image_embeds_.append(torch.zeros_like(image_embed))
434
+ else:
435
+ image_embeds_.append(image_embed)
436
+ image_embeds = torch.stack(image_embeds_)
437
+
438
+ with torch.no_grad():
439
+ # Use the generic global description. Change this if you also want to train to condition using global description.
440
+ encoder_output = text_encoder(global_desc_ids1.to(accelerator.device), output_hidden_states=True)
441
+ global_text_embeds = encoder_output.hidden_states[-2]
442
+ encoder_output_2 = text_encoder_2(global_desc_ids2.to(accelerator.device), output_hidden_states=True)
443
+ pooled_text_embeds = encoder_output_2[0]
444
+ global_text_embeds_2 = encoder_output_2.hidden_states[-2]
445
+ global_text_embeds = torch.concat([global_text_embeds, global_text_embeds_2], dim=-1) # concat
446
+ # repeat for each item in the batch
447
+ global_text_embeds = global_text_embeds.repeat(args.train_batch_size, 1, 1)
448
+ pooled_text_embeds = pooled_text_embeds.repeat(args.train_batch_size, 1)
449
+
450
+ # local description embeddings
451
+ local_text_embeds = []
452
+ for text_ids_1 in batch['local_descriptions_ids']:
453
+ local_text_embeds.append(text_encoder(text_ids_1.to(accelerator.device))['pooler_output'])
454
+ local_text_embeds = torch.stack(local_text_embeds)
455
+
456
+ partial_text_embeds_ = []
457
+ for text_embed, drop_image_embed in zip(local_text_embeds, batch["drop_image_embeds"]):
458
+ if drop_image_embed == 1:
459
+ partial_text_embeds_.append(torch.zeros_like(text_embed))
460
+ else:
461
+ partial_text_embeds_.append(text_embed)
462
+ local_text_embeds = torch.stack(partial_text_embeds_)
463
+
464
+ # local description embeds 2
465
+ local_text_embeds_2 = []
466
+ for local_text_ids_2 in batch['local_descriptions_ids_2']:
467
+ local_text_embeds_2.append(text_encoder_2(local_text_ids_2.to(accelerator.device))['text_embeds'])
468
+ local_text_embeds_2 = torch.stack(local_text_embeds_2)
469
+ local_text_embeds_2_ = []
470
+ for text_embed, drop_image_embed in zip(local_text_embeds_2, batch["drop_image_embeds"]):
471
+ if drop_image_embed == 1:
472
+ local_text_embeds_2_.append(torch.zeros_like(text_embed))
473
+ else:
474
+ local_text_embeds_2_.append(text_embed)
475
+ local_text_embeds_2 = torch.stack(local_text_embeds_2_)
476
+
477
+ # merge partial text embeds in channels
478
+ local_text_embeds = torch.cat([local_text_embeds, local_text_embeds_2], dim=2)
479
+
480
+ # add cond
481
+ add_time_ids = [
482
+ batch["original_size"].to(accelerator.device),
483
+ batch["crop_coords_top_left"].to(accelerator.device),
484
+ batch["target_size"].to(accelerator.device),
485
+ ]
486
+ add_time_ids = torch.cat(add_time_ids, dim=1).to(accelerator.device, dtype=weight_dtype)
487
+ unet_added_cond_kwargs = {"text_embeds": pooled_text_embeds, "time_ids": add_time_ids}
488
+
489
+ noise_pred = lots_pipeline(noisy_latents, timesteps, global_text_embeds, unet_added_cond_kwargs,
490
+ image_embeds=image_embeds,
491
+ image_masks=batch['local_sketch_masks'],
492
+ partial_text_embeds=local_text_embeds,
493
+ partial_text_masks=batch['local_text_masks'])
494
+
495
+ loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
496
+
497
+ # Gather the losses across all processes for logging (if we use distributed training).
498
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
499
+
500
+ # Backpropagate
501
+ accelerator.backward(loss)
502
+ # accellerator takes care of gradient accumulation
503
+ optimizer.step()
504
+ optimizer.zero_grad()
505
+
506
+
507
+ if accelerator.is_main_process:
508
+ print("Epoch {}, step {}, step_loss: {}".format(
509
+ epoch, step, avg_loss))
510
+
511
+ global_step += 1
512
+
513
+ if global_step % args.save_steps == 0:
514
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
515
+ accelerator.save_state(save_path, safe_serialization=False)
516
+ if accelerator.is_main_process:
517
+ # save fusion config
518
+ pair_former.save_config_json(os.path.join(save_path, 'pair_former_config.json'))
519
+ state_dict = convert_lots_weights(os.path.join(save_path, 'pytorch_model.bin'))
520
+ torch.save(state_dict, os.path.join(save_path, 'lots.bin'))
521
+ # remove old save state
522
+ os.remove(os.path.join(save_path, 'pytorch_model.bin'))
523
+ print(f"Saved checkpoint to {save_path}")
524
+
525
+ accelerator.wait_for_everyone()
526
+ save_path = os.path.join(args.output_dir, f"checkpoint-final")
527
+ accelerator.save_state(save_path, safe_serialization=False)
528
+ if accelerator.is_main_process:
529
+ pair_former.save_config_json(os.path.join(save_path, 'pair_former_config.json'))
530
+ state_dict = convert_lots_weights(os.path.join(save_path, 'pytorch_model.bin'))
531
+ torch.save(state_dict, os.path.join(save_path, 'lots.bin'))
532
+ print(f"Saved checkpoint to {save_path}")
533
+ accelerator.end_training()
534
+
535
+ if __name__ == "__main__":
536
+ main()
scripts/sketchy/sketchy.ipynb ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "258ea95e",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Sketchy"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "code",
13
+ "execution_count": null,
14
+ "id": "6ec5215d",
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "import matplotlib.pyplot as plt\n",
19
+ "from sketchy.sketchy_dataset import SketchyDataset\n",
20
+ "from torch.utils.data import DataLoader\n",
21
+ "from tqdm import tqdm"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "id": "8f772acd",
28
+ "metadata": {},
29
+ "outputs": [],
30
+ "source": [
31
+ "dataset_root = \"<path/to/sketchy/root>\"\n",
32
+ "split = \"train\"\n",
33
+ "img_size = 512\n",
34
+ "load_img = True\n",
35
+ "load_global_sketch = True\n",
36
+ "load_local_sketches = True\n",
37
+ "with_shoes = False\n",
38
+ "concat_locals = True\n",
39
+ "compose_global_sketch = True\n",
40
+ "img_transforms = None\n",
41
+ "global_sketch_transforms = None\n",
42
+ "\n",
43
+ "\n",
44
+ "sketchy_dataset = SketchyDataset(dataset_root=dataset_root, \n",
45
+ " split=split, \n",
46
+ " img_size=img_size, \n",
47
+ " load_img=load_img, \n",
48
+ " load_global_sketch=load_global_sketch,\n",
49
+ " load_local_sketch=load_local_sketches,\n",
50
+ " img_transforms=img_transforms,\n",
51
+ " global_sketch_transforms=global_sketch_transforms,\n",
52
+ " with_shoes=with_shoes,\n",
53
+ " concat_locals=concat_locals,\n",
54
+ " compose_global_sketch=compose_global_sketch,\n",
55
+ " )\n",
56
+ "print(f\"Number of images in {split} split: {len(sketchy_dataset)}\")"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "execution_count": null,
62
+ "id": "0d036a36",
63
+ "metadata": {},
64
+ "outputs": [],
65
+ "source": [
66
+ "# create a dataloader with the proper collate function\n",
67
+ "dataloader = DataLoader(sketchy_dataset,\n",
68
+ " batch_size=8, \n",
69
+ " shuffle=False, \n",
70
+ " num_workers=0, \n",
71
+ " collate_fn=sketchy_dataset.collate_fn)"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "markdown",
76
+ "id": "5baa0a3c",
77
+ "metadata": {},
78
+ "source": [
79
+ "## Visualize the item data"
80
+ ]
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "execution_count": null,
85
+ "id": "6ea93e19",
86
+ "metadata": {},
87
+ "outputs": [],
88
+ "source": [
89
+ "# get a sample from the dataset\n",
90
+ "item = sketchy_dataset[13]\n",
91
+ "print(\"####### ITEM KEYS ########\")\n",
92
+ "for key in item.keys():\n",
93
+ " print(f\"{key}\")\n",
94
+ " \n",
95
+ "print(\"\\n####### IMAGE ########\")\n",
96
+ "# item['image'] is an image (by default PIL.Image)\n",
97
+ "plt.imshow(item['image'])\n",
98
+ "plt.axis('off')\n",
99
+ "plt.title(\"GT Image of item\")\n",
100
+ "plt.show()\n",
101
+ "\n",
102
+ "\n",
103
+ "print(\"\\n####### LOCAL DESCRIPTIONS ########\")\n",
104
+ "# item['local_descriptions'] is a list of strings. Each string is a description of a single item in the image.\n",
105
+ "# NOTE: the local descriptions, local sketches, and masks are all aligned, meaning that the i-th local description corresponds to the i-th mask and i-th local sketch.\n",
106
+ "num_descriptions = len(item['local_descriptions'])\n",
107
+ "print(f\"Number of local descriptions in item: {num_descriptions}\")\n",
108
+ "for i, desc in enumerate(item['local_descriptions']):\n",
109
+ " print(f\"Local description {i}: {desc}\")\n",
110
+ "\n",
111
+ "print(\"\\n####### GLOBAL SKETCH ########\")\n",
112
+ "# item['global_sketch'] is an image\n",
113
+ "# visualize the global sketch\n",
114
+ "plt.imshow(item['global_sketch'])\n",
115
+ "plt.axis('off')\n",
116
+ "plt.title(\"Global Sketch\")\n",
117
+ "plt.show()\n",
118
+ "\n",
119
+ "print(\"\\n####### LOCAL SKETCHES ########\")\n",
120
+ "# item['local_sketches'] is a list of images. Each item in the item has a list. In each sublist, there is an image for each local sketch in the item.\n",
121
+ "num_local_sketches = len(item['local_sketches'])\n",
122
+ "assert num_local_sketches == num_descriptions, \"Number of local sketches will always be equal to number of local descriptions\"\n",
123
+ "print(f\"Number of local sketches in item 0: {num_local_sketches}\")\n",
124
+ "# visualize the local sketches\n",
125
+ "MAX_NUM_COLUMNS = 2\n",
126
+ "num_cols = min(num_local_sketches, MAX_NUM_COLUMNS)\n",
127
+ "num_rows = num_local_sketches // num_cols + (num_local_sketches % num_cols > 0)\n",
128
+ "fig, axs = plt.subplots(num_rows, num_cols, figsize=(5, 5))\n",
129
+ "if num_local_sketches > 1:\n",
130
+ " # flatten the axs for easier indexing\n",
131
+ " axs = axs.flatten()\n",
132
+ " for i in range(len(item['local_sketches'])):\n",
133
+ " axs[i].imshow(item['local_sketches'][i])\n",
134
+ " axs[i].set_title(f\"Local Sketch {i}\")\n",
135
+ " axs[i].axis('off')\n",
136
+ "else:\n",
137
+ " axs.imshow(item['local_sketches'][0])\n",
138
+ " axs.set_title(f\"Local Sketch 0\")\n",
139
+ " axs.axis('off')"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": null,
145
+ "id": "56d29ae3",
146
+ "metadata": {},
147
+ "outputs": [],
148
+ "source": [
149
+ "# iterate over the dataloader.\n",
150
+ "# NOTE: this changes how the data is structured due to the collate function. This is needed for batching the data.\n",
151
+ "for idx, batch in tqdm(enumerate(dataloader), total=len(dataloader), desc=\"Iterating over batches\"):\n",
152
+ " continue # remove this to visualize the first element of a batch\n",
153
+ "\n",
154
+ " print(\"####### BATCH INFO ########\")\n",
155
+ " # every batch is a dictionary with the following keys:\n",
156
+ " for key in batch.keys():\n",
157
+ " print(f\"{key}\")\n",
158
+ " \n",
159
+ " print(\"\\n####### IMAGE ########\")\n",
160
+ " # batch['image'] is a list of images, one for each item in the batch\n",
161
+ " plt.imshow(batch['image'][0])\n",
162
+ " plt.axis('off')\n",
163
+ " plt.title(\"GT Image of item 0 in batch\")\n",
164
+ " plt.show()\n",
165
+ " \n",
166
+ "\n",
167
+ " print(\"####### LOCAL DESCRIPTIONS ########\")\n",
168
+ " # batch['local_descriptions'] is a list of lists of strings. Each item in the batch has a list. In each sublist, there is a description for each item in the image.\n",
169
+ " num_descriptions = len(batch['local_descriptions'][0])\n",
170
+ " print(f\"Number of local descriptions in item 0: {num_descriptions}\")\n",
171
+ " for i, desc in enumerate(batch['local_descriptions'][0]):\n",
172
+ " print(f\"Local description {i}: {desc}\")\n",
173
+ "\n",
174
+ " \n",
175
+ " print(\"####### GLOBAL SKETCH ########\")\n",
176
+ " # batch['global_sketch'] is a list of images, one for each item in the batch\n",
177
+ " # visualize the global sketch\n",
178
+ " plt.imshow(batch['global_sketch'][0])\n",
179
+ " plt.axis('off')\n",
180
+ " plt.title(\"Global Sketch of item 0 in batch\")\n",
181
+ " plt.show()\n",
182
+ "\n",
183
+ " \n",
184
+ " print(\"####### LOCAL SKETCHES ########\")\n",
185
+ " # batch['local_sketches'] is a list of lists of images. Each item in the batch has a list. In each sublist, there is an image for each local sketch in the item.\n",
186
+ " num_local_sketches = len(batch['local_sketches'][0])\n",
187
+ " assert num_local_sketches == num_descriptions, \"Number of local sketches will always be equal to number of local descriptions\"\n",
188
+ " print(f\"Number of local sketches in item 0: {num_local_sketches}\")\n",
189
+ " # visualize the local sketches\n",
190
+ " MAX_NUM_COLUMNS = 2\n",
191
+ " num_cols = min(num_local_sketches, MAX_NUM_COLUMNS)\n",
192
+ " num_rows = num_local_sketches // num_cols + (num_local_sketches % num_cols > 0)\n",
193
+ " fig, axs = plt.subplots(num_rows, num_cols, figsize=(5, 5))\n",
194
+ " # flatten the axs for easier indexing\n",
195
+ " if num_local_sketches > 1:\n",
196
+ " axs = axs.flatten()\n",
197
+ " for i in range(len(batch['local_sketches'][0])):\n",
198
+ " axs[i].imshow(batch['local_sketches'][0][i])\n",
199
+ " axs[i].set_title(f\"Local Sketch {i}\")\n",
200
+ " axs[i].axis('off')\n",
201
+ " else:\n",
202
+ " axs.imshow(batch['local_sketches'][0][0])\n",
203
+ " axs.set_title(f\"Local Sketch 0\")\n",
204
+ " axs.axis('off')\n",
205
+ " break # remove this to iterate through all batches"
206
+ ]
207
+ }
208
+ ],
209
+ "metadata": {
210
+ "kernelspec": {
211
+ "display_name": "sketch2img",
212
+ "language": "python",
213
+ "name": "python3"
214
+ },
215
+ "language_info": {
216
+ "codemirror_mode": {
217
+ "name": "ipython",
218
+ "version": 3
219
+ },
220
+ "file_extension": ".py",
221
+ "mimetype": "text/x-python",
222
+ "name": "python",
223
+ "nbconvert_exporter": "python",
224
+ "pygments_lexer": "ipython3",
225
+ "version": "3.12.9"
226
+ }
227
+ },
228
+ "nbformat": 4,
229
+ "nbformat_minor": 5
230
+ }
setup.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from setuptools import setup
2
+
3
+ setup()
src/lots/__init__.py ADDED
File without changes
src/lots/cross_attn.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ class LOTSAttnProcessor2_0(torch.nn.Module):
6
+ r"""
7
+ Attention processor for LOTS cross-attention modules for PyTorch 2.0.
8
+ Inspired by IP-Adapter https://github.dev/tencent-ailab/IP-Adapter/tree/main
9
+ Args:
10
+ hidden_size (`int`):
11
+ The hidden size of the attention layer.
12
+ cross_attention_dim (`int`):
13
+ The number of channels in the `encoder_hidden_states`.
14
+ scale (`float`, defaults to 1.0):
15
+ the weight scale of image prompt.
16
+ num_global_tokens (`int`):
17
+ The context length of the global text tokens (not pair information).
18
+ """
19
+
20
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_global_tokens=77):
21
+ super().__init__()
22
+
23
+ if not hasattr(F, "scaled_dot_product_attention"):
24
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
25
+
26
+ self.hidden_size = hidden_size
27
+ self.cross_attention_dim = cross_attention_dim
28
+ self.scale = scale
29
+ self.num_global_tokens = num_global_tokens
30
+
31
+ self.to_k_lots = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
32
+ self.to_v_lots = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
33
+
34
+ def __call__(
35
+ self,
36
+ attn,
37
+ hidden_states,
38
+ encoder_hidden_states=None,
39
+ attention_mask=None,
40
+ temb=None,
41
+ *args,
42
+ **kwargs,
43
+ ):
44
+ residual = hidden_states
45
+
46
+ if attn.spatial_norm is not None:
47
+ hidden_states = attn.spatial_norm(hidden_states, temb)
48
+
49
+ input_ndim = hidden_states.ndim
50
+
51
+ if input_ndim == 4:
52
+ batch_size, channel, height, width = hidden_states.shape
53
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
54
+
55
+ batch_size, sequence_length, _ = (
56
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
57
+ )
58
+
59
+ # our attention mask in case of padding items in the batch
60
+ if attention_mask is not None:
61
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length - self.num_global_tokens, batch_size)
62
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
63
+
64
+ if attn.group_norm is not None:
65
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
66
+
67
+ query = attn.to_q(hidden_states)
68
+
69
+ if encoder_hidden_states is None:
70
+ encoder_hidden_states = hidden_states
71
+ else:
72
+ # get encoder_hidden_states, lots_pair_states
73
+ encoder_hidden_states, lots_pair_states = (
74
+ encoder_hidden_states[:, :self.num_global_tokens, :],
75
+ encoder_hidden_states[:, self.num_global_tokens:, :],
76
+ )
77
+ if attn.norm_cross:
78
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
79
+
80
+ key = attn.to_k(encoder_hidden_states)
81
+ value = attn.to_v(encoder_hidden_states)
82
+
83
+ inner_dim = key.shape[-1]
84
+ head_dim = inner_dim // attn.heads
85
+
86
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
87
+
88
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
89
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
90
+
91
+ hidden_states = F.scaled_dot_product_attention(
92
+ query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False
93
+ )
94
+
95
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
96
+ hidden_states = hidden_states.to(query.dtype)
97
+
98
+ # for lots cross-attn
99
+ lots_key = self.to_k_lots(lots_pair_states)
100
+ lots_value = self.to_v_lots(lots_pair_states)
101
+
102
+ lots_key = lots_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
103
+ lots_value = lots_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
104
+
105
+ lots_pair_states = F.scaled_dot_product_attention(
106
+ query, lots_key, lots_value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
107
+ )
108
+ with torch.no_grad():
109
+ self.attn_map = query @ lots_key.transpose(-2, -1).softmax(dim=-1)
110
+ # use the mask to mask the attention map
111
+ if attention_mask is not None:
112
+ self.masked_attn_map = (query @ lots_key.transpose(-2, -1) + attention_mask).softmax(dim=-1)
113
+
114
+
115
+ lots_pair_states = lots_pair_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
116
+ lots_pair_states = lots_pair_states.to(query.dtype)
117
+
118
+ hidden_states = hidden_states + self.scale * lots_pair_states
119
+
120
+ # linear proj
121
+ hidden_states = attn.to_out[0](hidden_states)
122
+ # dropout
123
+ hidden_states = attn.to_out[1](hidden_states)
124
+
125
+ if input_ndim == 4:
126
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
127
+
128
+ if attn.residual_connection:
129
+ hidden_states = hidden_states + residual
130
+
131
+ hidden_states = hidden_states / attn.rescale_output_factor
132
+
133
+ return hidden_states
134
+
135
+
136
+ class LOTSAttnProcessor(nn.Module):
137
+ r"""
138
+ Attention processor for LOTS cross-attention.
139
+ Inspired by IP-Adapter
140
+ Args:
141
+ hidden_size (`int`):
142
+ The hidden size of the attention layer.
143
+ cross_attention_dim (`int`):
144
+ The number of channels in the `encoder_hidden_states`.
145
+ scale (`float`, defaults to 1.0):
146
+ the weight scale of image prompt.
147
+ num_global_tokens (`int`):
148
+ The context length of the global text tokens (not pair information).
149
+ """
150
+
151
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_global_tokens=77):
152
+ super().__init__()
153
+
154
+ self.hidden_size = hidden_size
155
+ self.cross_attention_dim = cross_attention_dim
156
+ self.scale = scale
157
+ self.num_global_tokens = num_global_tokens
158
+
159
+ self.to_k_lots = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
160
+ self.to_v_lots = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
161
+
162
+ def __call__(
163
+ self,
164
+ attn,
165
+ hidden_states,
166
+ encoder_hidden_states=None,
167
+ attention_mask=None,
168
+ temb=None,
169
+ *args,
170
+ **kwargs,
171
+ ):
172
+ residual = hidden_states
173
+
174
+ if attn.spatial_norm is not None:
175
+ hidden_states = attn.spatial_norm(hidden_states, temb)
176
+
177
+ input_ndim = hidden_states.ndim
178
+
179
+ if input_ndim == 4:
180
+ batch_size, channel, height, width = hidden_states.shape
181
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
182
+
183
+ batch_size, sequence_length, _ = (
184
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
185
+ )
186
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
187
+
188
+ if attn.group_norm is not None:
189
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
190
+
191
+ query = attn.to_q(hidden_states)
192
+
193
+ if encoder_hidden_states is None:
194
+ encoder_hidden_states = hidden_states
195
+ else:
196
+ # get encoder_hidden_states, lots_pair_states
197
+ encoder_hidden_states, lots_pair_states = (
198
+ encoder_hidden_states[:, :self.num_global_tokens, :],
199
+ encoder_hidden_states[:, self.num_global_tokens:, :],
200
+ )
201
+ if attn.norm_cross:
202
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
203
+
204
+ key = attn.to_k(encoder_hidden_states)
205
+ value = attn.to_v(encoder_hidden_states)
206
+
207
+ query = attn.head_to_batch_dim(query)
208
+ key = attn.head_to_batch_dim(key)
209
+ value = attn.head_to_batch_dim(value)
210
+
211
+ attention_probs = attn.get_attention_scores(query, key, None)
212
+ hidden_states = torch.bmm(attention_probs, value)
213
+ hidden_states = attn.batch_to_head_dim(hidden_states)
214
+
215
+ # for lots cross-attn
216
+ lots_key = self.to_k_lots(lots_pair_states)
217
+ lots_value = self.to_v_lots(lots_pair_states)
218
+
219
+ lots_key = attn.head_to_batch_dim(lots_key)
220
+ lots_value = attn.head_to_batch_dim(lots_value)
221
+
222
+ lots_attention_probs = attn.get_attention_scores(query, lots_key, attention_mask)
223
+ self.attn_map = lots_attention_probs
224
+ lots_pair_states = torch.bmm(lots_attention_probs, lots_value)
225
+ lots_pair_states = attn.batch_to_head_dim(lots_pair_states)
226
+
227
+ hidden_states = hidden_states + self.scale * lots_pair_states
228
+
229
+ # linear proj
230
+ hidden_states = attn.to_out[0](hidden_states)
231
+ # dropout
232
+ hidden_states = attn.to_out[1](hidden_states)
233
+
234
+ if input_ndim == 4:
235
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
236
+
237
+ if attn.residual_connection:
238
+ hidden_states = hidden_states + residual
239
+
240
+ hidden_states = hidden_states / attn.rescale_output_factor
241
+
242
+ return hidden_states
243
+
244
+
245
+ # Processors from IP-Adapter https://github.dev/tencent-ailab/IP-Adapter/tree/main
246
+ class AttnProcessor(nn.Module):
247
+ r"""
248
+ Default processor for performing attention-related computations.
249
+ """
250
+
251
+ def __init__(
252
+ self,
253
+ hidden_size=None,
254
+ cross_attention_dim=None,
255
+ ):
256
+ super().__init__()
257
+
258
+ def __call__(
259
+ self,
260
+ attn,
261
+ hidden_states,
262
+ encoder_hidden_states=None,
263
+ attention_mask=None,
264
+ temb=None,
265
+ *args,
266
+ **kwargs,
267
+ ):
268
+ residual = hidden_states
269
+
270
+ if attn.spatial_norm is not None:
271
+ hidden_states = attn.spatial_norm(hidden_states, temb)
272
+
273
+ input_ndim = hidden_states.ndim
274
+
275
+ if input_ndim == 4:
276
+ batch_size, channel, height, width = hidden_states.shape
277
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
278
+
279
+ batch_size, sequence_length, _ = (
280
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
281
+ )
282
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
283
+
284
+ if attn.group_norm is not None:
285
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
286
+
287
+ query = attn.to_q(hidden_states)
288
+
289
+ if encoder_hidden_states is None:
290
+ encoder_hidden_states = hidden_states
291
+ elif attn.norm_cross:
292
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
293
+
294
+ key = attn.to_k(encoder_hidden_states)
295
+ value = attn.to_v(encoder_hidden_states)
296
+
297
+ query = attn.head_to_batch_dim(query)
298
+ key = attn.head_to_batch_dim(key)
299
+ value = attn.head_to_batch_dim(value)
300
+
301
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
302
+ hidden_states = torch.bmm(attention_probs, value)
303
+ hidden_states = attn.batch_to_head_dim(hidden_states)
304
+
305
+ # linear proj
306
+ hidden_states = attn.to_out[0](hidden_states)
307
+ # dropout
308
+ hidden_states = attn.to_out[1](hidden_states)
309
+
310
+ if input_ndim == 4:
311
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
312
+
313
+ if attn.residual_connection:
314
+ hidden_states = hidden_states + residual
315
+
316
+ hidden_states = hidden_states / attn.rescale_output_factor
317
+
318
+ return hidden_states
319
+
320
+ class AttnProcessor2_0(torch.nn.Module):
321
+ r"""
322
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
323
+ """
324
+
325
+ def __init__(
326
+ self,
327
+ hidden_size=None,
328
+ cross_attention_dim=None,
329
+ ):
330
+ super().__init__()
331
+ if not hasattr(F, "scaled_dot_product_attention"):
332
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
333
+
334
+ def __call__(
335
+ self,
336
+ attn,
337
+ hidden_states,
338
+ encoder_hidden_states=None,
339
+ attention_mask=None,
340
+ temb=None,
341
+ *args,
342
+ **kwargs,
343
+ ):
344
+ residual = hidden_states
345
+
346
+ if attn.spatial_norm is not None:
347
+ hidden_states = attn.spatial_norm(hidden_states, temb)
348
+
349
+ input_ndim = hidden_states.ndim
350
+
351
+ if input_ndim == 4:
352
+ batch_size, channel, height, width = hidden_states.shape
353
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
354
+
355
+ batch_size, sequence_length, _ = (
356
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
357
+ )
358
+
359
+ if attention_mask is not None:
360
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
361
+ # scaled_dot_product_attention expects attention_mask shape to be
362
+ # (batch, heads, source_length, target_length)
363
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
364
+
365
+ if attn.group_norm is not None:
366
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
367
+
368
+ query = attn.to_q(hidden_states)
369
+
370
+ if encoder_hidden_states is None:
371
+ encoder_hidden_states = hidden_states
372
+ elif attn.norm_cross:
373
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
374
+
375
+ key = attn.to_k(encoder_hidden_states)
376
+ value = attn.to_v(encoder_hidden_states)
377
+
378
+ inner_dim = key.shape[-1]
379
+ head_dim = inner_dim // attn.heads
380
+
381
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
382
+
383
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
384
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
385
+
386
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
387
+ # TODO: add support for attn.scale when we move to Torch 2.1
388
+ hidden_states = F.scaled_dot_product_attention(
389
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
390
+ )
391
+
392
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
393
+ hidden_states = hidden_states.to(query.dtype)
394
+
395
+ # linear proj
396
+ hidden_states = attn.to_out[0](hidden_states)
397
+ # dropout
398
+ hidden_states = attn.to_out[1](hidden_states)
399
+
400
+ if input_ndim == 4:
401
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
402
+
403
+ if attn.residual_connection:
404
+ hidden_states = hidden_states + residual
405
+
406
+ hidden_states = hidden_states / attn.rescale_output_factor
407
+
408
+ return hidden_states
src/lots/lots_pipeline.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from PIL import Image
3
+ import torch
4
+ import os
5
+ from typing import List
6
+ import torch
7
+ from PIL import Image
8
+ from lots.projectors import TokenProjector, SequenceProjModel
9
+ from utils.dinov2_utils import get_pooling_dim, get_feature_dim
10
+ from transformers import AutoImageProcessor
11
+ from lots.pair_former import PairFormer
12
+ from utils.script_utils import is_torch2_available, get_generator
13
+ import json
14
+
15
+ if is_torch2_available():
16
+ from lots.cross_attn import AttnProcessor2_0 as AttnProcessor
17
+ from lots.cross_attn import LOTSAttnProcessor2_0 as LOTSAttnProcessor
18
+ else:
19
+ from lots.cross_attn import AttnProcessor
20
+ from lots.cross_attn import LOTSAttnProcessor
21
+
22
+ class LOTSPipeline:
23
+
24
+ def __init__(self, sd_pipe, lots_ckpt, device, image_encoder=None, num_global_tokens=77, num_tokens=32, model_type='vits14'):
25
+ # TODO: documentation
26
+ self.device = device
27
+ self.image_encoder = image_encoder
28
+ self.lots_ckpt = lots_ckpt
29
+ self.num_global_tokens = num_global_tokens
30
+ self.num_tokens = num_tokens
31
+ self.model_type = model_type
32
+
33
+
34
+ self.pipe = sd_pipe.to(self.device)
35
+ self.add_cross_attn(num_global_tokens=num_global_tokens)
36
+
37
+ self.image_encoder = image_encoder.to(self.device, dtype=torch.float16)
38
+ self.image_processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base")
39
+
40
+ # image proj model
41
+ self.image_proj_model, self.text_proj_model, self.pair_former = self.init_proj()
42
+ self.load_cross_attn()
43
+
44
+ def add_cross_attn(self, num_global_tokens=77):
45
+ unet = self.pipe.unet
46
+ attn_procs = {}
47
+ for name in unet.attn_processors.keys():
48
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
49
+ if name.startswith("mid_block"):
50
+ hidden_size = unet.config.block_out_channels[-1]
51
+ elif name.startswith("up_blocks"):
52
+ block_id = int(name[len("up_blocks.")])
53
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
54
+ elif name.startswith("down_blocks"):
55
+ block_id = int(name[len("down_blocks.")])
56
+ hidden_size = unet.config.block_out_channels[block_id]
57
+ if cross_attention_dim is None:
58
+ attn_procs[name] = AttnProcessor()
59
+ else:
60
+ attn_procs[name] = LOTSAttnProcessor(
61
+ hidden_size=hidden_size,
62
+ cross_attention_dim=cross_attention_dim,
63
+ scale=1.0,
64
+ num_global_tokens=num_global_tokens,
65
+ ).to(self.device, dtype=torch.float16)
66
+ unet.set_attn_processor(attn_procs)
67
+
68
+ def init_proj(self):
69
+
70
+ base_dim = get_feature_dim(self.model_type)
71
+ embeddings_dim = get_pooling_dim(base_dim, "cls")
72
+
73
+ image_proj_model = TokenProjector(
74
+ cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
75
+ embeddings_dim=embeddings_dim,
76
+ ).to(self.device, dtype=torch.float16)
77
+
78
+ text_proj_model = SequenceProjModel(
79
+ cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
80
+ embeddings_dim=self.pipe.text_encoder.config.projection_dim + self.pipe.text_encoder_2.config.projection_dim,
81
+ extra_context_tokens=4,
82
+ ).to(self.device, dtype=torch.float16)
83
+
84
+ # check if config is available from ckpt folder
85
+ # should be in the same folder as self.lots_ckpt
86
+ config_path = os.path.join(os.path.dirname(self.lots_ckpt), "pair_former_config.json")
87
+ if os.path.exists(config_path):
88
+ with open(config_path, "r") as f:
89
+ fusion_config = json.load(f)
90
+ pair_former_model = PairFormer(**fusion_config).to(self.device, dtype=torch.float16)
91
+ else:
92
+ # use default parameters
93
+ pair_former_model = PairFormer(
94
+ in_channels=self.pipe.unet.config.cross_attention_dim,
95
+ inner_dim=self.pipe.unet.config.cross_attention_dim,
96
+ fusion_strategy="deferred",
97
+ num_layers=2,
98
+ num_attention_heads=8,
99
+ dropout=0.0,
100
+ activation_fn="geglu",
101
+ norm_num_groups=32,
102
+ masking_strategy="compression",
103
+ num_cls_tokens=32,
104
+ ).to(self.device, dtype=torch.float16)
105
+ return image_proj_model, text_proj_model, pair_former_model
106
+
107
+ def load_cross_attn(self):
108
+ state_dict = torch.load(self.lots_ckpt, map_location="cpu")
109
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
110
+ self.text_proj_model.load_state_dict(state_dict["text_proj"], strict=True)
111
+ self.pair_former.load_state_dict(state_dict["pair_former"], strict=True)
112
+ # load through reference to unet to avoid issues
113
+ attn_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
114
+ attn_layers.load_state_dict(state_dict["cross_attn"], strict=True)
115
+
116
+ def generate(
117
+ self,
118
+ pil_images,
119
+ descriptions,
120
+ prompt=None,
121
+ negative_prompt=None,
122
+ scale=1.0,
123
+ num_samples=4,
124
+ seed=None,
125
+ num_inference_steps=30,
126
+ resolution=512,
127
+ **kwargs,
128
+ ):
129
+ self.set_scale(scale)
130
+
131
+ num_prompts = 1
132
+ num_sketches = len(pil_images)
133
+
134
+ if prompt is None:
135
+ prompt = "High quality photo of a model, artistic, 4k"
136
+ if negative_prompt is None:
137
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
138
+
139
+ if not isinstance(prompt, List):
140
+ prompt = [prompt] * num_prompts
141
+ if not isinstance(negative_prompt, List):
142
+ negative_prompt = [negative_prompt] * num_prompts
143
+
144
+ # TODO: implement multiple images per prompt
145
+ # sketch image embeds
146
+ image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_images)
147
+
148
+ # text embeds
149
+ text_prompt_embeds, uncond_text_prompt_embeds = self.get_text_embeds(descriptions)
150
+
151
+ # fusion embeds
152
+ # create masks for the pair former
153
+ mask = [[True for _ in range(num_sketches)]] # extra dimension for batching
154
+ pair_embeds = self.pair_former(image_embeds=image_prompt_embeds, text_embeds=text_prompt_embeds, image_masks=mask, text_masks=mask)
155
+ uncond_pair_embeds = self.pair_former(image_embeds=uncond_image_prompt_embeds, text_embeds=uncond_text_prompt_embeds, image_masks=mask, text_masks=mask)
156
+
157
+
158
+ with torch.inference_mode():
159
+ (
160
+ prompt_embeds,
161
+ negative_prompt_embeds,
162
+ pooled_prompt_embeds,
163
+ negative_pooled_prompt_embeds,
164
+ ) = self.pipe.encode_prompt(
165
+ prompt,
166
+ num_images_per_prompt=num_samples,
167
+ do_classifier_free_guidance=True,
168
+ negative_prompt=negative_prompt,
169
+ )
170
+ prompt_embeds = torch.cat([prompt_embeds, pair_embeds], dim=1)
171
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_pair_embeds], dim=1)
172
+
173
+ self.generator = get_generator(seed, self.device)
174
+
175
+ images = self.pipe(
176
+ prompt_embeds=prompt_embeds,
177
+ negative_prompt_embeds=negative_prompt_embeds,
178
+ pooled_prompt_embeds=pooled_prompt_embeds,
179
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
180
+ num_inference_steps=num_inference_steps,
181
+ generator=self.generator,
182
+ height=resolution,
183
+ width=resolution,
184
+ **kwargs,
185
+ ).images
186
+
187
+ return images
188
+
189
+ @torch.inference_mode()
190
+ def get_image_embeds(self, pil_images):
191
+ if isinstance(pil_images, Image.Image):
192
+ pil_images = [pil_images]
193
+
194
+ sketches = [self.image_processor(images=pil_image, return_tensors="pt").pixel_values.to(self.device, dtype=torch.float16) for pil_image in pil_images]
195
+ sketches = torch.cat(sketches, dim=0)
196
+ outputs = self.image_encoder(sketches)
197
+
198
+ image_embeds = outputs.last_hidden_state.unsqueeze(0) # add batch dimension
199
+
200
+ image_prompt_embeds = self.image_proj_model(image_embeds)
201
+ uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(image_embeds))
202
+ return image_prompt_embeds, uncond_image_prompt_embeds
203
+
204
+ @torch.inference_mode()
205
+ def get_text_embeds(self, descriptions):
206
+ if descriptions is not None:
207
+ if isinstance(descriptions, str):
208
+ descriptions = [descriptions]
209
+ descriptions_ids = [self.pipe.tokenizer(description, return_tensors="pt", padding="max_length", truncation=True, max_length=self.pipe.tokenizer.model_max_length).input_ids.to(self.device)
210
+ for description in descriptions]
211
+ text_embeds = [self.pipe.text_encoder(description_ids)['pooler_output'] for description_ids in descriptions_ids]
212
+ descriptions_ids_2 = [self.pipe.tokenizer_2(description, return_tensors="pt", padding="max_length", truncation=True, max_length=self.pipe.tokenizer_2.model_max_length).input_ids.to(self.device)
213
+ for description in descriptions]
214
+ text_embeds_2 = [self.pipe.text_encoder_2(description_ids_2)['text_embeds'] for description_ids_2 in descriptions_ids_2]
215
+ text_embeds = torch.cat(text_embeds, dim=0)
216
+ text_embeds_2 = torch.cat(text_embeds_2, dim=0)
217
+ text_embeds = torch.cat([text_embeds, text_embeds_2], dim=1).unsqueeze(0) # add batch dimension
218
+
219
+ text_prompt_embeds = self.text_proj_model(text_embeds)
220
+ uncond_text_prompt_embeds = self.text_proj_model(torch.zeros_like(text_embeds))
221
+ return text_prompt_embeds, uncond_text_prompt_embeds
222
+
223
+ def set_scale(self, scale):
224
+ for attn_processor in self.pipe.unet.attn_processors.values():
225
+ if isinstance(attn_processor, LOTSAttnProcessor):
226
+ attn_processor.scale = scale
227
+
src/lots/pair_former.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusers.models.attention import BasicTransformerBlock
4
+ import json
5
+
6
+ class PairFormer(nn.Module):
7
+ # TODO: documentation
8
+ def __init__(self,
9
+ in_channels: int,
10
+ fusion_strategy: str = "deferred",
11
+ num_layers: int = 2,
12
+ num_attention_heads: int = 8,
13
+ inner_dim: int = 2048,
14
+ dropout: float = 0.0,
15
+ norm_num_groups: int = 32,
16
+ activation_fn: str = "geglu",
17
+ masking_strategy="compression",
18
+ num_cls_tokens: int = 30,
19
+ ):
20
+ super(PairFormer, self).__init__()
21
+ self.allowed_masking_strategies = ["modality", "pair", "compression", "all"]
22
+ self.mask_type = ["pair", "modality", "compression", "all"]
23
+ self.allowed_fusion_strategy = ["mean", "deferred"]
24
+ assert inner_dim % num_attention_heads == 0, "Inner_dim must be divisible by num_attention_heads"
25
+ assert in_channels % norm_num_groups == 0, "Inner_dim must be divisible by norm_num_groups"
26
+ assert masking_strategy in self.allowed_masking_strategies, "Masking strategy not supported, choose from: {}".format(self.allowed_masking_strategies)
27
+ self.masking_strategy = masking_strategy
28
+ self.attention_head_dim = inner_dim // num_attention_heads
29
+ self.in_channels = in_channels
30
+ self.with_in_projection = in_channels != inner_dim
31
+ self.with_out_projection = in_channels != inner_dim
32
+ self.fusion_strategy = fusion_strategy
33
+ self.num_layers = num_layers
34
+ self.inner_dim = inner_dim
35
+ self.num_cls_tokens = num_cls_tokens
36
+ # save the parameters in a config
37
+ self.config = {
38
+ "in_channels": in_channels,
39
+ "pooling_method": fusion_strategy,
40
+ "num_layers": num_layers,
41
+ "num_attention_heads": num_attention_heads,
42
+ "inner_dim": inner_dim,
43
+ "dropout": dropout,
44
+ "norm_num_groups": norm_num_groups,
45
+ "activation_fn": activation_fn,
46
+ "masking_strategy": masking_strategy,
47
+ "num_cls_tokens": num_cls_tokens
48
+ }
49
+
50
+
51
+ self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True)
52
+ if self.with_in_projection:
53
+ self.in_proj = nn.Linear(in_channels, inner_dim)
54
+ self.transformer_blocks = nn.ModuleList(
55
+ [
56
+ BasicTransformerBlock(
57
+ self.inner_dim,
58
+ num_attention_heads=num_attention_heads,
59
+ attention_head_dim=self.attention_head_dim,
60
+ dropout=dropout,
61
+ activation_fn=activation_fn,
62
+ norm_type="layer_norm",
63
+ num_embeds_ada_norm=None,
64
+ attention_bias=False,
65
+ double_self_attention=True,
66
+ norm_elementwise_affine=True,
67
+ positional_embeddings=None,
68
+ num_positional_embeddings=None,
69
+ )
70
+ for d in range(num_layers)
71
+ ]
72
+ )
73
+ if self.with_out_projection:
74
+ self.proj_out = nn.Linear(inner_dim, in_channels)
75
+
76
+ if self.masking_strategy == "compression" or self.masking_strategy == "all":
77
+ # create learnable CLS tokens
78
+ assert num_cls_tokens > 0, "Number of CLS tokens must be provided for masking strategy compression"
79
+ self.cls_tokens = nn.Parameter(torch.randn(1,1, num_cls_tokens, inner_dim)) # B, N, L, C
80
+
81
+ def save_config_json(self, path):
82
+ json.dump(self.config, open(path, "w"))
83
+
84
+ def prepare_attention_mask(self, image_masks, text_masks, LI, LT, masking_strategy="compression"):
85
+ """
86
+ Args:
87
+ image_masks: list of lists, of shape (B, N)
88
+ text_masks: list of lists of shape (B, N)
89
+ LI: int, number of image tokens
90
+ LT: int, number of text tokens
91
+ """
92
+ B = len(image_masks)
93
+ N = len(image_masks[0])
94
+ # create the attention mask
95
+ if masking_strategy == "pair":
96
+ """
97
+ Paired information can only attend to each other. Basically a giant diagonal matrix.
98
+ """
99
+ # since each pair can only attend to himself, we can collapse the pairs in the batch dimension and have a True mask
100
+ attention_mask = torch.ones(B*N, (LI+LT), (LI+LT), dtype=torch.bool)
101
+ elif masking_strategy == "modality":
102
+ """
103
+ Each sketch can attend to all other sketches (except padding ones). Same with text.
104
+ Fusion is done on a modality-level, not pair-level.
105
+ """
106
+ # the attention mask is a grid with 2 repeating rows and columns
107
+ rep_row = torch.ones(((LI+LT), (LI+LT)), dtype=torch.bool)
108
+ # prevent image tokens (first LI) to attend to text tokens (last LT)
109
+ rep_row[:LI, LI:] = False
110
+ # and vice versa
111
+ rep_row[LI:, :LI] = False
112
+ # repeat the column N times
113
+ mask = rep_row.repeat(N, N)
114
+ # repeat the mask for each batch element
115
+ attention_mask = mask.repeat(B, 1, 1)
116
+ # each item has different masks
117
+ for b in range(B):
118
+ for m in range(N):
119
+ # find from which item the padding starts
120
+ if not image_masks[b][m]:
121
+ attention_mask[b, :, m*(LI+LT):] = False
122
+ break
123
+ elif masking_strategy == "compression":
124
+ """
125
+ Paired information can only attend to each other and the added cls_tokens. Basically a giant diagonal matrix.
126
+ This is the default LOTS behavior.
127
+ """
128
+ # same as v1, but you have extra self.num_cls_tokens tokens per item
129
+ attention_mask = torch.zeros(B, N*(LI+LT+self.num_cls_tokens), N*(LI+LT+self.num_cls_tokens), dtype=torch.bool)
130
+ # each item has different masks
131
+ for b in range(B):
132
+ for i in range(N):
133
+ # allow the image tokens and text tokens of the same pair to attend to each other
134
+ attention_mask[b, i*(LI+LT+self.num_cls_tokens):(i+1)*(LI+LT+self.num_cls_tokens), i*(LI+LT+self.num_cls_tokens):(i+1)*(LI+LT+self.num_cls_tokens)] = True
135
+ elif masking_strategy == "all":
136
+ "all tokens, including cls, can attend to all other tokens, except padding"
137
+ attention_mask = torch.ones(B, N*(LI+LT+self.num_cls_tokens), N*(LI+LT+self.num_cls_tokens), dtype=torch.bool)
138
+ for b in range(B):
139
+ for m in range(N):
140
+ # find from which item the padding starts
141
+ if not image_masks[b][m]:
142
+ attention_mask[b, :, m*(LI+LT+self.num_cls_tokens):] = False
143
+ break
144
+ else:
145
+ raise NotImplementedError("Masking strategy not implemented")
146
+ return attention_mask
147
+
148
+ def forward(self, image_embeds, image_masks, text_embeds, text_masks, timestep=None):
149
+ """
150
+ Args:
151
+ image_embeds: torch.Tensor of shape (batch_size, sequence_length, in_channels)
152
+ image_masks: torch.Tensor of shape (batch_size, sequence_length)
153
+ text_embeds: torch.Tensor of shape (batch_size, sequence_length, in_channels)
154
+ text_masks: torch.Tensor of shape (batch_size, sequence_length)
155
+ """
156
+ B, N, LI, C = image_embeds.shape
157
+ _, _, LT, _ = text_embeds.shape
158
+ # prepare masks
159
+ attention_masks = []
160
+ for l in range(self.num_layers):
161
+ if self.masking_strategy == "modality":
162
+ attention_masks.append(self.prepare_attention_mask(image_masks, text_masks, LI, LT, masking_strategy="modality").to(image_embeds.device))
163
+ elif self.masking_strategy == "pair":
164
+ attention_masks.append(self.prepare_attention_mask(image_masks, text_masks, LI, LT, masking_strategy="pair").to(image_embeds.device))
165
+ elif self.masking_strategy == "compression":
166
+ attention_masks.append(self.prepare_attention_mask(image_masks, text_masks, LI, LT, masking_strategy="compression").to(image_embeds.device))
167
+ elif self.masking_strategy == "all":
168
+ attention_masks.append(self.prepare_attention_mask(image_masks, text_masks, LI, LT, masking_strategy="all").to(image_embeds.device))
169
+ else:
170
+ raise NotImplementedError("Masking strategy not implemented")
171
+
172
+ # concat image and text
173
+ if self.masking_strategy == "compression" or self.masking_strategy == "all":
174
+ # with cls tokens
175
+ batch_cls_tokens = self.cls_tokens.repeat(B, N, 1, 1)
176
+ x = torch.cat([batch_cls_tokens, image_embeds, text_embeds], dim=2)
177
+ else:
178
+ x = torch.cat([image_embeds, text_embeds], dim=2)
179
+ _, _, L, C = x.shape
180
+ if self.masking_strategy == "pair":
181
+ # collapse dim 0 and 1 (pairs as batch items)
182
+ x = x.reshape(B*N, L, C)
183
+ else:
184
+ # collapse dim 1 and 2
185
+ x = x.reshape(B, N*L, C)
186
+
187
+ # normalize the channels
188
+ x = x.permute(0, 2, 1) # B, C, N*L
189
+ x = self.norm(x)
190
+ x = x.permute(0, 2, 1) # B, N*L, C
191
+ # projection if necessary
192
+ if self.with_in_projection:
193
+ x = self.in_proj(x)
194
+ for attn_mask, block in zip(attention_masks, self.transformer_blocks):
195
+ x = block(hidden_states=x, attention_mask=attn_mask, encoder_attention_mask=attn_mask, timestep=timestep)
196
+ # this returns a B, N*L, C tensor
197
+ if self.with_out_projection:
198
+ x = self.proj_out(x)
199
+ # restore to original dimensions
200
+ x = x.reshape(B, N, L, C)
201
+ # x = x + residual # NOTE: do we want residuals?
202
+ if self.masking_strategy == "compression" or self.masking_strategy == "all":
203
+ x = x[:, :, :self.num_cls_tokens, :]
204
+ # do pooling keeping in mind the masking
205
+ if self.fusion_strategy == "mean":
206
+ pair_embeds = []
207
+ for b in range(B):
208
+ # select only items that are not masked
209
+ selector = torch.ones((N), dtype=torch.bool).to(x.device)
210
+ for i in range(N):
211
+ if not image_masks[b][i]:
212
+ selector[i] = False
213
+ item_embeds = x[b, selector, :, :]
214
+ # do the mean pooling
215
+ item_embeds = item_embeds.mean(dim=0, keepdim=False)
216
+ pair_embeds.append(item_embeds)
217
+ pair_embeds = torch.stack(pair_embeds)
218
+ # pair_embeds: B, L, C
219
+ elif self.fusion_strategy == "deferred":
220
+ pair_embeds = x.reshape(B, -1, C) # B, N*L, C
221
+ # the padding items are masked in the unet cross_attn outside of this module
222
+
223
+ else:
224
+ raise NotImplementedError("Pooling method not implemented")
225
+ return pair_embeds
226
+
src/lots/projectors.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ class TokenProjector(torch.nn.Module):
4
+ """
5
+ Projection Model
6
+ Takes in input embeddings of shape (BS, L, embeddings_dim) and projects them to (BS, L, cross_attention_dim)
7
+ """
8
+
9
+ def __init__(self, embeddings_dim=1024, cross_attention_dim=1024):
10
+ super().__init__()
11
+ self.cross_attention_dim = cross_attention_dim
12
+ self.proj = torch.nn.Linear(embeddings_dim, cross_attention_dim)
13
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
14
+
15
+ def forward(self, token_embeds):
16
+ """
17
+ token_embeds: torch.Tensor of shape (BS, L, embeddings_dim)
18
+
19
+ returns: torch.Tensor of shape (BS, L, attention_dim)
20
+ """
21
+ # image embeds in shape (BS, L, C)
22
+ embeds = token_embeds
23
+ projected_tokens = self.proj(embeds)
24
+ projected_tokens = self.norm(projected_tokens)
25
+ return projected_tokens
26
+
27
+ class SequenceProjModel(torch.nn.Module):
28
+ """
29
+ Projection Model
30
+ Extends a single token to a sequence of tokens
31
+ """
32
+
33
+ def __init__(self, cross_attention_dim=1024, embeddings_dim=1024, extra_context_tokens=4):
34
+ super().__init__()
35
+
36
+ self.generator = None
37
+ self.cross_attention_dim = cross_attention_dim
38
+ self.extra_context_tokens = extra_context_tokens
39
+ self.proj = torch.nn.Linear(embeddings_dim, self.extra_context_tokens * cross_attention_dim)
40
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
41
+
42
+ def forward(self, token_embeds):
43
+ embeds = token_embeds
44
+ B, L, C = embeds.shape
45
+ extra_context_tokens = self.proj(embeds).reshape(
46
+ B, L, self.extra_context_tokens, self.cross_attention_dim
47
+ )
48
+ extra_context_tokens = self.norm(extra_context_tokens)
49
+ return extra_context_tokens
src/sketchy/__init__.py ADDED
File without changes
src/sketchy/sketchy_dataset.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fashionpedia.fp import Fashionpedia
2
+ from PIL import Image, ImageOps
3
+ import os
4
+ import torch
5
+ from torch.utils.data import Dataset
6
+
7
+ class SketchyDataset(Dataset):
8
+
9
+ def __init__(self, dataset_root, split='train',
10
+ load_img=False,
11
+ load_global_sketch=False,
12
+ load_local_sketch=False,
13
+ img_size=512,
14
+ img_transforms=None,
15
+ global_sketch_transforms=None,
16
+ local_sketch_transforms=None,
17
+ text_tokenizers = None,
18
+ with_shoes=False, # shoes are not included by default
19
+ concat_locals=True, # concatenate local descriptions to create the global description
20
+ compose_global_sketch=True, # compose the global sketch from the local sketches instead of using the pre-computed one
21
+ ):
22
+ self.root = dataset_root
23
+ self.split = split
24
+ self.load_img = load_img
25
+ self.load_global_sketch = load_global_sketch
26
+ self.load_local_sketch = load_local_sketch
27
+ self.img_size = img_size
28
+ self.img_transforms = img_transforms
29
+ self.global_sketch_transforms = global_sketch_transforms
30
+ self.local_sketch_transforms = local_sketch_transforms
31
+ self.text_tokenizers = text_tokenizers
32
+ self.concat_locals = concat_locals
33
+ self.with_shoes = with_shoes
34
+ self.compose_global_sketch = compose_global_sketch
35
+
36
+ if self.compose_global_sketch:
37
+ assert load_global_sketch and load_local_sketch, "Need to load both global and local sketches to compose the global sketch"
38
+
39
+ self.json_path = os.path.join(self.root, f"{self.split}_sketchy.json")
40
+
41
+ self.init_dataset(self.json_path)
42
+
43
+ def init_dataset(self, json_path):
44
+ self.fp = Fashionpedia(json_path)
45
+ # go through the dataset and remove the shoes
46
+ if not self.with_shoes:
47
+ self.removeShoes()
48
+ # get all images ids
49
+ self.img_ids = list(self.fp.getImgIds())
50
+
51
+ def collate_fn(self, batch):
52
+ """ Use this when you are ok with having lists of different sizes in the batch"""
53
+ return_dict = {}
54
+ for key in batch[0].keys():
55
+ if key == 'image':
56
+ images = [d[key] for d in batch]
57
+ if self.img_transforms is not None:
58
+ images = torch.stack(images)
59
+ return_dict['image'] = images
60
+ else:
61
+ return_dict[key] = [d[key] for d in batch]
62
+ return return_dict
63
+
64
+ def __len__(self):
65
+ return len(self.img_ids)
66
+
67
+ def __getitem__(self, idx):
68
+ return_dict = {}
69
+ img_id = self.img_ids[idx]
70
+ return_dict['image_id'] = img_id
71
+ img_data = self.fp.loadImgs(img_id)[0]
72
+ return_dict['img_data'] = img_data
73
+ img_path = os.path.join(self.root, self.split, 'images', str(img_id), img_data['file_name'])
74
+ global_sketch_path = os.path.join(self.root, self.split, 'full_sketches', str(img_id), str(img_id) + '.png')
75
+ annotations = self.fp.loadAnns(self.fp.getAnnIds(img_id))
76
+ return_dict['annotations'] = annotations
77
+ return_dict['global_sketch_path'] = global_sketch_path
78
+
79
+ return_dict['local_descriptions'] = [ann['description'].strip().lower() for ann in annotations]
80
+ return_dict['local_descriptions_ann_ids'] = [ann['id'] for ann in annotations]
81
+ if self.concat_locals:
82
+ return_dict['global_description'] = ". ".join(return_dict['local_descriptions']).strip().lower()
83
+
84
+ return_dict['local_sketches_paths'] = [os.path.join(self.root, self.split, 'partial_sketches', str(img_id), str(ann['id']) + '.png') for ann in annotations]
85
+ if self.load_local_sketch:
86
+ local_sketches = [Image.open(local_sketch_path).resize((self.img_size, self.img_size)) for local_sketch_path in return_dict['local_sketches_paths']]
87
+ if self.compose_global_sketch:
88
+
89
+ global_sketch = Image.new("L", (self.img_size, self.img_size), color=0)
90
+ for local_sketch in local_sketches:
91
+ local_sketch = ImageOps.invert(local_sketch.convert("L"))
92
+ global_sketch.paste(local_sketch, (0, 0), local_sketch)
93
+ global_sketch = ImageOps.invert(global_sketch)
94
+ global_sketch = global_sketch.convert("RGB")
95
+ if self.global_sketch_transforms is not None:
96
+ global_sketch = self.global_sketch_transforms(global_sketch)
97
+ return_dict['global_sketch'] = global_sketch
98
+ local_sketches = [local_sketch.convert("RGB") for local_sketch in local_sketches]
99
+ if self.local_sketch_transforms is not None:
100
+ local_sketches = [self.local_sketch_transforms(local_sketch) for local_sketch in local_sketches]
101
+ return_dict['local_sketches'] = local_sketches
102
+ else:
103
+ return_dict['local_sketches'] = return_dict['local_sketches_paths']
104
+ return_dict['image_path'] = img_path
105
+ if self.load_img:
106
+ image = Image.open(img_path).convert("RGB")
107
+ image = image.resize((self.img_size, self.img_size))
108
+ if self.img_transforms is not None:
109
+ image = self.img_transforms(image)
110
+ return_dict['image'] = image
111
+ else:
112
+ return_dict['image'] = img_path
113
+
114
+ if not self.compose_global_sketch:
115
+ if self.load_global_sketch:
116
+ global_sketch = Image.open(global_sketch_path).convert("RGB")
117
+ global_sketch = global_sketch.resize((self.img_size, self.img_size))
118
+ if self.global_sketch_transforms is not None:
119
+ global_sketch = self.global_sketch_transforms(global_sketch)
120
+ return_dict['global_sketch'] = global_sketch
121
+ else:
122
+ return_dict['global_sketch'] = global_sketch_path
123
+
124
+ # process text with tokenizers if needed
125
+ if self.text_tokenizers is not None:
126
+ # first global description
127
+ text = return_dict['global_description']
128
+ if len(self.text_tokenizers) == 1:
129
+ text_input_ids = self.text_tokenizers[0](
130
+ text,
131
+ max_length=self.text_tokenizers[0].model_max_length,
132
+ padding="max_length",
133
+ truncation=True,
134
+ return_tensors="pt"
135
+ ).input_ids
136
+ return_dict['global_description_ids'] = text_input_ids
137
+
138
+ # then local descriptions
139
+ local_descriptions = return_dict['local_descriptions']
140
+ local_text_ids = []
141
+ for text in local_descriptions:
142
+ text_input_ids = self.text_tokenizers[0](
143
+ text,
144
+ max_length=self.text_tokenizers[0].model_max_length,
145
+ padding="max_length",
146
+ truncation=True,
147
+ return_tensors="pt"
148
+ ).input_ids
149
+ local_text_ids.append(text_input_ids)
150
+ return_dict['local_descriptions_ids'] = local_text_ids
151
+ else:
152
+ # get text and tokenize
153
+ text_input_ids = self.text_tokenizers[0](
154
+ text,
155
+ max_length=self.text_tokenizers[0].model_max_length,
156
+ padding="max_length",
157
+ truncation=True,
158
+ return_tensors="pt"
159
+ ).input_ids
160
+
161
+ text_input_ids_2 =self.text_tokenizers[1](
162
+ text,
163
+ max_length=self.text_tokenizers[1].model_max_length,
164
+ padding="max_length",
165
+ truncation=True,
166
+ return_tensors="pt"
167
+ ).input_ids
168
+ return_dict['global_description_ids'] = text_input_ids
169
+ return_dict['global_description_ids_2'] = text_input_ids_2
170
+
171
+ # then local descriptions
172
+ local_descriptions = return_dict['local_descriptions']
173
+ local_text_ids = []
174
+ for text in local_descriptions:
175
+ text_input_ids = self.text_tokenizers[0](
176
+ text,
177
+ max_length=self.text_tokenizers[0].model_max_length,
178
+ padding="max_length",
179
+ truncation=True,
180
+ return_tensors="pt"
181
+ ).input_ids
182
+ local_text_ids.append(text_input_ids)
183
+ return_dict['local_descriptions_ids'] = local_text_ids
184
+ local_text_ids_2 = []
185
+ for text in local_descriptions:
186
+ text_input_ids_2 = self.text_tokenizers[1](
187
+ text,
188
+ max_length=self.text_tokenizers[1].model_max_length,
189
+ padding="max_length",
190
+ truncation=True,
191
+ return_tensors="pt"
192
+ ).input_ids
193
+ local_text_ids_2.append(text_input_ids_2)
194
+ return_dict['local_descriptions_ids_2'] = local_text_ids_2
195
+ return return_dict
196
+
197
+ def ann2Mask(self, ann):
198
+ mask = self.fp.annToMask(ann)*255
199
+ mask = Image.fromarray(mask)
200
+ mask = ImageOps.contain(mask, (ann['final_width'], ann['final_height']))
201
+ padding = tuple(ann['padding'])
202
+ mask = ImageOps.expand(mask, padding, fill='black')
203
+ mask = mask.resize((self.img_size, self.img_size))
204
+ return mask
205
+
206
+ def removeShoes(self):
207
+ # get the annotations from the fp object
208
+ new_annotations = []
209
+ for ann_id, ann in self.fp.anns.items():
210
+ # remove all annotations with category_name "shoe"
211
+ if ann['category_name'] != 'shoe':
212
+ new_annotations.append(ann.copy())
213
+ self.fp.dataset['annotations'] = new_annotations
214
+ # re-create the index
215
+ self.fp.createIndex()
216
+ # get all images ids
217
+ self.img_ids = list(self.fp.getImgIds())
218
+ # remove images that have no annotations
219
+ new_img_data = []
220
+ for img_id, img_data in self.fp.imgs.items():
221
+ anns = self.fp.loadAnns(self.fp.getAnnIds(img_id))
222
+ if len(anns) > 0:
223
+ new_img_data.append(img_data.copy())
224
+ self.fp.dataset['images'] = new_img_data
225
+ # re-create the index
226
+ self.fp.createIndex()
src/utils/__init__.py ADDED
File without changes
src/utils/dinov2_utils.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoImageProcessor, AutoModel
2
+ import torch
3
+
4
+ def get_dinov2_model(model_type="vits14"):
5
+ """Get DINOv2 model that returns full hidden states"""
6
+ model_map = {
7
+ 'vits14': 'facebook/dinov2-small',
8
+ 'vitb14': 'facebook/dinov2-base',
9
+ 'vitl14': 'facebook/dinov2-large',
10
+ 'vitg14': 'facebook/dinov2-giant'
11
+ }
12
+
13
+ model = AutoModel.from_pretrained(model_map[model_type])
14
+ return model
15
+
16
+ def get_feature_dim(model_type):
17
+ """Get feature dimension based on model type"""
18
+ dims = {
19
+ 'vits14': 384,
20
+ 'vitb14': 768,
21
+ 'vitl14': 1024,
22
+ 'vitg14': 1536
23
+ }
24
+ return dims[model_type]
25
+
26
+ def extract_features(image_features, pooling_type='cls'):
27
+ """Extract features using different pooling strategies"""
28
+ # image_features should be last_hidden_states with shape [batch_size, num_patches+1, hidden_dim]
29
+ batch_size = image_features.shape[0]
30
+
31
+ if pooling_type == 'cls':
32
+ return image_features[:, 0] # get CLS token
33
+ elif pooling_type == 'avg':
34
+ return torch.mean(image_features[:, 1:], dim=1) # average over patches
35
+ elif pooling_type == 'max':
36
+ return torch.max(image_features[:, 1:], dim=1)[0] # max over patches
37
+ elif pooling_type == 'cls_max':
38
+ cls_token = image_features[:, 0]
39
+ max_pool = torch.max(image_features[:, 1:], dim=1)[0]
40
+ return torch.cat([cls_token, max_pool], dim=-1)
41
+ elif pooling_type == 'cls_avg':
42
+ cls_token = image_features[:, 0]
43
+ avg_pool = torch.mean(image_features[:, 1:], dim=1)
44
+ return torch.cat([cls_token, avg_pool], dim=-1)
45
+ else:
46
+ raise ValueError(f"Unknown pooling type: {pooling_type}")
47
+
48
+ def get_pooling_dim(base_dim, pooling_type):
49
+ """Returns the final feature dimension according to the pooling type"""
50
+ if pooling_type in ['cls', 'avg', 'max']:
51
+ return base_dim
52
+ elif pooling_type in ['cls_max', 'cls_avg']:
53
+ return base_dim * 2
54
+ else:
55
+ raise ValueError(f"Unknown pooling type: {pooling_type}")
src/utils/script_utils.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import numpy as np
3
+ import torch
4
+ from transformers import PretrainedConfig
5
+ import torch.nn.functional as F
6
+
7
+ def set_seed(seed):
8
+ random.seed(seed)
9
+ np.random.seed(seed)
10
+ torch.manual_seed(seed)
11
+ torch.cuda.manual_seed_all(seed)
12
+
13
+ def import_model_class_from_model_name_or_path(
14
+ pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
15
+ ):
16
+ text_encoder_config = PretrainedConfig.from_pretrained(
17
+ pretrained_model_name_or_path, subfolder=subfolder, revision=revision
18
+ )
19
+ model_class = text_encoder_config.architectures[0]
20
+
21
+ if model_class == "CLIPTextModel":
22
+ from transformers import CLIPTextModel
23
+
24
+ return CLIPTextModel
25
+ elif model_class == "CLIPTextModelWithProjection":
26
+ from transformers import CLIPTextModelWithProjection
27
+
28
+ return CLIPTextModelWithProjection
29
+ else:
30
+ raise ValueError(f"{model_class} is not supported.")
31
+
32
+ def encode_prompt(prompt_batch, text_encoders, tokenizers, proportion_empty_prompts=0):
33
+ prompt_embeds_list = []
34
+ captions = []
35
+ if type(prompt_batch) == str:
36
+ prompt_batch = [prompt_batch]
37
+ for caption in prompt_batch:
38
+ if random.random() < proportion_empty_prompts:
39
+ # randomly replace some captions with empty ones
40
+ captions.append("")
41
+ elif isinstance(caption, str):
42
+ # keep the caption
43
+ captions.append(caption)
44
+ elif isinstance(caption, (list, np.ndarray)):
45
+ # This happens when passing multiple captions for the same image
46
+ raise ValueError("Multiple captions were passed in the wrong format.")
47
+ else:
48
+ raise ValueError("Prompt is in the wrong format.")
49
+
50
+ with torch.no_grad():
51
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
52
+ text_inputs = tokenizer(
53
+ captions,
54
+ padding="max_length",
55
+ max_length=tokenizer.model_max_length,
56
+ truncation=True,
57
+ return_tensors="pt",
58
+ )
59
+ text_input_ids = text_inputs.input_ids
60
+ untruncated_ids = tokenizer(captions, padding="longest", return_tensors="pt").input_ids
61
+
62
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
63
+ text_input_ids, untruncated_ids
64
+ ):
65
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
66
+ print(
67
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
68
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
69
+ )
70
+
71
+ prompt_embeds = text_encoder(
72
+ text_input_ids.to(text_encoder.device),
73
+ output_hidden_states=True,
74
+ )
75
+
76
+ # We are only interested in the pooled output of the final text encoder
77
+ pooled_prompt_embeds = prompt_embeds[0]
78
+ prompt_embeds = prompt_embeds.hidden_states[-2]
79
+ bs_embed, seq_len, _ = prompt_embeds.shape
80
+ prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
81
+ prompt_embeds_list.append(prompt_embeds)
82
+
83
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
84
+ pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
85
+ return prompt_embeds, pooled_prompt_embeds
86
+
87
+ def is_torch2_available():
88
+ return hasattr(F, "scaled_dot_product_attention")
89
+
90
+ def get_generator(seed, device):
91
+
92
+ if seed is not None:
93
+ if isinstance(seed, list):
94
+ generator = [torch.Generator(device).manual_seed(seed_item) for seed_item in seed]
95
+ else:
96
+ generator = torch.Generator(device).manual_seed(seed)
97
+ else:
98
+ generator = None
99
+
100
+ return generator
static/LOTS.png ADDED

Git LFS Details

  • SHA256: 7f5f7a616a1856458a8ab11f6b8ba5b3f1a3a1121a9a4a52f5f96c1f080716a1
  • Pointer size: 131 Bytes
  • Size of remote file: 271 kB