Skip to content

Commit 9f281db

Browse files
Initial commit
0 parents  commit 9f281db

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

95 files changed

+4799
-0
lines changed

Diff for: .gitignore

+163
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
*.py,cover
50+
.hypothesis/
51+
.pytest_cache/
52+
cover/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
.pybuilder/
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
# For a library or package, you might want to ignore these files since the code is
87+
# intended to run in multiple environments; otherwise, check them in:
88+
# .python-version
89+
90+
# pipenv
91+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
93+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
94+
# install all needed dependencies.
95+
#Pipfile.lock
96+
97+
# poetry
98+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99+
# This is especially recommended for binary packages to ensure reproducibility, and is more
100+
# commonly ignored for libraries.
101+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102+
#poetry.lock
103+
104+
# pdm
105+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106+
#pdm.lock
107+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108+
# in version control.
109+
# https://pdm.fming.dev/#use-with-ide
110+
.pdm.toml
111+
112+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113+
__pypackages__/
114+
115+
# Celery stuff
116+
celerybeat-schedule
117+
celerybeat.pid
118+
119+
# SageMath parsed files
120+
*.sage.py
121+
122+
# Environments
123+
.env
124+
.venv
125+
env/
126+
venv/
127+
ENV/
128+
env.bak/
129+
venv.bak/
130+
131+
# Spyder project settings
132+
.spyderproject
133+
.spyproject
134+
135+
# Rope project settings
136+
.ropeproject
137+
138+
# mkdocs documentation
139+
/site
140+
141+
# mypy
142+
.mypy_cache/
143+
.dmypy.json
144+
dmypy.json
145+
146+
# Pyre type checker
147+
.pyre/
148+
149+
# pytype static type analyzer
150+
.pytype/
151+
152+
# Cython debug symbols
153+
cython_debug/
154+
155+
# PyCharm
156+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158+
# and can be added to the global gitignore or merged into this file. For a more nuclear
159+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
160+
#.idea/
161+
162+
# Hydra output dir
163+
outputs/

Diff for: LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2024 CompVis - Computer Vision and Learning LMU Munich
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

Diff for: README.md

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Fine-Grained Subject-Specific Attribute Expression Control in T2I Models
2+
3+
[![Project Page](https://img.shields.io/badge/Project-Page-blue)](https://compvis.github.io/attribute-control/)
4+
[![Paper](https://img.shields.io/badge/arXiv-PDF-b31b1b)](https://arxiv.org/abs/TODO)
5+
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/CompVis/attribute-control/blob/main/notebooks/inference_sdxl_colab.ipynb)
6+
7+
This repository contains an implementation of the paper "Continuous, Subject-Specific Attribute Control in T2I Models by Identifying Semantic Directions".
8+
9+
[Stefan Andreas Baumann](https://stefan-baumann.eu/), [Felix Krause](https://www.linkedin.com/in/felixmkrause/), [Michael Neumayr](https://www.linkedin.com/in/michaelneumayr/), [Nick Stracke](https://de.linkedin.com/in/nick-stracke), [Vincent Tao Hu](https://taohu.me/), [Björn Ommer](https://ommer-lab.com/people/ommer/)
10+
11+
We present a simple, straight-forward method for enabling fine-grained control over attribute expression in T2I (diffusion) models in a subject-specific manner.
12+
We identify meaningful directions in the tokenwise prompt embedding space that enable modulating single attributes for specific subjects without adapting the T2I model.
13+
14+
![teaser](./docs/static/images/teaser.png)
15+
16+
## 🚀 Usage
17+
### Setup
18+
Just clone the repo and install the requirements via `pip install -r requirements.txt`, then you're ready to go. For usage, see the examples below, everything else that's needed (model checkpoints) will be downloaded automatically.
19+
20+
### Inference
21+
For inference, just start with one of the notebook at `notebooks` for a minimal example.
22+
23+
We provide a range of learned deltas for SDXL at `pretrained_deltas`. These can also be used for models such as SD 1.5 or LDM3D by just loading them as usual .
24+
25+
### Creating new Attribute Deltas
26+
When creating deltas for new attributes, start by creating a config for them akin to `configs/prompts/people/age.yaml`. There are multiple entries of base prompts that correspond to the attribute in a neutral, "negative", and "positive" direction. Please make sure to use the same noun for all the prompts per entry and specify it as the `pattern_target`.
27+
You can also specify a list of prefixes that contain various other words that will be added before the main prompt to help obtain more robust deltas. The syntax used finds all sets of words enclosed in braces (e.g., `{young,old}`) and then generates all combinations of words in the braces.
28+
29+
#### Learning-based Method
30+
The best method to obtain deltas is the learning-based method, although it takes substantially longer than the naive method (see below)
31+
32+
To obtain a delta with the naive method, use:
33+
```shell
34+
python learn_delta.py device=cuda:0 model=sdxl prompts=people/age
35+
```
36+
This will save the delta at `outputs/learn_delta/people/age/runs/<date>/<time>/checkpoints/delta.pt`, which you can then directly use as shown in the example notebooks.
37+
38+
#### Naive CLIP Difference Method
39+
The simplest method to obtain deltas is the naive CLIP difference-based method. With it, you can obtain a delta in a few seconds on a decent GPU. It is substantially worse than the proper learned method though.
40+
41+
To obtain a delta with the naive method, use (same arguments as for the learning-based method):
42+
```shell
43+
python learn_delta_naive_clip.py device=cuda:0 model=sdxl prompts=people/age
44+
```
45+
This will save the delta at `outputs/learn_delta_naive_clip/people/age/runs/<date>/<time>/checkpoints/delta.pt`, which you can then directly use as shown in the example notebooks.
46+
47+
## Future Plans
48+
This repository contains a clean re-implementation of the code used to create our paper. Therefore, it is still missing some non-essential features. We are planning to add these in the near future.
49+
50+
We also hope to add support for inference & delta learning with more models in the future.
51+
52+
If you have any suggestions as to what you'd like to see, let us know in the issues!
53+
54+
We also welcome external contributions! Additionally, if you build something cool with this, let us know so that we can add a link here.
55+
56+
## 🎓 Citation
57+
58+
If you use this codebase or otherwise found our work valuable, please cite our paper:
59+
60+
```bibtex
61+
@misc{baumann2024attributecontrol,
62+
title={Continuous, Subject-Specific Attribute Control in T2I Models by Identifying Semantic Directions},
63+
author={Baumann, Stefan Andreas and Krause, Felix and Neumayr, Michael and Stracke, Nick and Hu, Vincent Tao and Ommer, Bj\"orn},
64+
year={2024},
65+
archivePrefix={arXiv},
66+
}
67+
```

Diff for: attribute_control/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from . import utils
2+
from .base import PromptEmbedding, EmbeddingDelta

Diff for: attribute_control/base.py

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from __future__ import annotations
2+
3+
from dataclasses import dataclass, field
4+
from typing import Tuple, Dict, List
5+
import torch
6+
from torch import nn
7+
from jaxtyping import Float
8+
9+
10+
@dataclass
11+
class PromptEmbedding:
12+
prompt: str
13+
tokenwise_embeddings: Dict[str, Float[torch.Tensor, 'n d']]
14+
tokenwise_embedding_spans: Dict[str, List[Tuple[int, int]]]
15+
pooled_embeddings: Dict[str, Float[torch.Tensor, 'd']] = field(default_factory=dict)
16+
17+
@staticmethod
18+
def merge(*embs: PromptEmbedding) -> PromptEmbedding:
19+
emb_joined = None
20+
for emb in embs:
21+
if emb_joined is None:
22+
emb_joined = PromptEmbedding(
23+
prompt=emb.prompt,
24+
tokenwise_embeddings={ k: v for k, v in emb.tokenwise_embeddings.items() },
25+
tokenwise_embedding_spans={ k: v for k, v in emb.tokenwise_embedding_spans.items() },
26+
pooled_embeddings={ k: v for k, v in emb.pooled_embeddings.items() },
27+
)
28+
else:
29+
assert emb.prompt == emb_joined.prompt
30+
emb_joined.tokenwise_embeddings = emb_joined.tokenwise_embeddings | emb.tokenwise_embeddings
31+
emb_joined.tokenwise_embedding_spans = emb_joined.tokenwise_embedding_spans | emb.tokenwise_embedding_spans
32+
emb_joined.pooled_embeddings = emb_joined.pooled_embeddings | emb.pooled_embeddings
33+
return emb_joined
34+
35+
def get_tokenwise_mask(self, characterwise_mask: List[bool]) -> Dict[str, List[bool]]:
36+
tokenwise_masks = { }
37+
for k, t_embs, t_spans in ((k, self.tokenwise_embeddings[k], self.tokenwise_embedding_spans[k]) for k in self.tokenwise_embeddings):
38+
token_mask = [False] * len(t_embs)
39+
for i_t, (t_span_start, t_span_end) in enumerate(t_spans):
40+
if t_span_start != t_span_end: # Don't apply to SOS/EOS tokens
41+
m = characterwise_mask[t_span_start:t_span_end]
42+
assert all(m) or not any(m), 'Inconsistent mask'
43+
if all(m):
44+
token_mask[i_t] = True
45+
tokenwise_masks[k] = token_mask
46+
return tokenwise_masks
47+
48+
49+
class EmbeddingDelta(nn.Module):
50+
def __init__(self, dims: Dict[str, int]) -> None:
51+
super().__init__()
52+
self.tokenwise_delta = nn.ParameterDict({ k: nn.Parameter(torch.zeros(d), requires_grad=True) for k, d in dims.items() })
53+
54+
def apply(self, emb: PromptEmbedding, characterwise_mask: List[bool], alpha: float = 1.) -> PromptEmbedding:
55+
tokenwise_embeddings = { }
56+
matching_keys = [k for k in self.tokenwise_delta if k in emb.tokenwise_embeddings]
57+
assert len(matching_keys) > 0, f'Cannot apply delta if no embeddings match. Embeddings present in delta: {[k for k in self.tokenwise_delta]}. Embeddings present in embedding: {[k for k in emb.tokenwise_embeddings]}.'
58+
for k, t_embs, t_spans in ((k, emb.tokenwise_embeddings[k], emb.tokenwise_embedding_spans[k]) for k in matching_keys):
59+
token_mask = [0] * len(t_embs)
60+
for i_t, (t_span_start, t_span_end) in enumerate(t_spans):
61+
if t_span_start != t_span_end: # Don't apply to SOS/EOS tokens
62+
m = characterwise_mask[t_span_start:t_span_end]
63+
assert all(m) or not any(m), 'Inconsistent mask'
64+
if all(m):
65+
token_mask[i_t] = 1
66+
assert sum(token_mask) >= 1, f'No tokens in prompt selected for delta application via characterwise mask.'
67+
tokenwise_embeddings[k] = t_embs + alpha * torch.tensor(token_mask, dtype=t_embs.dtype, device=t_embs.device).unsqueeze(-1) * self.tokenwise_delta[k].unsqueeze(0).to(t_embs.dtype)
68+
return PromptEmbedding(
69+
prompt=emb.prompt,
70+
tokenwise_embeddings=tokenwise_embeddings,
71+
tokenwise_embedding_spans=emb.tokenwise_embedding_spans,
72+
pooled_embeddings=emb.pooled_embeddings
73+
)

Diff for: attribute_control/model/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .model import ModelBase, SD15, SDXL, StableCascade

0 commit comments

Comments
 (0)